auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ResultValidator expectEvents(Object... expectedEvents) { if (expectedEvents.length != publishedEvents.size()) { reporter.reportWrongEvent(publishedEvents, Arrays.asList(expectedEvents), actualException); } Iterator<EventMessage<?>> iterator = publishedEvents.iterator(); for (Object expectedEvent : expectedEvents) { EventMessage actualEvent = iterator.next(); <START> if (EventMessage.class.isInstance(expectedEvent)) { <END> EventMessage<?> expectedEventMessage = (EventMessage<?>) expectedEvent; if (!verifyEventEquality(expectedEventMessage.getPayload(), actualEvent.getPayload()) || !verifyMetaDataEquality(expectedEventMessage.getMetaData(), actualEvent.getMetaData())) { reporter.reportWrongEvent(publishedEvents, Arrays.asList(expectedEvents), actualException); } } else if (!verifyEventEquality(expectedEvent, actualEvent.getPayload())) { reporter.reportWrongEvent(publishedEvents, Arrays.asList(expectedEvents), actualException); } } return this; }</code><technical_language>I addition able check payload metadata, kinda feels added additional behaviour 'event-payload-matching' function is clear front.. settled alternative solution, sprung mind is a expectEventMessages(EventMessage<?>... expectedEventMessages) function. thinking out loud here, do @bliessens</technical_language>

Target:
public ResultValidator expectEvents(Object... expectedEvents) { if (expectedEvents.length != publishedEvents.size()) { reporter.reportWrongEvent(publishedEvents, Arrays.asList(expectedEvents), actualException); } Iterator<EventMessage<?>> iterator = publishedEvents.iterator(); for (Object expectedEvent : expectedEvents) { EventMessage actualEvent = iterator.next(); if (!verifyEventEquality(expectedEvent, actualEvent.getPayload())) { reporter.reportWrongEvent(publishedEvents, Arrays.asList(expectedEvents), actualException); } } return this; }
Source:
<code>public Fluid setColor(Color color) { <START> this.color = (color.getAlpha()<<24) + (color.getRed()<<16) + (color.getGreen()<<8) + color.getBlue(); <END> return this; }</code><technical_language>This replaced this.color = color.getRGB()</technical_language>

Target:
public Fluid setColor(Color color) { this.color = color.getRGB(); return this; }
Source:
<code>public OrderByOperator( OperatorContext operatorContext, List<Type> sourceTypes, List<Integer> outputChannels, int expectedPositions, List<Integer> sortChannels, List<SortOrder> sortOrder, PagesIndex.Factory pagesIndexFactory, boolean spillEnabled, Optional<SpillerFactory> spillerFactory) { requireNonNull(pagesIndexFactory, "pagesIndexFactory is null"); this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); this.outputChannels = Ints.toArray(requireNonNull(outputChannels, "outputChannels is null")); this.sortChannels = ImmutableList.copyOf(requireNonNull(sortChannels, "sortChannels is null")); this.sortOrder = ImmutableList.copyOf(requireNonNull(sortOrder, "sortOrder is null")); this.sourceTypes = sourceTypes; <START> this.localUserMemoryContext = operatorContext.localUserMemoryContext(); <END> this.localRevocableMemoryContext = operatorContext.localRevocableMemoryContext(); this.spillerFactory = spillerFactory; this.pageIndex = pagesIndexFactory.newPagesIndex(sourceTypes, expectedPositions); this.spillEnabled = spillEnabled; }</code><technical_language>rename to: pagesIndexUserMemoryContext pagesIndexRevocableMemoryContext</technical_language>

Target:
public OrderByOperator( OperatorContext operatorContext, List<Type> sourceTypes, List<Integer> outputChannels, int expectedPositions, List<Integer> sortChannels, List<SortOrder> sortOrder, PagesIndex.Factory pagesIndexFactory, boolean spillEnabled, Optional<SpillerFactory> spillerFactory) { requireNonNull(pagesIndexFactory, "pagesIndexFactory is null"); this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); this.outputChannels = Ints.toArray(requireNonNull(outputChannels, "outputChannels is null")); this.sortChannels = ImmutableList.copyOf(requireNonNull(sortChannels, "sortChannels is null")); this.sortOrder = ImmutableList.copyOf(requireNonNull(sortOrder, "sortOrder is null")); this.sourceTypes = sourceTypes; this.pagesIndexUserMemoryContext = operatorContext.localUserMemoryContext(); this.pagesIndexRevocableMemoryContext = operatorContext.localRevocableMemoryContext(); this.spillerFactory = spillerFactory; this.pageIndex = pagesIndexFactory.newPagesIndex(sourceTypes, expectedPositions); this.spillEnabled = spillEnabled; }
Source:
<code><START> public synchronized PartitionUpsertMetadataManager getOrCreatePartitionManager(int partitionId) { if(!_partitionMetadataManagerMap.containsKey(partitionId)) { _partitionMetadataManagerMap.put(partitionId, new PartitionUpsertMetadataManager(partitionId)); } return _partitionMetadataManagerMap.get(partitionId); } <END></code><technical_language>suggestion public PartitionUpsertMetadataManager getOrCreatePartitionManager(int partitionId) { return _partitionMetadataManagerMap.computeIfAbsent(partitionId, PartitionUpsertMetadataManager::new); }</technical_language>

