auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void triggerTimer(TimerInstance timerInstance) { for (Map.Entry<Timer, DroolsAction> entry : getEventBasedNode().getTimers().entrySet()) { if (entry.getKey().getId() == timerInstance.getTimerId()) { executeAction((Action) entry.getValue().getMetaData("Action")); if (!(timerInstance.getJobHandle() instanceof DefaultJobHandle)) { return; } DefaultTimerJobInstance defaultTimerInstance = (DefaultTimerJobInstance) ((DefaultJobHandle) timerInstance.getJobHandle()).getTimerJobInstance(); if (defaultTimerInstance.getTrigger().hasNextFireTime() == null) { timerInstances.remove(timerInstance.getId()); } return; } } }

Target:
private void triggerTimer(TimerInstance timerInstance) { for (Map.Entry<Timer, DroolsAction> entry : getEventBasedNode().getTimers().entrySet()) { if (entry.getKey().getId() == timerInstance.getTimerId()) { executeAction((Action) entry.getValue().getMetaData("Action")); if (!(timerInstance.getJobHandle() instanceof DefaultJobHandle)) { return; } TimerJobInstance defaultTimerInstance = ((DefaultJobHandle) timerInstance.getJobHandle()).getTimerJobInstance(); if (defaultTimerInstance.getTrigger().hasNextFireTime() == null) { timerInstances.remove(timerInstance.getId()); } return; } } }
Source:
public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException { Set<ByteSequence> cfSet; if (columnFamilies.size() > 0) if (columnFamilies instanceof Set<?>) { cfSet = (Set<ByteSequence>) columnFamilies; } else { cfSet = new HashSet<>(); cfSet.addAll(columnFamilies); } else cfSet = Collections.emptySet(); if (lastUsed != null && cfSet.equals(lastColumnFamilies) && inclusive == lastInclusive) { clear(); for (LocalityGroup lgr : lastUsed) { lgr.getIterator().seek(range, EMPTY_CF_SET, false); addSource(lgr.getIterator()); } } else { if (lastUsed == null) { lastUsed = new ArrayList<LocalityGroup>(lgContext.groups.length); } else { lastUsed.clear(); } lastColumnFamilies = cfSet; lastInclusive = inclusive; seek(this, lgContext, range, columnFamilies, inclusive, lastUsed); } }

Target:
public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException { lgCache = seek(this, lgContext, range, columnFamilies, inclusive, lgCache); }
Source:
public EventBookingDTO recordAttendance(final IsaacEventPageDTO event, final RegisteredUserDTO userDTO, final boolean attended) throws SegueDatabaseException, EventBookingUpdateException { final EventBookingDTO eventBooking = this.bookingPersistenceManager.getBookingByEventIdAndUserId( event.getId(), userDTO.getId()); if (null == eventBooking) { throw new EventBookingUpdateException("Unable to record attendance for booking that doesn't exist."); } BookingStatus attendanceStatus = attended ? BookingStatus.ATTENDED : BookingStatus.ABSENT; if (attendanceStatus.equals(eventBooking.getBookingStatus())) { throw new EventBookingUpdateException("Booking attendance is already registered."); } UserSummaryDTO reservedBy = this.bookingPersistenceManager .getBookingByEventIdAndUserId(event.getId(), userDTO.getId()).getReservedBy(); Long reservedById = reservedBy == null ? null : reservedBy.getId(); EventBookingDTO updatedStatus = this.bookingPersistenceManager.updateBookingStatus(eventBooking.getEventId(), userDTO.getId(), reservedById, attendanceStatus, eventBooking.getAdditionalInformation()); return updatedStatus; }

Target:
public EventBookingDTO recordAttendance(final IsaacEventPageDTO event, final RegisteredUserDTO userDTO, final boolean attended) throws SegueDatabaseException, EventBookingUpdateException { final EventBookingDTO eventBooking = this.bookingPersistenceManager.getBookingByEventIdAndUserId( event.getId(), userDTO.getId()); if (null == eventBooking) { throw new EventBookingUpdateException("Unable to record attendance for booking that doesn't exist."); } BookingStatus attendanceStatus = attended ? BookingStatus.ATTENDED : BookingStatus.ABSENT; if (attendanceStatus.equals(eventBooking.getBookingStatus())) { throw new EventBookingUpdateException("Booking attendance is already registered."); } EventBookingDTO updatedStatus = this.bookingPersistenceManager.updateBookingStatus(eventBooking.getEventId(), userDTO.getId(), attendanceStatus, eventBooking.getAdditionalInformation()); return updatedStatus; }
Source:
private String escapeComma(String s) { if ((s.indexOf(',') < 0) && (s.indexOf('\\') < 0) && s.indexOf('\n') < 0 && s.indexOf('\r') < 0) return s; StringBuffer sb= new StringBuffer(s.length()+10); for (int i= 0; i < s.length(); i++) { char c= s.charAt(i); if (c == ',') sb.append("\\,"); else if (c == '\\') sb.append("\\\\"); else if (c == '\n' || c == '\r') sb.append(" "); else sb.append(c); } return sb.toString(); }

Target:
private String escapeComma(String s) { if ((s.indexOf(',') < 0) && (s.indexOf('\\') < 0)) return s; StringBuffer sb= new StringBuffer(s.length()+10); for (int i= 0; i < s.length(); i++) { char c= s.charAt(i); if (c == ',') sb.append("\\,"); else if (c == '\\') sb.append("\\\\"); else sb.append(c); } return sb.toString(); }
Source:
private void setSameTopic(GerritClient gerritClient, ChangeInfo element) { ListIterator<ChangeInfo> litr; WritableList writeInfoList; ChangeInfo[] sameTopicChangeInfo = null; fSameTopicChangeInfo.clear(); if (element.getTopic() != null) { try { sameTopicChangeInfo = querySameTopic(gerritClient, element.getTopic(), new NullProgressMonitor()); } catch (MalformedURLException e) { EGerritCorePlugin.logError(e.getMessage()); } litr = Arrays.asList(sameTopicChangeInfo).listIterator(); while (litr.hasNext()) { ChangeInfo cur = litr.next(); if (fChangeInfo.getId().compareTo(cur.getId()) != 0) { ChangeInfo item = new ChangeInfo(); item.setChange_id(cur.getId()); item.setSubject(cur.getSubject()); fSameTopicChangeInfo.add(item); } } writeInfoList = new WritableList(fSameTopicChangeInfo, ReviewerInfo.class); tableSameTopicViewer.setInput(writeInfoList); } }

Target:
private void setSameTopic(GerritClient gerritClient, ChangeInfo element) { ListIterator<ChangeInfo> litr; WritableList writeInfoList; ChangeInfo[] sameTopicChangeInfo = null; fSameTopicChangeInfo.clear(); if (element.getTopic() != null) { try { sameTopicChangeInfo = querySameTopic(gerritClient, element.getTopic(), new NullProgressMonitor()); } catch (MalformedURLException e) { EGerritCorePlugin.logError(e.getMessage()); } litr = Arrays.asList(sameTopicChangeInfo).listIterator(); while (litr.hasNext()) { ChangeInfo cur = litr.next(); if (fChangeInfo.getId().compareTo(cur.getId()) != 0) { ChangeInfo item = new ChangeInfo(); item.setChange_id(cur.getChange_id()); item.setSubject(cur.getSubject()); fSameTopicChangeInfo.add(item); } } writeInfoList = new WritableList(fSameTopicChangeInfo, ReviewerInfo.class); tableSameTopicViewer.setInput(writeInfoList); } }
Source:
public Construct exec(Target t, com.laytonsmith.core.environments.Environment environment, Construct... args) throws ConfigRuntimeException { MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], null, t); MCSound sound = MCSound.BREATH; float volume = 1, pitch = 1; if (!(args[1] instanceof CArray)) throw new Exceptions.FormatException("An array was expected but recieved " + args[1], t); CArray sa = (CArray) args[1]; if (sa.containsKey("sound")) { try { sound = MCSound.valueOf(sa.get("sound", t).val().toUpperCase()); } catch (IllegalArgumentException iae) { } } else { throw new Exceptions.FormatException("Sound field was missing.", t); } if (sa.containsKey("volume")) volume = Static.getDouble32(sa.get("volume", t), t); if (sa.containsKey("pitch")) pitch = Static.getDouble32(sa.get("pitch", t), t); if (args.length == 3) { java.util.List<MCPlayer> players = new java.util.ArrayList<MCPlayer>(); if (args[2] instanceof CArray) { for (String key : ((CArray) args[2]).keySet()) players.add(Static.GetPlayer(((CArray) args[2]).get(key, t), t)); } else { players.add(Static.GetPlayer(args[2], t)); } for (MCPlayer p : players) p.playSound(loc, sound, volume, pitch); } else { loc.getWorld().playSound(loc, sound, volume, pitch); } return new CVoid(t); }

Target:
public Construct exec(Target t, com.laytonsmith.core.environments.Environment environment, Construct... args) throws ConfigRuntimeException { MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], null, t); MCSound sound = MCSound.BREATH; float volume = 1, pitch = 1; if (!(args[1] instanceof CArray)) throw new Exceptions.FormatException("An array was expected but recieved " + args[1], t); CArray sa = (CArray) args[1]; if (sa.containsKey("sound")) { try { sound = MCSound.valueOf(sa.get("sound", t).val().toUpperCase()); } catch (IllegalArgumentException iae) { throw new Exceptions.FormatException("Sound name '" + sa.get("sound", t).val() + "' is invalid.", t); } } else { throw new Exceptions.FormatException("Sound field was missing.", t); } if (sa.containsKey("volume")) volume = Static.getDouble32(sa.get("volume", t), t); if (sa.containsKey("pitch")) pitch = Static.getDouble32(sa.get("pitch", t), t); if (args.length == 3) { java.util.List<MCPlayer> players = new java.util.ArrayList<MCPlayer>(); if (args[2] instanceof CArray) { for (String key : ((CArray) args[2]).keySet()) players.add(Static.GetPlayer(((CArray) args[2]).get(key, t), t)); } else { players.add(Static.GetPlayer(args[2], t)); } for (MCPlayer p : players) p.playSound(loc, sound, volume, pitch); } else { loc.getWorld().playSound(loc, sound, volume, pitch); } return new CVoid(t); }
Source:
public void unretireOrderType_shouldUnretireTheGivenUnretiredOrderType() { OrderService orderService = Context.getOrderService(); OrderType orderType = orderService.getOrderType(11); assertTrue(orderType.getRetired()); orderService.unretireOrderType(orderType); orderType = orderService.getOrderType(11); assertFalse(orderType.getRetired()); }

Target:
public void unretireOrderType_shouldUnretireTheGivenUnretiredOrderType() { OrderService orderService = Context.getOrderService(); OrderType orderType = orderService.getOrderType(16); assertTrue(orderType.getRetired()); assertNotNull(orderType.getRetiredBy()); assertNotNull(orderType.getRetireReason()); assertNotNull(orderType.getDateRetired()); orderService.unretireOrderType(orderType); orderType = orderService.getOrderType(16); assertFalse(orderType.getRetired()); assertNull(orderType.getRetiredBy()); assertNull(orderType.getRetireReason()); assertNull(orderType.getDateRetired()); }
Source:
public Object acquireLockIfAvailable(Order order) { if (order == null || order instanceof NullOrderImpl) { if (LOG.isDebugEnabled()) { LOG.debug("Attempted to grab a lock for a NullOrderImpl. Not blocking"); } return order; } boolean lockAcquired = orderService.acquireLock(order); return lockAcquired ? order : null; }

Target:
public Object acquireLockIfAvailable(Order order) { if (order == null || order instanceof NullOrderImpl) { if (LOG.isDebugEnabled()) { LOG.debug("Attempted to grab a lock - order was null or it was a NullOrderImpl. Not blocking"); } return order; } boolean lockAcquired = orderService.acquireLock(order); return lockAcquired ? order : null; }
Source:
public Temporal adjustInto(Temporal temporal) { int dow = temporal.get(DAY_OF_WEEK); switch (dow) { case 6: return temporal.minus(1, DAYS); case 7: return temporal.minus(2, DAYS); default: return temporal; } }