Target:
public PartitionUpsertMetadataManager getOrCreatePartitionManager(int partitionId) { return _partitionMetadataManagerMap.computeIfAbsent(partitionId, k -> new PartitionUpsertMetadataManager()); }
Source:
<code>public SelectRouteDialog(List<IRoute> routes, Shell shell) { super(shell, new RouteLabelProvider()); setTitle("Select Route"); StringBuilder message = new StringBuilder(); if(!routes.isEmpty()) { IRoute route = routes.get(0); IConnection connection = ConnectionsRegistryUtil.safeGetConnectionFor(route); if(connection != null) { message.append("Server: ") .append(connection.getUsername()).append(" ").append(connection.getHost()) .append(StringUtils.getLineSeparator()); } <START> IProject project = route.getProject(); <END> if(project != null) { message.append("Project: ") .append(project.getName()) .append(StringUtils.getLineSeparator()); } if(message.length() > 0) { message.append(StringUtils.getLineSeparator()); } } message.append("Select the route to open in a browser."); setMessage(message.toString()); setMultipleSelection(false); setAllowDuplicates(false); setElements(routes.toArray()); }</code><technical_language>need is project name, #getNamespace() route. return value. Additionally a call grab project dont cache this info moment</technical_language>

Target:
public SelectRouteDialog(List<IRoute> routes, Shell shell) { super(shell, new RouteLabelProvider()); setTitle("Select Route"); StringBuilder message = new StringBuilder(); if(!routes.isEmpty()) { IRoute route = routes.get(0); IConnection connection = ConnectionsRegistryUtil.safeGetConnectionFor(route); if(connection != null) { message.append("Server: ") .append(connection.getUsername()).append(" ").append(connection.getHost()) .append(StringUtils.getLineSeparator()); } message.append("Project: ") .append(route.getNamespace()) .append(StringUtils.getLineSeparator()); message.append(StringUtils.getLineSeparator()); } message.append("Select the route to open in a browser."); setMessage(message.toString()); setMultipleSelection(false); setAllowDuplicates(false); setElements(routes.toArray()); }
Source:
<code>public boolean isReservationMadeByRequestingUser(RegisteredUserDTO user, RegisteredUserDTO userOwningReservation, IsaacEventPageDTO event) throws SegueDatabaseException { EventBookingDTO booking = this.getBookingByEventIdAndUserId(event.getId(), userOwningReservation.getId()); UserSummaryDTO reservingUser = booking.getReservedBy(); <START> if (null != reservingUser) { <END> return reservingUser.getId().equals(user.getId()); } else { return false; } }</code><technical_language>flip .equals(..) avoid null check, if safe missing another null check</technical_language>

Target:
public boolean isReservationMadeByRequestingUser(RegisteredUserDTO user, RegisteredUserDTO userOwningReservation, IsaacEventPageDTO event) throws SegueDatabaseException { EventBookingDTO booking = this.getBookingByEventIdAndUserId(event.getId(), userOwningReservation.getId()); Long reservingUserId = booking.getReservedById(); return user.getId().equals(reservingUserId); }
Source:
<code>public void writeApplication(HttpServletRequest request, HttpServletResponse response) <START> throws IOException, UnsupportedFormatException, NotAcceptableException, ReadException, NotAuthorizedException { <END> ResponseWriter writer = writerResolver.writerFor(request, response); checkAccess(request); Application application = deserialize(new InputStreamReader(request.getInputStream()), Application.class); if (application.getId() != null) { Optional<Application> existing = applicationStore.applicationFor(application.getId()); application = application.copy().withSlug(existing.get().getSlug()).build(); application = applicationStore.updateApplication(application); } else { application = applicationStore.createApplication(application); } QueryResult<Application> queryResult = QueryResult.singleResult(application, QueryContext.standard()); resultWriter.write(queryResult, writer); }</code><technical_language>caught, bar IOException, written out error summaries</technical_language>

Target:
public void writeApplication(HttpServletRequest request, HttpServletResponse response) throws IOException { ResponseWriter writer = null; try { writer = writerResolver.writerFor(request, response); Application application = deserialize(new InputStreamReader(request.getInputStream()), Application.class); if (application.getId() != null) { Optional<Application> existing = applicationStore.applicationFor(application.getId()); application = application.copy().withSlug(existing.get().getSlug()).build(); application = applicationStore.updateApplication(application); } else { application = applicationStore.createApplication(application); } QueryResult<Application> queryResult = QueryResult.singleResult(application, QueryContext.standard()); resultWriter.write(queryResult, writer); } catch (Exception e) { log.error("Request exception " + request.getRequestURI(), e); ErrorSummary summary = ErrorSummary.forException(e); new ErrorResultWriter().write(summary, writer, request, response); } }
Source:
<code>void loadContactsFromServer(){ <START> HandlerService.getAllContacts(1, new ServiceCallback<HandlerDataListBody<User>, User.Error>() { <END> @Override public void onSuccess(HandlerDataListBody<User> result) { } @Override public void onEror(User.Error error, int code) { } }); }</code><technical_language>pass "null" callback? is used, anyway</technical_language>

Target:
void loadContactsFromServer() { HandlerService.getAllContacts(1, null); }
Source:
<code>public static void checkReceivedMail(List<MailMessage> mails, DocumentModel commentDocModel, DocumentModel commentedDocModel, Event event, String commentEventType) { DocumentModel sourceDocument = ((DocumentEventContext) event.getContext()).getSourceDocument(); <START> int expectedMailsCount = COMMENT_REMOVED.equals(commentEventType) ? 0 : 1; expectedMailsCount = COMMENT_ADDED.equals(commentEventType) && !sourceDocument.getId().equals(commentedDocModel.getId()) ? 2 : expectedMailsCount; assertEquals(expectedMailsCount, mails.size()); if (expectedMailsCount > 0) { String subject = String.format("[Nuxeo5]%s comment on '%s'", <END> COMMENT_ADDED.equals(event.getName()) ? "New" : "Updated", sourceDocument.getName()); List<MailMessage> mailsBySubject = mails.stream() .filter(m -> subject.equals(m.getSubject())) .collect(Collectors.toList()); assertEquals(expectedMailsCount, mailsBySubject.size()); String expectedMailContent = getExpectedMailContent(commentDocModel, commentedDocModel, event, commentEventType); assertEquals(expectedMailContent, getMailContent(mailsBySubject.get(mailsBySubject.size() - 1))); } }</code><technical_language>leave ternary expression if/else if statements</technical_language>

Target:
public static void checkReceivedMail(List<MailMessage> mails, DocumentModel commentDocModel, DocumentModel commentedDocModel, Event event, String commentEventType) { int expectedMailsCount = COMMENT_REMOVED.equals(commentEventType) ? 0 : 1; assertEquals(expectedMailsCount, mails.size()); if (expectedMailsCount > 0) { String subject = String.format("[Nuxeo5]%s comment on '%s'", COMMENT_ADDED.equals(event.getName()) ? "New" : "Updated", commentedDocModel.getName()); List<MailMessage> mailsBySubject = mails.stream() .filter(m -> subject.equals(m.getSubject())) .collect(Collectors.toList()); assertEquals(1, mailsBySubject.size()); String expectedMailContent = getExpectedMailContent(commentDocModel, commentedDocModel, event, commentEventType); assertEquals(expectedMailContent, getMailContent(mailsBySubject.get(0))); } }
Source:
<code>private void addExecutablePermissions(Path allureHome) { Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_EXECUTE); perms.add(PosixFilePermission.OWNER_READ); <START> perms.add(PosixFilePermission.OWNER_WRITE); <END> Path binaries = allureHome.resolve("bin"); try { Files.setPosixFilePermissions(binaries.resolve("allure"), perms); Files.setPosixFilePermissions(binaries.resolve("allure.bat"), perms); } catch (IOException e) { LOGGER.error("Failed to change Allure bin permissions {}", e); } }</code><technical_language>is this permission for</technical_language>

Target:
private void addExecutablePermissions(Path allureHome) { Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_EXECUTE); Path binaries = allureHome.resolve("bin"); try { Files.setPosixFilePermissions(binaries.resolve("allure"), perms); Files.setPosixFilePermissions(binaries.resolve("allure.bat"), perms); } catch (IOException e) { LOGGER.error("Failed to change Allure bin permissions {}", e); } }
Source:
<code>public void modifyDefaultTimeout(@Observes(precedence = -100) BeforeSuite event) { if (arquillianDescriptor.get() .extension("drone") .getExtensionProperties() <START> .get("instantiationTimeoutInSeconds") != null) return; <END> GlobalDroneConfiguration globalDroneConfiguration = droneContext.get().getGlobalDroneConfiguration(GlobalDroneConfiguration.class); globalDroneConfiguration.setInstantiationTimeoutInSeconds(DEFAULT_INSTANTIATION_TIMEOUT); }</code><technical_language>curly brackets for if statements code consistent project</technical_language>

Target:
public void modifyDefaultTimeout(@Observes(precedence = -100) BeforeSuite event) { if (arquillianDescriptor.get() .extension(GlobalDroneConfiguration.CONFIGURATION_NAME) .getExtensionProperties() .get("instantiationTimeoutInSeconds") != null) { return; } GlobalDroneConfiguration globalDroneConfiguration = droneContext.get().getGlobalDroneConfiguration(GlobalDroneConfiguration.class); globalDroneConfiguration.setInstantiationTimeoutInSeconds(DEFAULT_INSTANTIATION_TIMEOUT); }
Source:
<code>public static Attribute unmarshalFrom(ObjectElement element) { AttributeImpl attribute = null; for (Serializable value : element.getValue()) { <START> try { <END> value = (Serializable) new ObjectInputStream(new ByteArrayInputStream((byte[]) value)).readObject(); } catch (IOException | ClassNotFoundException e) { LOGGER.debug("Could not unmarshal Metacard Object from Base64 encoded string", e); } if (attribute == null) { attribute = new AttributeImpl(element.getName(), value); } else { attribute.addValue(value); } } return attribute; }</code><technical_language>check is a byte[]</technical_language>

Target:
public static Attribute unmarshalFrom(ObjectElement element) { AttributeImpl attribute = null; String elementName = element.getName(); for (byte[] value : element.getValue()) { Serializable unmarshalledValue = value; try (ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(value))) { unmarshalledValue = (Serializable) objectInputStream.readObject(); } catch (IOException | ClassNotFoundException | RuntimeException e) { LOGGER.debug("Could not unmarshal Metacard object for attribute: {}", elementName, e); } if (attribute == null) { attribute = new AttributeImpl(elementName, unmarshalledValue); } else { attribute.addValue(unmarshalledValue); } } return attribute; }
Source:
<code>public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, <START> HttpServletRequest request, HttpServletResponse response) { <END> if (this.isCurrentPrincipalAuthenticated()) { this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal); } else { this.httpSessionAuthorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, request, response); } }</code><technical_language>passed in Authentication is ignored. leverage SecurityContextHolder</technical_language>

Target:
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, HttpServletRequest request, HttpServletResponse response) { if (this.isPrincipalAuthenticated(principal)) { this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal); } else { this.anonymousAuthorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, request, response); } }
Source:
<code>private int numberOfAssignmentsForConsumersGroups(List<String> consumerGroupsIds) throws ExecutionException, InterruptedException { Collection<ConsumerGroupDescription> consumerGroupsDescriptions = adminClient.describeConsumerGroups(consumerGroupsIds).all().get().values(); <START> Collection<MemberDescription> memberDescriptions = consumerGroupsDescriptions.stream().flatMap(desc -> desc.members().stream()).collect(Collectors.toList()); <END> return memberDescriptions.stream().flatMap(memberDescription -> memberDescription.assignment().topicPartitions().stream()).collect(Collectors.toList()).size(); }</code><technical_language>dont need collect that, left stream, minor</technical_language>