Target:
public Temporal adjustInto(Temporal temporal) { int dow = temporal.get(DAY_OF_WEEK); switch (dow) { case 6: return temporal.plus(2, DAYS); case 5: return temporal.plus(3, DAYS); default: return temporal.plus(1, DAYS); } }
Source:
public ProtocolVersion highestCommon(Collection<Node> nodes) { if (nodes == null || nodes.isEmpty()) { throw new IllegalArgumentException("Expected at least one node"); } SortedSet<CoreProtocolVersion> candidates = new TreeSet<>(); for (CoreProtocolVersion version : CoreProtocolVersion.values()) { if (!version.isBeta()) { candidates.add(version); } } for (Node node : nodes) { CassandraVersion cassandraVersion = node.getCassandraVersion(); if (cassandraVersion == null) { LOG.warn( "[{}] Node reports null Cassandra version, " + "ignoring it from optimal protocol version computation", logPrefix, node.getConnectAddress()); continue; } cassandraVersion = cassandraVersion.nextStable(); if (cassandraVersion.compareTo(CASSANDRA_210) < 0) { throw new IllegalArgumentException( String.format( "Node %s reports Cassandra version %s, " + "but the driver only supports 2.1.0 and above", node.getConnectAddress(), cassandraVersion)); } LOG.debug( "[{}] Node reports Cassandra version {}", logPrefix, node.getConnectAddress(), cassandraVersion); if (cassandraVersion.compareTo(CASSANDRA_220) < 0 && candidates.remove(CoreProtocolVersion.V4)) { LOG.debug("[{}] Excluding protocol V4", logPrefix); } } if (candidates.isEmpty()) { throw new IllegalArgumentException( String.format( "Could not determine a common protocol version, " + "enable DEBUG logs for '%s' for more details", LOG.getName())); } else { return candidates.last(); } }

Target:
public ProtocolVersion highestCommon(Collection<Node> nodes) { if (nodes == null || nodes.isEmpty()) { throw new IllegalArgumentException("Expected at least one node"); } SortedSet<CoreProtocolVersion> candidates = new TreeSet<>(); for (CoreProtocolVersion version : CoreProtocolVersion.values()) { if (!version.isBeta()) { candidates.add(version); } } for (Node node : nodes) { CassandraVersion cassandraVersion = node.getCassandraVersion(); if (cassandraVersion == null) { LOG.warn( "[{}] Node reports null Cassandra version, " + "ignoring it from optimal protocol version computation", logPrefix, node.getConnectAddress()); continue; } cassandraVersion = cassandraVersion.nextStable(); if (cassandraVersion.compareTo(CASSANDRA_210) < 0) { throw new UnsupportedProtocolVersionException( node.getConnectAddress(), String.format( "Node %s reports Cassandra version %s, " + "but the driver only supports 2.1.0 and above", node.getConnectAddress(), cassandraVersion), ImmutableList.of(CoreProtocolVersion.V3, CoreProtocolVersion.V4)); } LOG.debug( "[{}] Node reports Cassandra version {}", logPrefix, node.getConnectAddress(), cassandraVersion); if (cassandraVersion.compareTo(CASSANDRA_220) < 0 && candidates.remove(CoreProtocolVersion.V4)) { LOG.debug("[{}] Excluding protocol V4", logPrefix); } } if (candidates.isEmpty()) { throw new UnsupportedProtocolVersionException( null, String.format( "Could not determine a common protocol version, " + "enable DEBUG logs for '%s' for more details", LOG.getName()), ImmutableList.of(CoreProtocolVersion.V3, CoreProtocolVersion.V4)); } else { return candidates.last(); } }
Source:
@Test public void builtInConvertersAbsentInCloneBuilder() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .build(); assertEquals(retrofit.converterFactories().size() - 1, retrofit.newBuilder().converterFactories().size()); }

Target:
@Test public void builtInConvertersAbsentInCloneBuilder() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .build(); assertEquals(0, retrofit.newBuilder().converterFactories().size()); }
Source:
public static synchronized void storeInteractionForCurrentAppVersion(Context context, String name) { storeRecordForCurrentAppVersion(context, false, name); }

Target:
public static synchronized void storeInteractionForCurrentAppVersion(Context context, String name) { storeRecordForCurrentAppVersion(context, true, name); }
Source:
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { int length = this.applicationContext .getBeanNamesForType(TaskBatchExecutionListener.class).length; if(bean instanceof AbstractJob) { if(length != 1) { throw new IllegalStateException("The application context is required to " + "have exactly 1 instance of the TaskBatchExecutionListner but has " + length); } ((AbstractJob) bean).registerJobExecutionListener( this.applicationContext.getBean(TaskBatchExecutionListener.class)); } return bean; }

Target:
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { int length = this.applicationContext .getBeanNamesForType(TaskBatchExecutionListener.class).length; if(bean instanceof AbstractJob) { if(length != 1) { throw new IllegalStateException("The application context is required to " + "have exactly 1 instance of the TaskBatchExecutionListener but has " + length); } ((AbstractJob) bean).registerJobExecutionListener( this.applicationContext.getBean(TaskBatchExecutionListener.class)); } return bean; }
Source:
public void walk() { Set<Role> roles = RoleMap.this.getRoles(); Iterator<Role> iter = roles.iterator(); while (iter.hasNext()) { Role current = iter.next(); perform(current); if(a) { break; } } }

Target:
public void walk() { Set<Role> roles = RoleMap.this.getRoles(); Iterator<Role> iter = roles.iterator(); while (iter.hasNext()) { Role current = iter.next(); perform(current); if (shouldAbort) { break; } } }
Source:
private void throwIfNotValidMerchantId(JsonNode valueNode, String field) { boolean isValidWorldpayMerchantId = valueNode.textValue().matches("[0-9a-f]{15}"); if(!isValidWorldpayMerchantId) { throw new ValidationException(Collections.singletonList(format("Field [%s] value [%s] does not match that expected for a Worldpay Merchant ID; characters should be within range [0-9a-f]", field, valueNode.asText()))); } }

Target:
private void throwIfNotValidMerchantId(JsonNode valueNode, String field) { boolean isValidWorldpayMerchantId = valueNode.textValue().matches("[0-9a-f]{15}"); if(!isValidWorldpayMerchantId) { throw new ValidationException(Collections.singletonList(format("Field [%s] value [%s] does not match that expected for a Worldpay Merchant ID; should be 15 characters and within range [0-9a-f]", field, valueNode.asText()))); } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository[] repos = getRepositories(event); if (repos.length == 0) return null; Set<Repository> repositories = new HashSet<Repository>(); for (int i = 0; i < repos.length; i++) repositories.add(repos[i]); new PullOperationUI(repositories).start(); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository[] repos = getRepositories(event); if (repos.length == 0) return null; Set<Repository> repositories = new HashSet<Repository>( Arrays.asList(repos)); new PullOperationUI(repositories).start(); return null; }
Source:
public static MaterialDesignIcon getIconForSignState(AccountAgeWitnessService.SignState state) { if (state.equals(AccountAgeWitnessService.SignState.PEER_INITIAL)) return MaterialDesignIcon.CLOCK; return (state.equals(AccountAgeWitnessService.SignState.ARBITRATOR) || state.equals(AccountAgeWitnessService.SignState.PEER_SIGNER)) ? MaterialDesignIcon.APPROVAL : MaterialDesignIcon.ALERT_CIRCLE_OUTLINE; }