Target:
private int numberOfAssignmentsForConsumersGroups(List<String> consumerGroupsIds) throws ExecutionException, InterruptedException { Collection<ConsumerGroupDescription> consumerGroupsDescriptions = adminClient.describeConsumerGroups(consumerGroupsIds).all().get().values(); Stream<MemberDescription> memberDescriptions = consumerGroupsDescriptions.stream().flatMap(desc -> desc.members().stream()); return memberDescriptions.flatMap(memberDescription -> memberDescription.assignment().topicPartitions().stream()).collect(Collectors.toList()).size(); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { HttpSession session = ((HttpServletRequest) request).getSession(false); Long userId = null; if (session != null) { userId = (Long) session.getAttribute(SessionResource.USER_ID_KEY); if (userId != null) { Context.getPermissionsManager().checkUserEnabled(userId); Context.getStatisticsManager().registerRequest(userId); } } if (userId == null) { throw new NotAuthorizedException("Not authorized"); } String[] parts = ((HttpServletRequest) request).getPathInfo().split("/"); if (parts.length < 2) { if (dirAllowed) { Context.getPermissionsManager().checkAdmin(userId); } else { throw new SecurityException("Wrong path"); } <START> } else if (parts.length == 2 && !dirAllowed) { <END> throw new SecurityException("Wrong path"); } else { Device device = Context.getIdentityManager().getByUniqueId(parts[1]); if (device != null) { Context.getPermissionsManager().checkDevice(userId, device.getId()); } else { throw new IllegalArgumentException("Device not found"); } } chain.doFilter(request, response); } catch (Exception e) { formatError((HttpServletResponse) response, e); } }</code><technical_language>is this check for</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = ((HttpServletResponse) response); try { HttpSession session = ((HttpServletRequest) request).getSession(false); Long userId = null; if (session != null) { userId = (Long) session.getAttribute(SessionResource.USER_ID_KEY); if (userId != null) { Context.getPermissionsManager().checkUserEnabled(userId); Context.getStatisticsManager().registerRequest(userId); } } if (userId == null) { httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } String path = ((HttpServletRequest) request).getPathInfo(); String[] parts = path.split("/"); if (parts.length < 2 || parts.length == 2 && !path.endsWith("/")) { Context.getPermissionsManager().checkAdmin(userId); } else { Device device = Context.getDeviceManager().getByUniqueId(parts[1]); if (device != null) { Context.getPermissionsManager().checkDevice(userId, device.getId()); } else { httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } chain.doFilter(request, response); } catch (SecurityException e) { httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); httpResponse.getWriter().println(Log.exceptionStack(e)); } catch (SQLException e) { httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); httpResponse.getWriter().println(Log.exceptionStack(e)); } }
Source:
<code>public long getEntityOwnerId() { Long accountId = _accountService.getActiveAccountByName(accountName, domainId).getAccountId(); if (accountId == null) { return CallContext.current().getCallingAccount().getId(); } <START> return Account.ACCOUNT_ID_SYSTEM; <END> }</code><technical_language>This right. do here</technical_language>

Target:
public long getEntityOwnerId() { return _accountService.getActiveAccountByName(accountName, domainId).getAccountId(); }
Source:
<code>public void reconnect(String scheme, String hostName, int port, boolean managementSubsystemEndpoint, String asAuthKey) { assert holdsLock(lock); try { Base64OutputStream base64 = getBase64OutputStream(stdin); StreamUtils.writeUTFZBytes(base64, scheme); StreamUtils.writeUTFZBytes(base64, hostName); StreamUtils.writeInt(base64, port); StreamUtils.writeBoolean(base64, managementSubsystemEndpoint); <START> base64.write(asAuthKey.getBytes()); <END> base64.close(); } catch (IOException e) { if(state == State.STARTED) { log.failedToSendReconnect(e, processName); } } }</code><technical_language>needs US-ASCII charset, some other simple ascii encoding conversion</technical_language>

Target:
public void reconnect(String scheme, String hostName, int port, boolean managementSubsystemEndpoint, String asAuthKey) { assert holdsLock(lock); try { Base64OutputStream base64 = getBase64OutputStream(stdin); StreamUtils.writeUTFZBytes(base64, scheme); StreamUtils.writeUTFZBytes(base64, hostName); StreamUtils.writeInt(base64, port); StreamUtils.writeBoolean(base64, managementSubsystemEndpoint); base64.write(asAuthKey.getBytes(Charset.forName("US-ASCII"))); base64.close(); } catch (IOException e) { if(state == State.STARTED) { log.failedToSendReconnect(e, processName); } } }
Source:
<code>public void onFocusSourceColumnSeparator() { LogicalWindow window = getParentLogicalWindow(sourceColumnManager_.getActiveElement()); if (window == null || window.getNormal() == null || !window.getNormal().getName().contains(SourceColumnManager.COLUMN_PREFIX)) { <START> Debug.log("Attempted focusSourceColumnSeparator when source column not active."); <END> return; } panel_.focusSplitter(window.getNormal()); }</code><technical_language>leave this in</technical_language>

Target:
public void onFocusSourceColumnSeparator() { LogicalWindow window = getParentLogicalWindow(sourceColumnManager_.getActiveElement()); if (window == null || window.getNormal() == null || !window.getNormal().getName().contains(SourceColumnManager.COLUMN_PREFIX)) { Debug.logWarning("Attempted focusSourceColumnSeparator when source column not active."); return; } panel_.focusSplitter(window.getNormal()); }
Source:
<code>private void buildHoursSegment() { if (venue.getMealsByDay().get(0).getMeals() != null) { List<MITDiningMeal> meals = venue.getMealsByDay().get(0).getMeals(); String startDate = venue.getMealsByDay().get(0).getDateString(); List<MITDiningMeal> previousMeals = meals; for (int i = 1; i < venue.getMealsByDay().size(); i++) { if (!checkMeals(venue.getMealsByDay().get(i).getMeals(), previousMeals)) { String endDate = venue.getMealsByDay().get(i - 1).getDateString(); meals = venue.getMealsByDay().get(i - 1).getMeals(); String range = formatDate(startDate) + " - " + formatDate(endDate); buildAndAddView(range, meals); previousMeals = venue.getMealsByDay().get(i).getMeals(); startDate = venue.getMealsByDay().get(i).getDateString(); } else if (i == venue.getMealsByDay().size() - 1) { String endDate = venue.getMealsByDay().get(i).getDateString(); meals = venue.getMealsByDay().get(i).getMeals(); String range = formatDate(startDate) + " - " + formatDate(endDate); buildAndAddView(range, meals); } } } else { <START> buildAnddAddView(); <END> } }</code><technical_language>Small typo</technical_language>

Target:
private void buildHoursSegment() { if (venue.getMealsByDay().get(0).getMeals() != null) { List<MITDiningMeal> meals = venue.getMealsByDay().get(0).getMeals(); String startDate = venue.getMealsByDay().get(0).getDateString(); List<MITDiningMeal> previousMeals = meals; for (int i = 1; i < venue.getMealsByDay().size(); i++) { if (!checkMeals(venue.getMealsByDay().get(i).getMeals(), previousMeals)) { String endDate = venue.getMealsByDay().get(i - 1).getDateString(); meals = venue.getMealsByDay().get(i - 1).getMeals(); String range = formatDate(startDate) + " - " + formatDate(endDate); buildAndAddView(range, meals); previousMeals = venue.getMealsByDay().get(i).getMeals(); startDate = venue.getMealsByDay().get(i).getDateString(); } else if (i == venue.getMealsByDay().size() - 1) { String endDate = venue.getMealsByDay().get(i).getDateString(); meals = venue.getMealsByDay().get(i).getMeals(); String range = formatDate(startDate) + " - " + formatDate(endDate); buildAndAddView(range, meals); } } } else { buildAndAddView(); } }
Source:
<code>public void configure() { <START> factory(ReceiveCommits.Factory.class); <END> }</code><technical_language>AsyncReceiveCommits.Factory</technical_language>

Target:
public void configure() { install(new FactoryModuleBuilder() .build(AsyncReceiveCommits.Factory.class)); expose(AsyncReceiveCommits.Factory.class); install(new FactoryModuleBuilder() .build(ReceiveCommits.Factory.class)); }
Source:
<code>public void process(ClusterEvent event) throws Exception { HelixManager helixManager = event.getAttribute(AttributeName.helixmanager.name()); Set<String> aggregationEnabledTypes = new HashSet<>(); <START> if (helixManager.getHelixDataAccessor().getProperty( <END> helixManager.getHelixDataAccessor().keyBuilder().customizedStateConfig()) != null) { aggregationEnabledTypes = new HashSet<>(helixManager.getHelixDataAccessor().getProperty( helixManager.getHelixDataAccessor().keyBuilder().customizedStateConfig()) .getRecord().getListFields().get( CustomizedStateConfig.CustomizedStateProperty.AGGREGATION_ENABLED_TYPES .name())); } _eventId = event.getEventId(); BaseControllerDataProvider cache = event.getAttribute(AttributeName.ControllerDataProvider.name()); final Map<String, Resource> resourceMap = event.getAttribute(AttributeName.RESOURCES.name()); if (cache == null || resourceMap == null) { throw new StageException( "Missing attributes in event:" + event + ". Requires DataCache|RESOURCE"); } Map<String, LiveInstance> liveInstances = cache.getLiveInstances(); final CustomizedStateOutput customizedStateOutput = new CustomizedStateOutput(); for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); for (String customizedStateType : aggregationEnabledTypes) { Map<String, CustomizedState> customizedStateMap = cache.getCustomizedState(instanceName, customizedStateType); updateCustomizedStates(instance, customizedStateType, customizedStateMap, customizedStateOutput, resourceMap); } } event.addAttribute(AttributeName.CUSTOMIZED_STATE.name(), customizedStateOutput); }</code><technical_language>refreshed this in BaseControllerDataProvider, result here</technical_language>

Target:
public void process(ClusterEvent event) throws Exception { _eventId = event.getEventId(); ResourceControllerDataProvider cache = event.getAttribute(AttributeName.ControllerDataProvider.name()); final Map<String, Resource> resourceMap = event.getAttribute(AttributeName.RESOURCES_TO_REBALANCE.name()); Set<String> aggregationEnabledTypes = cache.getAggregationEnabledCustomizedStateTypes(); if (cache == null || resourceMap == null) { throw new StageException( "Missing attributes in event:" + event + ". Requires DataCache|RESOURCE"); } Map<String, LiveInstance> liveInstances = cache.getLiveInstances(); final CustomizedStateOutput customizedStateOutput = new CustomizedStateOutput(); for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); for (String customizedStateType : aggregationEnabledTypes) { Map<String, CustomizedState> customizedStateMap = cache.getCustomizedState(instanceName, customizedStateType); updateCustomizedStates(instanceName, customizedStateType, customizedStateMap, customizedStateOutput, resourceMap); } } event.addAttribute(AttributeName.CUSTOMIZED_STATE.name(), customizedStateOutput); }
Source:
<code>public void testCommitShortInfo() throws Exception { GHRepository r = gitHub.getRepository("github-api/github-api"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f23"); assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Kohsuke Kawaguchi"); assertEquals(commit.getCommitShortInfo().getMessage(), "doc"); assertFalse(commit.getCommitShortInfo().getVerification().getVerified()); <START> assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHReason.UNSIGNED.get()); <END> }</code><technical_language>noted above, need tests for a more GHReason values (specifically multi-word values)</technical_language>