Target:
public static MaterialDesignIcon getIconForSignState(AccountAgeWitnessService.SignState state) { if (state.equals(AccountAgeWitnessService.SignState.PEER_INITIAL)) { return MaterialDesignIcon.CLOCK; } return (state.equals(AccountAgeWitnessService.SignState.ARBITRATOR) || state.equals(AccountAgeWitnessService.SignState.PEER_SIGNER)) ? MaterialDesignIcon.APPROVAL : MaterialDesignIcon.ALERT_CIRCLE_OUTLINE; }
Source:
private void init(Configuration config) throws AMQException, JMSException, URISyntaxException { conn = new AMQConnection(config.getString(ConfigKey.AMQP_CONNECT_STRING.toString())); conn.start(); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); dest = new AMQAnyDestination("event"); consumer = sess.createDurableSubscriber(dest, "event"); consumer.setMessageListener(eventMessageListener); log.info("receiver init complete"); }

Target:
private void init(Configuration config) throws AMQException, JMSException, URISyntaxException { conn = new AMQConnection(config.getString(ConfigKey.AMQP_CONNECT_STRING.toString())); conn.start(); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); dest = new AMQAnyDestination("event"); consumer = sess.createDurableSubscriber(dest, "event"); consumer.setMessageListener(eventMessageListener); log.info("Receiver init complete"); }
Source:
public boolean removeAll(final Collection<?> c) { boolean ret = false; for(Object elem : c) { boolean currentRet = remove(elem); if(currentRet) { ret = true; } } return ret; }

Target:
public boolean removeAll(final Collection<?> c) { boolean ret = false; for(final Object elem : c) { boolean currentRet = remove(elem); if(currentRet) { ret = true; } } return ret; }
Source:
private void findMatch() { boolean cont = true; while (cont && matcher.find()) { final FileText text = getFileContents().getText(); final LineColumn start = text.lineColumn(matcher.start()); final int startLine = start.getLine(); final boolean ignore = isIgnore(startLine, text, start); if (!ignore) { matchCount++; if (illegalPattern || checkForDuplicates && matchCount - 1 > duplicateLimit) { errorCount++; logMessage(startLine); } } if (!canContinueValidation()) { cont = false; } } if (!illegalPattern && matchCount == 0) { logMessage(0); } }

Target:
private void findMatch() { final boolean foundMatch = matcher.find(); if (foundMatch) { final FileText text = getFileContents().getText(); final LineColumn start = text.lineColumn(matcher.start()); final int startLine = start.getLine(); final boolean ignore = isIgnore(startLine, text, start); if (!ignore) { matchCount++; if (illegalPattern || checkForDuplicates && matchCount - 1 > duplicateLimit) { errorCount++; logMessage(startLine); } } if (canContinueValidation(ignore)) { findMatch(); } } else if (!illegalPattern && matchCount == 0) { logMessage(0); } }
Source:
ModuleLaunchTask(ModuleResolver moduleResolver, String module, String[] args) { this.moduleResolver = moduleResolver; String[] tokens = module.split(":"); Assert.isTrue(tokens.length == 3, "required module format is: 'groupId:artifactId:version'"); this.groupId = tokens[0]; this.artifactId = tokens[1]; this.version = tokens[2]; this.args = args; }

Target:
ModuleLaunchTask(ModuleResolver moduleResolver, String module, String[] args) { this.moduleResolver = moduleResolver; this.coordinates = parse(module); this.args = args; }
Source:
public void addNewModelElements(EObject eObject, EReference eReference) { if (eReference == EcorePackage.eINSTANCE.getEReference_EOpposite()) { handleEOpposite(eObject, eReference); return; } super.addNewModelElements(eObject, eReference); }

Target:
public void addNewModelElements(EObject eObject, EReference eReference) { addNewModelElements(eObject, eReference, true); }
Source:
public SerbianStemmerTokenFilter(TokenStream in) { super(in); this.stemmer = new LjubesicPandzicStemmer(); }

Target:
public SerbianStemmerTokenFilter(TokenStream in) { super(in); }
Source:
public void init() { initMocks(this); pid = PIDs.get(UUID.randomUUID().toString()); unit = new AdminUnit(pid, repository, dataLoader); collectionChildPid = PIDs.get(UUID.randomUUID().toString()); workChildPid = PIDs.get(UUID.randomUUID().toString()); when(repository.mintContentPid()).thenReturn(collectionChildPid).thenReturn(workChildPid); collectionChildObj = new CollectionObject(collectionChildPid, repository, dataLoader); when(repository.createCollectionObject(any(PID.class), any(Model.class))) .thenReturn(collectionChildObj); workChildObj = new WorkObject(workChildPid, repository, dataLoader); when(repository.createWorkObject(any(PID.class), any(Model.class))) .thenReturn(workChildObj); }

Target:
public void init() { initMocks(this); pid = PIDs.get(UUID.randomUUID().toString()); unit = new AdminUnit(pid, repository, dataLoader); collectionChildPid = PIDs.get(UUID.randomUUID().toString()); when(collectionChildObj.getPid()).thenReturn(collectionChildPid); }
Source:
public IntegrationFlow messageSourceFlow(IntegrationFlowFunctionSupport functionSupport) { Assert.hasText(functionProperties.getName(), "Supplier name must be provided"); IntegrationFlowBuilder flowBuilder = functionSupport .integrationFlowFromNamedSupplier() .split() .channel(source.output()); return flowBuilder.get(); }

Target:
public IntegrationFlow messageSourceFlow(IntegrationFlowFunctionSupport functionSupport) { Assert.hasText(functionProperties.getName(), "Supplier name must be provided"); IntegrationFlowBuilder flowBuilder = functionSupport .integrationFlowFromNamedSupplier() .channel(source.output()); return flowBuilder.get(); }
Source:
public void run() { Map<String, Object> data = new HashMap<String, Object>(); Map<String, String> status = this.getDepositStatus(); if(!status.containsKey(DepositField.depositorEmail.name())) return; data.putAll(status); data.put("baseUrl", this.getBaseUrl()); if(status.containsKey(DepositField.errorMessage.name())) { data.put("error", Boolean.TRUE); } else { data.put("error", Boolean.FALSE); } String html = htmlTemplate.execute(data); String text = textTemplate.execute(data); MimeMessage mimeMessage = mailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED); String addy = status.get(DepositField.depositorEmail.name()); message.addTo(addy); message.setSubject("CDR deposit complete"); message.setFrom(getFromAddress()); message.setText(text, html); this.mailSender.send(mimeMessage); } catch(MessagingException e) { failJob(e, null, "Cannot send notification email"); } }

Target:
public void run() { Map<String, Object> data = new HashMap<String, Object>(); Map<String, String> status = this.getDepositStatus(); if(!status.containsKey(DepositField.depositorEmail.name())) return; data.putAll(status); data.put("baseUrl", this.getBaseUrl()); boolean error = status.containsKey(DepositField.errorMessage.name()); data.put("error", Boolean.valueOf(error)); String html = htmlTemplate.execute(data); String text = textTemplate.execute(data); MimeMessage mimeMessage = mailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED); String addy = status.get(DepositField.depositorEmail.name()); message.addTo(addy); if(error) { message.setSubject("CDR deposit error"); } else { message.setSubject("CDR deposit complete"); } message.setFrom(getFromAddress()); message.setText(text, html); this.mailSender.send(mimeMessage); } catch(MessagingException e) { failJob(e, null, "Cannot send notification email"); } }
Source:
public void commitStub() { SqlStorage<FormRecord> storage = CommCareApplication.instance().getUserStorage(FormRecord.class); SqlStorage<SessionStateDescriptor> sessionStorage = CommCareApplication.instance().getUserStorage(SessionStateDescriptor.class); SecretKey key = CommCareApplication.instance().createNewSymmetricKey(); FormRecord r = new FormRecord(FormRecord.STATUS_UNSTARTED, getSession().getForm(), key.getEncoded(), null, new Date(0), CommCareApplication.instance().getCurrentApp().getAppRecord().getApplicationId()); storage.write(r); setFormRecordId(r.getID()); SessionStateDescriptor ssd = SessionStateDescriptor.buildFromSessionWrapper(this); try { sessionStorage.write(ssd); } catch (Exception e) { CrashUtil.log("SessionStateDescriptor form id: " + ssd.getFormRecordId()); throw e; } sessionStateRecordId = ssd.getID(); }

Target:
public void commitStub() { SqlStorage<FormRecord> storage = CommCareApplication.instance().getUserStorage(FormRecord.class); SqlStorage<SessionStateDescriptor> sessionStorage = CommCareApplication.instance().getUserStorage(SessionStateDescriptor.class); SecretKey key = CommCareApplication.instance().createNewSymmetricKey(); FormRecord r = new FormRecord(FormRecord.STATUS_UNSTARTED, getSession().getForm(), key.getEncoded(), null, new Date(0), CommCareApplication.instance().getCurrentApp().getAppRecord().getApplicationId()); storage.write(r); setFormRecordId(r.getID()); SessionStateDescriptor ssd = SessionStateDescriptor.buildFromSessionWrapper(this); try { sessionStorage.write(ssd); } catch (Exception e) { if (ssd != null) { CrashUtil.log("SessionStateDescriptor form id: " + ssd.getFormRecordId()); } throw e; } sessionStateRecordId = ssd.getID(); }
Source:
public EvalHierarchyNode getNodeById(String nodeId) { if(cache.containsKey(nodeId)){ LOG.debug("--- Fetching (External)getNodeById record from cache for: " + nodeId); EvalHierarchyNode ret = (EvalHierarchyNode)cache.get(nodeId); if(ret != null) { return ret; } } EvalHierarchyNode node = null; if (evalHierarchyProvider != null) { node = evalHierarchyProvider.getNodeById(nodeId); } if (node == null) { HierarchyNode hNode = hierarchyService.getNodeById(nodeId); node = makeEvalNode(hNode); } LOG.debug("+++ Adding (External)getNodeById record to cache for: " + nodeId); cache.put(nodeId, node); return node; }

Target:
public EvalHierarchyNode getNodeById(String nodeId) { EvalHierarchyNode ret = (EvalHierarchyNode)cache.get(nodeId); if(ret != null) { LOG.debug("--- Fetching (External)getNodeById record from cache for: " + nodeId); return ret; } EvalHierarchyNode node = null; if (evalHierarchyProvider != null) { node = evalHierarchyProvider.getNodeById(nodeId); } if (node == null) { HierarchyNode hNode = hierarchyService.getNodeById(nodeId); node = makeEvalNode(hNode); } LOG.debug("+++ Adding (External)getNodeById record to cache for: " + nodeId); cache.put(nodeId, node); return node; }
Source:
public boolean isFinished() { return move.isFinished() || CommandScheduler.getInstance().timeSinceScheduled(this) > this.timeout; }

Target:
public boolean isFinished() { return move.isFinished() || CommandScheduler.getInstance().timeSinceScheduled(this) >= this.timeout; }
Source:
protected Iterator<Event> createEvents(SentenceSample sample) { Collection<Event> events = new ArrayList<Event>(); for (Span sentenceSpan : sample.getSentences()) { String sentenceString = sentenceSpan.getCoveredText(sample.getDocument()).toString(); for (Iterator<Integer> it = scanner.getPositions( sentenceString).iterator(); it.hasNext();) { int candidate = it.next(); String type = SentenceDetectorME.NO_SPLIT; if (!it.hasNext()) { type = SentenceDetectorME.SPLIT; } events.add(new Event(type, cg.getContext(sample.getDocument(), sentenceSpan.getStart() + candidate))); } } return events.iterator(); }

Target:
protected Iterator<Event> createEvents(SentenceSample sample) { Collection<Event> events = new ArrayList<>(); for (Span sentenceSpan : sample.getSentences()) { String sentenceString = sentenceSpan.getCoveredText(sample.getDocument()).toString(); for (Iterator<Integer> it = scanner.getPositions( sentenceString).iterator(); it.hasNext();) { int candidate = it.next(); String type = SentenceDetectorME.NO_SPLIT; if (!it.hasNext()) { type = SentenceDetectorME.SPLIT; } events.add(new Event(type, cg.getContext(sample.getDocument(), sentenceSpan.getStart() + candidate))); } } return events.iterator(); }
Source:
public void throwsUnknownRemoteExceptionWithCorrectBodyAfterFailingToDeserializeSerializableError() { String responseJson = "{\"attribute\": \"foo\"}"; MockResponse mockResponse = new MockResponse() .setBody(responseJson) .addHeader("Content-Type", "application/json") .setResponseCode(400); server.enqueue(mockResponse); OkHttpClient client = createRetryingClient(1); Call call = client.newCall(new Request.Builder().url(url).build()); assertThatThrownBy(call::execute).isInstanceOf(UnknownRemoteException.class) .hasMessageContaining("Error 400. (Failed to parse response body as SerializableError.)"); }