Target:
public void testCommitShortInfo() throws Exception { GHRepository r = gitHub.getRepository("github-api/github-api"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f23"); assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Kohsuke Kawaguchi"); assertEquals(commit.getCommitShortInfo().getMessage(), "doc"); assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.UNSIGNED); }
Source:
<code>public void modified(@Nullable Map<String, Object> configMap) { if (connection != null) { connection.stop(); } if (configMap == null || configMap.isEmpty() || mqttService == null) { return; } MqttBrokerConnectionConfig config = new Configuration(configMap).as(MqttBrokerConnectionConfig.class); try { String brokerID = config.getBrokerID(); if (StringUtils.isBlank(brokerID)) { logger.warn("Ignore invalid broker connection configuration: {}", config); return; } <START> assert brokerID != null; <END> assert mqttService != null; connection = mqttService.addBrokerConnection(brokerID, config); if (connection == null) { logger.warn("Ignore existing broker connection configuration for: {}", brokerID); return; } assert connection != null; connection.start(); } catch (ConfigurationException | IllegalArgumentException e) { logger.warn("MqttBroker connection configuration faulty: {}", e.getMessage()); } catch (MqttException e) { logger.warn("MqttBroker start failed: {}", e.getMessage(), e); } }</code><technical_language>This handled StringUtils.isBlank(brokerID)</technical_language>

Target:
public void modified(@Nullable Map<String, Object> configMap) { if (connection != null) { connection.stop(); } if (configMap == null || configMap.isEmpty() || mqttService == null) { return; } final @NonNull MqttService service = (@NonNull MqttService) mqttService; MqttBrokerConnectionConfig config = new Configuration(configMap).as(MqttBrokerConnectionConfig.class); try { String brokerID = config.getBrokerID(); if (StringUtils.isBlank(brokerID) || brokerID == null) { logger.warn("Ignore invalid broker connection configuration: {}", config); return; } MqttBrokerConnection c = service.addBrokerConnection(brokerID, config); connection = c; if (c == null) { logger.warn("Ignore existing broker connection configuration for: {}", brokerID); return; } c.start(); } catch (ConfigurationException | IllegalArgumentException e) { logger.warn("MqttBroker connection configuration faulty: {}", e.getMessage()); } catch (MqttException e) { logger.warn("MqttBroker start failed: {}", e.getMessage(), e); } }
Source:
<code>public <K, V> void send(final String topic, final K key, final V value, final Headers headers, final Long timestamp, final Serializer<K> keySerializer, final Serializer<V> valueSerializer, final StreamPartitioner<? super K, ? super V> partitioner) { <START> Integer partition = null; <END> if (partitioner != null) { final List<PartitionInfo> partitions = producer.partitionsFor(topic); if (partitions.size() > 0) { partition = partitioner.partition(topic, key, value, partitions.size()); } else { throw new StreamsException("Could not get partition information for topic '" + topic + "' for task " + taskId + ". This can happen if the topic does not exist."); } } send(topic, key, value, headers, partition, timestamp, keySerializer, valueSerializer); }</code><technical_language>nit: set final refactor as: final Integer partition; if (partitioner != null) { final List<PartitionInfo> partitions = producer.partitionsFor(topic); if (partitions.size() > 0) { partition = partitioner.partition(topic, key, value, partitions.size()); } else { throw new StreamsException("Could get partition information for topic '" + topic + "' for task " + taskId + ". This happen if topic exist."); } } else { partition = null; }</technical_language>

Target:
public <K, V> void send(final String topic, final K key, final V value, final Headers headers, final Long timestamp, final Serializer<K> keySerializer, final Serializer<V> valueSerializer, final StreamPartitioner<? super K, ? super V> partitioner) { final Integer partition; if (partitioner != null) { final List<PartitionInfo> partitions = producer.partitionsFor(topic); if (partitions.size() > 0) { partition = partitioner.partition(topic, key, value, partitions.size()); } else { throw new StreamsException("Could not get partition information for topic '" + topic + "' for task " + taskId + ". This can happen if the topic does not exist."); } } else { partition = null; } send(topic, key, value, headers, partition, timestamp, keySerializer, valueSerializer); }
Source:
<code><START> public void testAddTwoReviewersAndRemoveOne() throws Exception { <END> }</code><technical_language>write tests for removing a reviewer is review, removing a reviewer is a valid user</technical_language>

Target:
public void testAddTwoReviewersAndRemoveOne() throws Exception { List<String> reviewers = Arrays.asList(new String[] { "admin", "tests" }); List<Integer> userid = Arrays.asList(new Integer[] { 1000000, 1000001 }); ReviewerResult reviewerResult = reviewHarness.getClient().addReviewers(reviewHarness.getShortId(), reviewers, new NullProgressMonitor()); reviewHarness.retrieve(); assertReviewerResult(reviewerResult, null, userid); String reviewer = "tests"; ReviewerResult removeReviewerResult = reviewHarness.getClient().removeReviewer(reviewHarness.getShortId(), reviewer, new NullProgressMonitor()); reviewHarness.retrieve(); reviewers.remove(1); userid.remove(1); assertReviewerResult(removeReviewerResult, null, userid); }
Source:
<code>public List<String> getSupportedTypes() { final List<String> types = new ArrayList<>(); types.add(Constants.REMOTE_TYPE); <START> return types; <END> }</code><technical_language>block replaced with: return Collections.singletonList(Constants.REMOTE_TYPE);</technical_language>