Target:
public void throwsUnknownRemoteExceptionWithCorrectBodyAfterFailingToDeserializeSerializableError() { String responseJson = "{\"attribute\": \"foo\"}"; MockResponse mockResponse = new MockResponse() .setBody(responseJson) .addHeader("Content-Type", "application/json") .setResponseCode(400); server.enqueue(mockResponse); OkHttpClient client = createRetryingClient(1); Call call = client.newCall(new Request.Builder().url(url).build()); assertThatThrownBy(call::execute) .isInstanceOf(UnknownRemoteException.class) .hasMessageContaining("Error 400. (Failed to parse response body as SerializableError.)") .matches(exc -> ((UnknownRemoteException) exc).getStatus() == 400) .matches(exc -> ((UnknownRemoteException) exc).getBody().equals(responseJson)); }
Source:
private void createReleaseWebHook(final ReleaseWebHookResource resource) { if (resource == null) { throw new InvalidParameterException("event parameter is null"); } String payloadUrl = validateAndGetPayloadUrl(resource); String secret = resource.getSecret(); String webHookName = resource.getWebHookName(); if (webHookName == null || webHookName.isEmpty()) { throw new InvalidParameterException("webhook name is empty"); } List<ReleaseWebHook> releaseWebHooks = ReleaseWebHookHelper.getReleaseWebHookConfigurations(); for (ReleaseWebHook webHook : releaseWebHooks) { if (webHook.getPayloadUrl().equalsIgnoreCase(payloadUrl)) { logger.fine(String.format("WebHook found for payloadUrl %s already exists", payloadUrl)); return; } } ReleaseWebHook webHook = new ReleaseWebHook(webHookName, payloadUrl, secret); releaseWebHooks.add(webHook); ReleaseWebHookHelper.saveReleaseWebHookConfigurations(releaseWebHooks); }

Target:
private void createReleaseWebHook(final ReleaseWebHookResource resource) { if (resource == null) { throw new InvalidParameterException("resource is null"); } String payloadUrl = validateAndGetPayloadUrl(resource); String secret = resource.getSecret(); String webHookName = resource.getWebHookName(); if (StringUtils.isBlank(webHookName)) { throw new InvalidParameterException("webhook name is empty"); } List<ReleaseWebHook> releaseWebHooks = ReleaseWebHookHelper.getReleaseWebHookConfigurations(); for (ReleaseWebHook webHook : releaseWebHooks) { if (webHook.getWebHookName().equalsIgnoreCase(webHookName)) { if (webHook.getPayloadUrl().equalsIgnoreCase(payloadUrl)) { logger.fine(String.format("WebHook with the name %s and payloadUrl %s already exists", webHookName, payloadUrl)); return; } else { throw new InvalidParameterException(String.format("WebHook with the name %s already exists. Provide a unique name for the ReleaseWebHook", webHookName)); } } } ReleaseWebHook webHook = new ReleaseWebHook(webHookName, payloadUrl, secret); releaseWebHooks.add(webHook); ReleaseWebHookHelper.saveReleaseWebHookConfigurations(releaseWebHooks); }
Source:
public static void EnableLoadBalancer() { log.info("Start scheduling to enable load balancer"); SchedulerUtilQuartzImpl.getInstance().scheduleAFixedDelayJob(instance, "PerformLoadBalancing", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.VdsLoadBalancingeIntervalInMinutes), Config.<Integer> GetValue(ConfigValues.VdsLoadBalancingeIntervalInMinutes), TimeUnit.MINUTES); log.info("Finished scheduling to enable load balancer"); }

Target:
public static void EnableLoadBalancer() { log.info("Start scheduling to enable vds load balancer"); SchedulerUtilQuartzImpl.getInstance().scheduleAFixedDelayJob(instance, "PerformLoadBalancing", new Class[] {}, new Object[] {}, Config.<Integer> GetValue(ConfigValues.VdsLoadBalancingeIntervalInMinutes), Config.<Integer> GetValue(ConfigValues.VdsLoadBalancingeIntervalInMinutes), TimeUnit.MINUTES); log.info("Finished scheduling to enable vds load balancer"); }
Source:
public static Collection<Object[]> configs() { String[] ledgerManagers = new String[] { "org.apache.bookkeeper.meta.FlatLedgerManagerFactory", "org.apache.bookkeeper.meta.LegacyHierarchicalLedgerManagerFactory", "org.apache.bookkeeper.meta.LongHierarchicalLedgerManagerFactory", "org.apache.bookkeeper.meta.MSLedgerManagerFactory", }; ArrayList<Object[]> cfgs = new ArrayList<Object[]>(ledgerManagers.length); for (String lm : ledgerManagers) { cfgs.add(new Object[] { lm }); } return cfgs; }

Target:
public static Collection<Object[]> configs() { String[] ledgerManagers = new String[] { "org.apache.bookkeeper.meta.FlatLedgerManagerFactory", "org.apache.bookkeeper.meta.LegacyHierarchicalLedgerManagerFactory", "org.apache.bookkeeper.meta.HierarchicalLedgerManagerFactory", "org.apache.bookkeeper.meta.LongHierarchicalLedgerManagerFactory", "org.apache.bookkeeper.meta.MSLedgerManagerFactory", }; ArrayList<Object[]> cfgs = new ArrayList<Object[]>(ledgerManagers.length); for (String lm : ledgerManagers) { cfgs.add(new Object[] { lm }); } return cfgs; }
Source:
private RemoteConfigurationRegistryJAASConfig(List<RemoteConfigurationRegistryConfig> configs, AliasService aliasService) { try { delegate = Configuration.getConfiguration(); } catch(Exception e) { final String message = String.format(Locale.ROOT, "Error while getting secure configuration. This error usually indicates an issue within the supplied JAAS configuration: %s", System.getProperty(GatewayConfig.KRB5_LOGIN_CONFIG, "Undefined")); throw new ConfigurationException(message, e); } this.aliasService = aliasService; for (RemoteConfigurationRegistryConfig config : configs) { if (config.isSecureRegistry()) { contextEntries.put(config.getName(), createEntries(config)); } } if (!contextEntries.isEmpty()) { Configuration.setConfiguration(this); } }

Target:
private RemoteConfigurationRegistryJAASConfig(List<RemoteConfigurationRegistryConfig> configs, AliasService aliasService) { try { delegate = Configuration.getConfiguration(); } catch(Exception e) { final String message = String.format(Locale.ROOT, "%s: %s", JAAS_CONFIG_ERRROR_PREFIX, System.getProperty(GatewayConfig.KRB5_LOGIN_CONFIG, "Undefined")); throw new ConfigurationException(message, e); } this.aliasService = aliasService; for (RemoteConfigurationRegistryConfig config : configs) { if (config.isSecureRegistry()) { contextEntries.put(config.getName(), createEntries(config)); } } if (!contextEntries.isEmpty()) { Configuration.setConfiguration(this); } }
Source:
public void testPeriodParser() { BigDecimal yearsDecimal = new BigDecimal(0.1); BigDecimal monthsDecimal = new BigDecimal(0.2); BigDecimal secondsInAYear = new BigDecimal(ChronoUnit.YEARS.getDuration().getSeconds()); BigDecimal secondsInAMonth = new BigDecimal(ChronoUnit.MONTHS.getDuration().getSeconds()); int yearDecimalInSeconds = yearsDecimal.multiply(secondsInAYear).intValue(); int monthDecimalInSeconds = monthsDecimal.multiply(secondsInAMonth).intValue(); org.joda.time.Period period = org.joda.time.Period.parse( String.format("P8MT6H%dS", yearDecimalInSeconds + monthDecimalInSeconds)); assertThat(period, is(PeriodParser.parse("P.1Y8.2MT6H"))); }

Target:
public void testPeriodParser() { BigDecimal yearsDecimal = new BigDecimal("0.1"); BigDecimal monthsDecimal = new BigDecimal("0.2"); BigDecimal secondsInAYear = new BigDecimal(ChronoUnit.YEARS.getDuration().getSeconds()); BigDecimal secondsInAMonth = new BigDecimal(ChronoUnit.MONTHS.getDuration().getSeconds()); int yearDecimalInSeconds = yearsDecimal.multiply(secondsInAYear).intValue(); int monthDecimalInSeconds = monthsDecimal.multiply(secondsInAMonth).intValue(); org.joda.time.Period period = org.joda.time.Period.parse( String.format("P8MT6H%dS", yearDecimalInSeconds + monthDecimalInSeconds)); assertThat(period, is(PeriodParser.parse("RELATIVE(P.1Y8.2MT6H)", RELATIVE_TEMPORAL_REGEX))); }
Source:
public static FlowTrigger createTestFlowTrigger(final List<FlowTriggerDependency> deps, final Duration maxWaitDuration) { final FlowTrigger flowTrigger = new FlowTrigger( new CronSchedule("* * * * ? *"), deps, maxWaitDuration); return flowTrigger; }

Target:
public static FlowTrigger createTestFlowTrigger(final List<FlowTriggerDependency> deps, final Duration maxWaitDuration) { return new FlowTrigger( new CronSchedule("* * * * ? *"), deps, maxWaitDuration); }
Source:
public void define(WebService.NewController controller) { controller.createAction("form_data") .setSince("6.7") .setPost(true) .setDescription("Provide data for fields: the server ID and the total number of lines of code.") .setResponseExample(getClass().getResource("example-edition-form_data.json")) .setInternal(true) .setHandler(this); }