Target:
public List<String> getSupportedTypes() { return Collections.singletonList(Constants.REMOTE_TYPE); }
Source:
<code>public void distributeEntities() { Iterable<Entity> entityProvider = getConfig(ENTITY_PROVIDER); Function<Entity, String> bucketFunction = getConfig(BUCKET_FUNCTION); EntitySpec<? extends Group> groupSpec = getConfig(GROUP_SPEC); if (entityProvider == null) return; if (bucketFunction == null) return; if (groupSpec == null) return; for (Entity e : entityProvider) { for (Group g : bucketsByName.values()) g.removeMember(e); String bucketName = bucketFunction.apply(e); if (bucketName == null) continue; Group bucket = bucketsByName.get(bucketName); if (bucket == null) { <START> bucket = addChild(groupSpec.displayName(bucketName)); <END> Entities.manage(bucket); bucketsByName.put(bucketName, bucket); } bucket.addMember(e); } for (Group g : bucketsByName.values()) { if (g.getMembers().isEmpty()) removeChild(g); } }</code><technical_language>get this, this is modifying a shared instance of groupSpec instance (the EntitySpec is mutated methods). practice (probably) do EntitySpec.create(groupSpec).displayName(bucketName)</technical_language>

Target:
public void distributeEntities() { Predicate<? super Entity> entityFilter = getConfig(ENTITY_FILTER); Function<Entity, String> bucketFunction = getConfig(BUCKET_FUNCTION); EntitySpec<? extends Group> groupSpec = getConfig(BUCKET_SPEC); if (entityFilter == null) return; if (bucketFunction == null) return; if (groupSpec == null) return; for (Entity e : getManagementContext().getEntityManager().getEntities()) { if (!entityFilter.apply(e)) continue; for (Group g : bucketsByName.values()) g.removeMember(e); String bucketName = bucketFunction.apply(e); if (bucketName == null) continue; Group bucket = bucketsByName.get(bucketName); if (bucket == null) { bucket = addChild(EntitySpec.create(groupSpec).displayName(bucketName)); Entities.manage(bucket); bucketsByName.put(bucketName, bucket); } bucket.addMember(e); } for (Group g : ImmutableSet.copyOf(bucketsByName.values())) { if (g.getMembers().isEmpty()) { bucketsByName.remove(g.getDisplayName()); removeChild(g); Entities.unmanage(g); } } }
Source:
<code>private BlackboardArtifact getNodeArtifact(Node node) { BlackboardArtifact nodeArtifact = node.getLookup().lookup(BlackboardArtifact.class); if (nodeArtifact == null) { try { SleuthkitCase tskCase = Case.getCurrentCaseThrows().getSleuthkitCase(); <START> AbstractFile file = node.getLookup().lookup(AbstractFile.class); <END> List<BlackboardArtifact> artifactsList = tskCase.getBlackboardArtifacts(TSK_ASSOCIATED_OBJECT, file.getId()); for (BlackboardArtifact fileArtifact : artifactsList) { BlackboardAttribute associatedArtifactAttribute = fileArtifact.getAttribute(new BlackboardAttribute.Type(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT)); if (associatedArtifactAttribute != null) { BlackboardArtifact associatedArtifact = fileArtifact.getSleuthkitCase().getBlackboardArtifact(associatedArtifactAttribute.getValueLong()); if (isMessageArtifact(associatedArtifact)) { nodeArtifact = associatedArtifact; } } } } catch (NoCurrentCaseException | TskCoreException ex) { LOGGER.log(Level.SEVERE, "Failed to get file for selected node.", ex); } } return nodeArtifact; }</code><technical_language>Is guaranteed AbstractFile in Node</technical_language>

Target:
private BlackboardArtifact getNodeArtifact(Node node) { BlackboardArtifact nodeArtifact = node.getLookup().lookup(BlackboardArtifact.class); if (nodeArtifact == null) { try { SleuthkitCase tskCase = Case.getCurrentCaseThrows().getSleuthkitCase(); AbstractFile file = node.getLookup().lookup(AbstractFile.class); if (file != null) { List<BlackboardArtifact> artifactsList = tskCase.getBlackboardArtifacts(TSK_ASSOCIATED_OBJECT, file.getId()); for (BlackboardArtifact fileArtifact : artifactsList) { BlackboardAttribute associatedArtifactAttribute = fileArtifact.getAttribute(new BlackboardAttribute.Type(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT)); if (associatedArtifactAttribute != null) { BlackboardArtifact associatedArtifact = fileArtifact.getSleuthkitCase().getBlackboardArtifact(associatedArtifactAttribute.getValueLong()); if (isMessageArtifact(associatedArtifact)) { nodeArtifact = associatedArtifact; } } } } } catch (NoCurrentCaseException | TskCoreException ex) { LOGGER.log(Level.SEVERE, "Failed to get file for selected node.", ex); } } return nodeArtifact; }
Source:
<code>public int getPid() { ITmfEventField pidContext = this.getContent().getField("context._pid"); if (null != pidContext) { return ((Integer) pidContext.getValue()).intValue(); } CtfKernelTrace trace = (CtfKernelTrace) this.getTrace(); ITmfStateSystem ss = trace.getStateSystem(CtfKernelTrace.STATE_ID); <START> Integer threadNode = -1; <END> int retVal = -1; try { threadNode = ss.getQuarkAbsolute(Attributes.CPUS, String.valueOf(getCPU()), Attributes.CURRENT_THREAD); ITmfStateValue sv = ss.querySingleState(this.getTimestamp().getValue(), threadNode).getStateValue(); retVal = sv.unboxInt(); } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (TimeRangeException e) { e.printStackTrace(); } catch (StateSystemDisposedException e) { e.printStackTrace(); } catch (StateValueTypeException e) { e.printStackTrace(); } return retVal; }</code><technical_language>this int too. declared try {}</technical_language>