Target:
public void define(WebService.NewController controller) { controller.createAction("form_data") .setSince("6.7") .setPost(false) .setDescription("Provide data to prefill license request forms: the server ID and the total number of lines of code.") .setResponseExample(getClass().getResource("example-edition-form_data.json")) .setInternal(true) .setHandler(this); }
Source:
public int run(CommandLine cl) throws AlluxioException, IOException { mWorkingDirPath = getWorkingDirectory(cl); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"); for (int i = 0; i < COLLECT_METRICS_TIMES; i++) { LocalDateTime now = LocalDateTime.now(); String timeString = dtf.format(now); LOG.info(String.format("Collecting metrics at %s", timeString)); File outputFile = generateOutputFile(mWorkingDirPath, String.format("%s-%s", getCommandName(), i)); StringWriter outputBuffer = new StringWriter(); outputBuffer.write(String.format("Collect metric at approximately %s", timeString)); String masterAddr; try { masterAddr = mFsContext.getMasterAddress().getHostName(); } catch (UnavailableException e) { String noMasterMsg = "No Alluxio master available. Skip metrics collection."; LOG.warn(noMasterMsg); outputBuffer.write(noMasterMsg); continue; } String url = String.format("http://%s:%s%s", masterAddr, mFsContext.getClusterConf().get(PropertyKey.MASTER_WEB_PORT), METRICS_SERVLET_PATH); LOG.info(String.format("Metric address URL: %s", url)); String metricsResponse = getMetricsJson(url); outputBuffer.write(metricsResponse); FileUtils.writeStringToFile(outputFile, metricsResponse); SleepUtils.sleepMs(LOG, COLLECT_METRICS_INTERVAL); } return 0; }

Target:
public int run(CommandLine cl) throws AlluxioException, IOException { mWorkingDirPath = getWorkingDirectory(cl); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"); StringWriter outputBuffer = new StringWriter(); for (int i = 0; i < COLLECT_METRICS_TIMES; i++) { LocalDateTime now = LocalDateTime.now(); String timeMsg = String.format("Collecting metrics at %s", dtf.format(now)); LOG.info(timeMsg); outputBuffer.write(timeMsg); String masterAddr; try { masterAddr = mFsContext.getMasterAddress().getHostName(); } catch (UnavailableException e) { String noMasterMsg = "No Alluxio master available. Skip metrics collection."; LOG.warn(noMasterMsg); outputBuffer.write(noMasterMsg); break; } String url = String.format("http://%s:%s%s", masterAddr, mFsContext.getClusterConf().get(PropertyKey.MASTER_WEB_PORT), METRICS_SERVLET_PATH); LOG.info(String.format("Metric address URL: %s", url)); String metricsResponse = getMetricsJson(url); outputBuffer.write(metricsResponse); File outputFile = generateOutputFile(mWorkingDirPath, String.format("%s-%s", getCommandName(), i)); FileUtils.writeStringToFile(outputFile, metricsResponse); SleepUtils.sleepMs(LOG, COLLECT_METRICS_INTERVAL); } File outputFile = generateOutputFile(mWorkingDirPath, String.format("%s.txt", getCommandName())); FileUtils.writeStringToFile(outputFile, outputBuffer.toString()); return 0; }
Source:
private static void handleError(File pigLog) throws Exception { System.out.println(); System.out.println("Pig logfile dump:"); System.out.println(); try { BufferedReader reader = new BufferedReader(new FileReader(pigLog)); String line = reader.readLine(); isTuningError = false; TuningErrorHandler tuningErrorHandle = new TuningErrorHandler(); while (line != null) { System.err.println(line); line = reader.readLine(); if (tuningErrorHandle.containsAutoTuningError(line)) { isTuningError = true; } } reader.close(); } catch (FileNotFoundException e) { System.err.println("pig log file: " + pigLog + " not found."); } }

Target:
private static void handleError(File pigLog) throws Exception { System.out.println(); System.out.println("Pig logfile dump:"); System.out.println(); try (BufferedReader reader = new BufferedReader(new FileReader(pigLog))) { String line = reader.readLine(); boolean isTuningError = false; TuningErrorDetector tuningErrorDetector = new TuningErrorDetector(); while (line != null) { System.err.println(line); line = reader.readLine(); if (tuningErrorDetector.containsAutoTuningError(line)) { isTuningError = true; } } if (isTuningError) { throw new TuningException("Auto Tuning Failure"); } } catch (FileNotFoundException e) { System.err.println("pig log file: " + pigLog + " not found."); } }
Source:
public void testSplitDeviceDataByDay() { final DateTime timestamp = DateTime.now(DateTimeZone.UTC).withHourOfDay(21).withMinuteOfHour(0); final List<DeviceData> data = new ArrayList<>(); addDeviceData(data, 0, timestamp.withHourOfDay(21)); addDeviceData(data, 0, timestamp.withHourOfDay(23)); addDeviceData(data, 0, timestamp.plusDays(1).withHourOfDay(4)); addDeviceData(data, 1, timestamp.plusDays(1).withHourOfDay(21)); addDeviceData(data, 1, timestamp.plusDays(2).withHourOfDay(3)); addDeviceData(data, 1, timestamp.plusDays(2).withHourOfDay(4)); addDeviceData(data, 2, timestamp.plusDays(2).withHourOfDay(21)); addDeviceData(data, 3, timestamp.plusDays(4).withHourOfDay(1)); addDeviceData(data, 3, timestamp.plusDays(4).withHourOfDay(2)); final List<List<DeviceData>> deviceDataByDay = BedLightDuration.splitDeviceDataByDay(data); assertThat(deviceDataByDay.size(), is(4)); final Integer day1Duration = BedLightDuration.findLightOnDurationForDay(deviceDataByDay.get(0), 420); final Integer day2Duration = BedLightDuration.findLightOnDurationForDay(deviceDataByDay.get(1), 420); final Integer day3Duration = BedLightDuration.findLightOnDurationForDay(deviceDataByDay.get(2), 420); final Integer day4Duration = BedLightDuration.findLightOnDurationForDay(deviceDataByDay.get(3), 420); assertThat(day1Duration, is(7*60)); assertThat(day2Duration, is(7*60)); assertThat(day3Duration, is(0*60)); assertThat(day4Duration, is(1*60)); }

Target:
public void testSplitDeviceDataByDay() { final DateTime timestamp = DateTime.now(DateTimeZone.UTC).withHourOfDay(21).withMinuteOfHour(0); final List<DeviceData> data = Lists.newArrayList( createNewDeviceData(0, timestamp.withHourOfDay(21)), createNewDeviceData(0, timestamp.withHourOfDay(23)), createNewDeviceData(0, timestamp.plusDays(1).withHourOfDay(4)), createNewDeviceData(1, timestamp.plusDays(1).withHourOfDay(21)), createNewDeviceData(1, timestamp.plusDays(2).withHourOfDay(3)), createNewDeviceData(1, timestamp.plusDays(2).withHourOfDay(4)), createNewDeviceData(2, timestamp.plusDays(2).withHourOfDay(21)), createNewDeviceData(3, timestamp.plusDays(4).withHourOfDay(1)), createNewDeviceData(3, timestamp.plusDays(4).withHourOfDay(2)) ); final List<List<DeviceData>> deviceDataByDay = BedLightDuration.splitDeviceDataByDay(data); assertThat(deviceDataByDay.size(), is(4)); final Integer day1Duration = BedLightDuration.findLightOnDurationForDay(deviceDataByDay.get(0), 420); final Integer day2Duration = BedLightDuration.findLightOnDurationForDay(deviceDataByDay.get(1), 420); final Integer day3Duration = BedLightDuration.findLightOnDurationForDay(deviceDataByDay.get(2), 420); final Integer day4Duration = BedLightDuration.findLightOnDurationForDay(deviceDataByDay.get(3), 420); assertThat(day1Duration, is(7*60)); assertThat(day2Duration, is(7*60)); assertThat(day3Duration, is(0*60)); assertThat(day4Duration, is(1*60)); }
Source:
public ConfigImpl(Context context) { BASE_URL = context.getString(R.string.baseUrl); CANVASS_URL = context.getString(R.string.canvassUrl); CLIENT_ID = context.getString(R.string.oauth2ClientId); CLIENT_SECRET = context.getString(R.string.oauth2ClientSecret); String name = "FieldTheBern"; String version = null; try { version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) { version = "dev"; } LinkedList<String> comments = new LinkedList<>(); if(Build.VERSION.RELEASE != null) { comments.add("Android " + Build.VERSION.RELEASE); } if(Build.MODEL != null) { comments.add(Build.MODEL); } String nameAndVersion = name + "/" + version; String comment = Joiner.on("; ").join(comments); if(comment.length() > 0) { comment = " (" + comment + ")"; } USER_AGENT = nameAndVersion + comment; }

Target:
public ConfigImpl(Context context) { BASE_URL = context.getString(R.string.baseUrl); CANVASS_URL = context.getString(R.string.canvassUrl); CLIENT_ID = context.getString(R.string.oauth2ClientId); CLIENT_SECRET = context.getString(R.string.oauth2ClientSecret); String name = "FieldTheBern"; String version = "dev"; try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); version = packageInfo.versionName + "-b" + packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { } LinkedList<String> comments = new LinkedList<>(); if(Build.VERSION.RELEASE != null) { comments.add("Android " + Build.VERSION.RELEASE); } if(Build.MODEL != null) { comments.add(Build.MODEL); } String nameAndVersion = name + "/" + version; String comment = Joiner.on("; ").join(comments); if(comment.length() > 0) { comment = " (" + comment + ")"; } USER_AGENT = nameAndVersion + comment; }