Target:
public int getPid() { ITmfEventField pidContext = this.getContent().getField("context._pid"); if (null != pidContext) { return ((Integer) pidContext.getValue()).intValue(); } CtfKernelTrace trace = (CtfKernelTrace) this.getTrace(); ITmfStateSystem ss = trace.getStateSystem(CtfKernelTrace.STATE_ID); int retVal = -1; try { int threadNode = -1; threadNode = ss.getQuarkAbsolute(Attributes.CPUS, String.valueOf(getCPU()), Attributes.CURRENT_THREAD); ITmfStateValue sv = ss.querySingleState(this.getTimestamp().getValue(), threadNode).getStateValue(); retVal = sv.unboxInt(); } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (TimeRangeException e) { e.printStackTrace(); } catch (StateSystemDisposedException e) { e.printStackTrace(); } catch (StateValueTypeException e) { e.printStackTrace(); } return retVal; }
Source:
<code><START> public static boolean hasWebBrowser(Context context){ <END> Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("<LINK_0>")); PackageManager pm = context.getPackageManager(); List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size()==0 ? false : true; }</code><technical_language>suggestion private static boolean sHasRunWebBrowserCheck = false; private static boolean sHasWebBrowser = true; public static boolean hasWebBrowser(Context context) { if (sHasRunWebBrowserCheck) { return sHasWebBrowser; } this is static vary much, memoize this affect performance. I tested this suggested code work close working</technical_language>

Target:
public static boolean hasWebBrowser(Context context) { if (sHasRunWebBrowserCheck) { return sHasWebBrowser; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("<LINK_0>")); PackageManager pm = context.getPackageManager(); List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (list.size() == 0) { sHasWebBrowser = false; } sHasRunWebBrowserCheck = true; return sHasWebBrowser; }
Source:
<code>public void testDynamicTaskLoadingNonexistingJar() throws Exception { <START> List<String> taskClasses = new ArrayList<String>(); <END> taskClasses.add("com.mycompany.mocktask.MockTask"); DynamicTaskConfig taskConfig = new DynamicTaskConfig("Reindex", "src/test/resources/Random.jar", "1.0.0", taskClasses, "com.mycompany.mocktask.MockTaskFactory"); String path = TaskConstants.DYNAMICALLY_LOADED_TASK_PATH + "/Reindex"; removePathIfExists(path); _manager.getHelixDataAccessor().getBaseDataAccessor() .create(path, taskConfig.getTaskConfigZNRecord(), AccessOption.PERSISTENT); TaskDriver driver = new TaskDriver(_manager); String workflowName = TestHelper.getTestMethodName(); submitWorkflow(workflowName, driver); try { TaskState finalState = driver.pollForWorkflowState(workflowName, TaskState.COMPLETED, TaskState.FAILED); AssertJUnit.assertEquals(finalState, TaskState.FAILED); } catch (HelixException e) { AssertJUnit.fail(e.getMessage()); } }</code><technical_language><String> is necessary in new ArrayList<String>(); coding in Java 8? Please fix environment</technical_language>

Target:
public void testDynamicTaskLoadingNonexistingJar() throws Exception { String taskCommand = "Reindex"; String taskJarPath = "src/test/resources/Random.jar"; String taskVersion = "1.0.0"; String fullyQualifiedTaskClassName = "com.mycompany.mocktask.MockTask"; String fullyQualifiedTaskFactoryClassName = "com.mycompany.mocktask.MockTaskFactory"; List<String> taskClasses = new ArrayList(); taskClasses.add(fullyQualifiedTaskClassName); DynamicTaskConfig taskConfig = new DynamicTaskConfig(taskCommand, taskJarPath, taskVersion, taskClasses, fullyQualifiedTaskFactoryClassName); String path = TaskConstants.DYNAMICALLY_LOADED_TASK_PATH + "/" + taskCommand; removePathIfExists(path); _manager.getHelixDataAccessor().getBaseDataAccessor() .create(path, taskConfig.getTaskConfigZNRecord(), AccessOption.PERSISTENT); TaskDriver driver = new TaskDriver(_manager); String workflowName = TestHelper.getTestMethodName(); submitWorkflow(workflowName, driver); TaskState finalState = driver.pollForWorkflowState(workflowName, TaskState.COMPLETED, TaskState.FAILED); Assert.assertEquals(finalState, TaskState.FAILED); }
Source:
<code>public CallbackResult<Collection<ValueType>> call() { final long start = System.currentTimeMillis(); if(!cache.acquireLock()) { log.debug("{}: Unable to acquire refresh lock for", cache.getCacheName()); cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(new LockUnavailableException()); } <START> log.debug("{}: Attempting to refresh data for", cache.getCacheName()); <END> try { final Collection<ValueType> values = cache.loadAll(); if (values == null) { cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(); } log.info("{}: Async refresh for {}", cache.getCacheName()); Map<KeyType, ValueType> valuesMap = new HashMap<>(); for (ValueType value : values) { valuesMap.put(cache.keyFromValue(value), value); } cache.putAll(valuesMap); cache.markLoadSuccess(System.currentTimeMillis() - start); cache.loadAllComplete(); return new CallbackResult<>(values); } catch (Exception ex) { cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(ex); } finally { cache.releaseLock(); } }</code><technical_language>small - drop " for"</technical_language>

Target:
public CallbackResult<Collection<ValueType>> call() { final long start = System.currentTimeMillis(); if(!cache.acquireLock()) { log.debug("{}: Unable to acquire refresh lock", cache.getCacheName()); cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(new LockUnavailableException()); } log.debug("{}: Attempting to refresh data", cache.getCacheName()); try { final Collection<ValueType> values = cache.loadAll(); if (values == null) { cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(); } log.info("{}: Async refresh", cache.getCacheName()); Map<KeyType, ValueType> valuesMap = new HashMap<>(); for (ValueType value : values) { valuesMap.put(cache.keyFromValue(value), value); } cache.putAll(valuesMap); cache.markLoadSuccess(System.currentTimeMillis() - start); cache.loadAllComplete(); return new CallbackResult<>(values); } catch (Exception ex) { cache.markLoadException(System.currentTimeMillis() - start); return new CallbackResult<>(ex); } finally { cache.releaseLock(); } }