text:
#import "MXKSampleMainTableViewController.h"
#import "MXKSampleRoomViewController.h"
#import "MXKSampleJSQMessagesViewController.h"
#import "MXKSampleRoomMembersViewController.h"
#import "MXKWebViewViewController.h"

#import <MatrixSDK/MXFileStore.h>

@interface MXKSampleMainTableViewController ()
{
    /**
     Observer matrix sessions state.
     */
    id matrixSessionStateObserver;

    /**
     Observer used to handle call.
     */
    id callObserver;

    /**
     The current selected room.
     */
    MXRoom *selectedRoom;

    /**
     The current selected room member.
     */
    MXRoomMember *selectedRoomMember;

    /**
     The current selected account.
     */
    MXKAccount *selectedAccount;

    /**
     The current selected contact
     */
    MXKContact *selectedContact;

    /**
     The current call view controller (if any).
     */
    MXKCallViewController *currentCallViewController;

    /**
     Call status window displayed when user goes back to app during a call.
     */
    UIWindow* callStatusBarWindow;
    UIButton* callStatusBarButton;

    /**
     Current index of sections
     */
    NSInteger accountSectionIndex;
    NSInteger recentsSectionIndex;
    NSInteger roomSectionIndex;
    NSInteger roomMembersSectionIndex;
    NSInteger searchSectionIndex;
    NSInteger authenticationSectionIndex;
    NSInteger contactSectionIndex;
    NSInteger webViewSectionIndex;
    NSInteger countrySectionIndex;
}

@end

@implementation MXKSampleMainTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.tableHeaderView.hidden = ![MXKAccountManager sharedManager].activeAccounts.count;
    self.tableView.allowsSelection = YES;

    // Register matrix session state observer
    matrixSessionStateObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kMXSessionStateDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {

        MXSession *mxSession = (MXSession*)notif.object;

        if (mxSession.state == MXSessionStateClosed)
        {
            [self removeMatrixSession:mxSession];
            [[MXKContactManager sharedManager] removeMatrixSession:mxSession];
        }
        else
        {
            // Check whether the concerned session is a new one
            if ([self.mxSessions indexOfObject:mxSession] == NSNotFound)
            {
                // Report created matrix session
                [self addMatrixSession:mxSession];
                [[MXKContactManager sharedManager] addMatrixSession:mxSession];
            }
        }

        // Check whether the room selection is available, and update table header visibility
        BOOL isRoomSelectionEnabled = [MXKAccountManager sharedManager].activeAccounts.count;
        if (self.tableView.tableHeaderView.hidden == isRoomSelectionEnabled)
        {
            self.tableView.tableHeaderView.hidden = !isRoomSelectionEnabled;
            [self.tableView reloadData];
        }
    }];

    // Register call observer in order to handle voip call
    callObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kMXCallManagerNewCall object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {

        // Ignore the call if a call is already in progress
        if (!self->currentCallViewController)
        {
            MXCall *mxCall = (MXCall*)notif.object;

            self->currentCallViewController = [MXKCallViewController callViewController:mxCall];
            self->currentCallViewController.delegate = self;

            UINavigationController *navigationController = self.navigationController;
            [navigationController.topViewController presentViewController:self->currentCallViewController animated:YES completion:nil];

            // Hide system status bar
            [UIApplication sharedApplication].statusBarHidden = YES;
        }
    }];

    // Add observer to handle new account
    [[NSNotificationCenter defaultCenter] addObserverForName:kMXKAccountManagerDidAddAccountNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {

        // Check whether room selection is available
        self.tableView.tableHeaderView.hidden = ![MXKAccountManager sharedManager].activeAccounts.count;

        // Refresh table to add this new account
        [self.tableView reloadData];
    }];

    [[NSNotificationCenter defaultCenter] addObserverForName:kMXKAccountManagerDidRemoveAccountNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {

        MXKAccount *mxAccount = notif.object;
        if (mxAccount)
        {
            // Check whether details of this account was displayed
            if (self.childViewControllers.count)
            {
                for (id viewController in self.childViewControllers)
                {
                    if ([viewController isKindOfClass:[MXKAccountDetailsViewController class]])
                    {
                        MXKAccountDetailsViewController *accountDetailsViewController = (MXKAccountDetailsViewController*)viewController;
                        if ([accountDetailsViewController.mxAccount.mxCredentials.userId isEqualToString:mxAccount.mxCredentials.userId])
                        {
                            // pop the account details view controller
                            [self.navigationController popToRootViewControllerAnimated:YES];
                            break;
                        }
                    }
                }
            }
        }

        if (![MXKAccountManager sharedManager].accounts.count)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self logout];
            });
        }
        else
        {
            // Check whether room selection is available
            self.tableView.tableHeaderView.hidden = ![MXKAccountManager sharedManager].activeAccounts.count;

            // Refresh table to remove this account
            [self.tableView reloadData];
        }
    }];

    // Add observer to update accounts section
    [[NSNotificationCenter defaultCenter] addObserverForName:kMXKAccountUserInfoDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {
        // Refresh table to remove this account
        [self.tableView reloadData];
    }];

    // Observers have been set, we will start now a matrix session for each enabled accounts.
    // As there is no mock for MatrixSDK yet, use an actual Matrix file store to boost init
    [MXKAccountManager sharedManager].storeClass = [MXFileStore class];
    [[MXKAccountManager sharedManager] prepareSessionForActiveAccounts];

    // Check whether some accounts are availables
    if (![[MXKAccountManager sharedManager] accounts].count)
    {
        // Ask for a matrix account first
        [self performSegueWithIdentifier:@"showMXKAuthenticationViewController" sender:self];
    }

    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (selectedRoom)
    {
        // Let the manager release the previous room data source
        MXKRoomDataSourceManager *roomDataSourceManager = [MXKRoomDataSourceManager sharedManagerForMatrixSession:selectedRoom.mxSession];
        [roomDataSourceManager closeRoomDataSourceWithRoomId:selectedRoom.roomId forceClose:NO];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)login
{
    // Show authentication screen
    [self performSegueWithIdentifier:@"showMXKAuthenticationViewController" sender:self];
}

- (void)logout
{
    // Clear cache
    [MXMediaManager clearCache];

    // Logout all matrix account
    [[MXKAccountManager sharedManager] logoutWithCompletion:nil];

    // Reset
    NSArray *mxSessions = self.mxSessions;
    for (MXSession *mxSession in mxSessions)
    {
        [self removeMatrixSession:mxSession];
    }
    selectedRoom = nil;
    _selectedRoomDisplayName.text = nil;

    // Update display
    self.tableView.tableHeaderView.hidden = YES;
    self.selectedRoomDisplayName.text = @"Please select a room";
    [self.tableView reloadData];
}

- (IBAction)onAccountToggleChange:(id)sender
{
    UISwitch *accountSwitchToggle = sender;

    NSArray *accounts = [[MXKAccountManager sharedManager] accounts];
    if (accountSwitchToggle.tag < accounts.count)
    {
        MXKAccount *account = [accounts objectAtIndex:accountSwitchToggle.tag];
        account.disabled = !accountSwitchToggle.on;
    }

    [self.tableView reloadData];
}

// Test code for directly opening a Room VC
//- (void)didMatrixSessionStateChange{
//
//    [super didMatrixSessionStateChange];
//
//    if (self.mxSession.state == MXKDataSourceStateReady){
//        // Test code for directly opening a VC
//        NSString *roomId = @"!xxx";
//        selectedRoom = [self.mxSession roomWithRoomId:roomId];
//        [self performSegueWithIdentifier:@"showMXKRoomViewController" sender:self];
//    }
//
//}

#pragma mark - Table View Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger count = 0;

    accountSectionIndex = recentsSectionIndex = roomSectionIndex = roomMembersSectionIndex = searchSectionIndex =authenticationSectionIndex = contactSectionIndex = webViewSectionIndex = countrySectionIndex = -1;

    accountSectionIndex = count++;

    if ([[MXKAccountManager sharedManager] accounts].count)
    {
        recentsSectionIndex = count++;
    }

    if (selectedRoom)
    {
        roomSectionIndex = count++;
        roomMembersSectionIndex = count++;
    }

    if ([[MXKAccountManager sharedManager] accounts].count)
    {
        searchSectionIndex = count++;
    }

    authenticationSectionIndex = count++;
    contactSectionIndex = count++;
    webViewSectionIndex = count++;
    countrySectionIndex = count++;

    return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == accountSectionIndex)
    {
        if ([[MXKAccountManager sharedManager] accounts].count)
        {
            return [[MXKAccountManager sharedManager] accounts].count + 2; // Add 2 cells in this section to add actions: add account, logout all.
        }
        return 1; // Display only "Add account" action button.
    }
    else if (section == recentsSectionIndex)
    {
        return 2;
    }
    else if (section == roomSectionIndex)
    {
        return 3;
    }
    else if (section == roomMembersSectionIndex)
    {
        return 2;
    }
    else if (section == searchSectionIndex)
    {
        if (selectedRoom)
        {
            return 2;
        }
        return 1;
    }
    else if (section == authenticationSectionIndex)
    {
        return 1;
    }
    else if (section == contactSectionIndex)
    {
        return 1;
    }
    else if (section == webViewSectionIndex)
    {
        return 1;
    }
    else if (section == countrySectionIndex)
    {
        return 1;
    }

    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == accountSectionIndex)
    {
        return @"Accounts:";
    }
    else if (section == recentsSectionIndex)
    {
        return @"Recents:";
    }
    else if (section == roomSectionIndex)
    {
        return @"Rooms:";
    }
    else if (section == roomMembersSectionIndex)
    {
        return @"Room members:";
    }
    else if (section == searchSectionIndex)
    {
        return @"Search:";
    }
    else if (section == authenticationSectionIndex)
    {
        return @"Authentication:";
    }
    else if (section == contactSectionIndex)
    {
        return @"Contacts:";
    }
    else if (section == webViewSectionIndex)
    {
        return @"Webview:";
    }
    else if (section == countrySectionIndex)
    {
        return @"Country:";
    }

    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;

    if (indexPath.section == accountSectionIndex)
    {
        NSArray *accounts = [[MXKAccountManager sharedManager] accounts];
        if (indexPath.row < accounts.count)
        {
            MXKAccountTableViewCell *accountCell = [tableView dequeueReusableCellWithIdentifier:[MXKAccountTableViewCell defaultReuseIdentifier]];
            if (!accountCell)
            {
                accountCell = [[MXKAccountTableViewCell alloc] init];
            }

            accountCell.mxAccount = [accounts objectAtIndex:indexPath.row];

            // Display switch toggle in case of multiple accounts
            if (accounts.count > 1 || accountCell.mxAccount.disabled)
            {
                accountCell.accountSwitchToggle.tag = indexPath.row;
                accountCell.accountSwitchToggle.hidden = NO;
                [accountCell.accountSwitchToggle addTarget:self action:@selector(onAccountToggleChange:) forControlEvents:UIControlEventValueChanged];
            }

            cell = accountCell;
        }
        else if (indexPath.row == accounts.count)
        {
            MXKTableViewCellWithButton *addBtnCell = [tableView dequeueReusableCellWithIdentifier:[MXKTableViewCellWithButton defaultReuseIdentifier]];
            if (!addBtnCell)
            {
                addBtnCell = [[MXKTableViewCellWithButton alloc] init];
            }
            [addBtnCell.mxkButton setTitle:@"Add account" forState:UIControlStateNormal];
            [addBtnCell.mxkButton setTitle:@"Add account" forState:UIControlStateHighlighted];
            [addBtnCell.mxkButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];

            cell = addBtnCell;
        }
        else
        {
            MXKTableViewCellWithButton *logoutBtnCell = [tableView dequeueReusableCellWithIdentifier:[MXKTableViewCellWithButton defaultReuseIdentifier]];
            if (!logoutBtnCell)
            {
                logoutBtnCell = [[MXKTableViewCellWithButton alloc] init];
            }
            [logoutBtnCell.mxkButton setTitle:@"Logout all accounts" forState:UIControlStateNormal];
            [logoutBtnCell.mxkButton setTitle:@"Logout all accounts" forState:UIControlStateHighlighted];
            [logoutBtnCell.mxkButton addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];

            cell = logoutBtnCell;
        }
    }
    else if (indexPath.section == recentsSectionIndex)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"mainTableViewCellSampleVC" forIndexPath:indexPath];
        switch (indexPath.row)
        {
            case 0:
                cell.textLabel.text = @"MXKRecentListViewController";
                break;
            case 1:
                cell.textLabel.text = @"Interleaved Recents";
                break;
        }
    }
    else if (indexPath.section == roomSectionIndex)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"mainTableViewCellSampleVC" forIndexPath:indexPath];
        switch (indexPath.row)
        {
            case 0:
                cell.textLabel.text = @"MXKRoomViewController";
                break;
            case 1:
                cell.textLabel.text = @"Sample with editable title and growing text input";
                break;
            case 2:
                cell.textLabel.text = @"Sample based on JSQMessagesViewController lib";
                break;
        }
    }
    else if (indexPath.section == roomMembersSectionIndex)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"mainTableViewCellSampleVC" forIndexPath:indexPath];
        switch (indexPath.row)
        {
            case 0:
                cell.textLabel.text = @"MXKRoomMemberListViewController";
                break;
            case 1:
                cell.textLabel.text = @"Sample with customized Table View Cell";
                break;
        }
    }
    else if (indexPath.section == searchSectionIndex)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:@"mainTableViewCellSampleVC" forIndexPath:indexPath];
        switch (indexPath.row)
        {
            case 0:
                cell.textLabel.text = @"MXKSearchViewController";
                break;
            case 1:
                cell.textLabel.text = @"MXKSearchViewController on one room";
                break;
        }
    }
    else if (indexPath.section == authenticationSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                cell = [tableView dequeueReusableCellWithIdentifier:@"mainTableViewCellSampleVC" forIndexPath:indexPath];
                cell.textLabel.text = @"MXKAuthenticationViewController";
                break;
        }
    }
    else if (indexPath.section == contactSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                cell = [tableView dequeueReusableCellWithIdentifier:@"mainTableViewCellSampleVC" forIndexPath:indexPath];
                cell.textLabel.text = @"MXKContactListViewController";
                break;
        }
    }
    else if (indexPath.section == webViewSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                cell = [tableView dequeueReusableCellWithIdentifier:@"mainTableViewCellSampleVC" forIndexPath:indexPath];
                cell.textLabel.text = @"MXKWebViewViewController";
                break;
        }
    }
    else if (indexPath.section == countrySectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                cell = [tableView dequeueReusableCellWithIdentifier:@"mainTableViewCellSampleVC" forIndexPath:indexPath];
                cell.textLabel.text = @"MXKCountryPickerViewController";
                break;
        }
    }

    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == accountSectionIndex)
    {
        return 50;
    }
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.section == accountSectionIndex)
    {
        NSArray *accounts = [[MXKAccountManager sharedManager] accounts];
        if (indexPath.row < accounts.count)
        {
            selectedAccount = [accounts objectAtIndex:indexPath.row];

            [self performSegueWithIdentifier:@"showMXKAccountDetailsViewController" sender:self];
        }
    }
    else if (indexPath.section == recentsSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                [self performSegueWithIdentifier:@"showMXKRecentListViewController" sender:self];
                break;
            case 1:
                [self performSegueWithIdentifier:@"showInterleavedRecentsViewController" sender:self];
                break;
        }
    }
    else if (indexPath.section == roomSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                [self performSegueWithIdentifier:@"showMXKRoomViewController" sender:self];
                break;
            case 1:
                [self performSegueWithIdentifier:@"showSampleRoomViewController" sender:self];
                break;
            case 2:
                [self performSegueWithIdentifier:@"showSampleJSQMessagesViewController" sender:self];
                break;
        }
    }
    else if (indexPath.section == roomMembersSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                [self performSegueWithIdentifier:@"showMXKRoomMemberListViewController" sender:self];
                break;
            case 1:
                [self performSegueWithIdentifier:@"showSampleRoomMembersViewController" sender:self];
                break;
        }
    }
    else if (indexPath.section == searchSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                [self performSegueWithIdentifier:@"showMXKSearchViewController" sender:self];
                break;
            case 1:
                [self performSegueWithIdentifier:@"showMXKSearchViewControllerForRoom" sender:self];
                break;
        }
    }
    else if (indexPath.section == authenticationSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                [self performSegueWithIdentifier:@"showMXKAuthenticationViewController" sender:self];
                break;
        }
    }
    else if (indexPath.section == contactSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
                [self performSegueWithIdentifier:@"showMXKContactListViewController" sender:self];
                break;
        }
    }
    else if (indexPath.section == webViewSectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
            {
                MXKWebViewViewController *webViewViewController = [[MXKWebViewViewController alloc] initWithURL:@"https://www.matrix.org"];
                [self.navigationController pushViewController:webViewViewController animated:YES];
                break;
            }
        }
    }
    else if (indexPath.section == countrySectionIndex)
    {
        switch (indexPath.row)
        {
            case 0:
            {
                MXKCountryPickerViewController *countryPicker = [MXKCountryPickerViewController countryPickerViewController];
                countryPicker.delegate = self;
                countryPicker.showCountryCallingCode = YES;
                [self.navigationController pushViewController:countryPicker animated:YES];
                break;
            }
        }
    }
}

#pragma mark - Segues

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [super prepareForSegue:segue sender:sender];

    id destinationViewController = segue.destinationViewController;

    if (([segue.identifier isEqualToString:@"showMXKRecentListViewController"] || [segue.identifier isEqualToString:@"showRoomSelector"]) && self.mainSession)
    {
        MXKRecentListViewController *recentListViewController = (MXKRecentListViewController *)destinationViewController;
        recentListViewController.delegate = self;

        // Prepare listDataSource
        MXKRecentsDataSource *listDataSource = [[MXKRecentsDataSource alloc] init];
        NSArray* accounts = [[MXKAccountManager sharedManager] activeAccounts];
        for (MXKAccount *account in accounts)
        {
            if (account.mxSession)
            {
                [listDataSource addMatrixSession:account.mxSession];
            }
        }
        [recentListViewController displayList:listDataSource];
    }
    else if ([segue.identifier isEqualToString:@"showInterleavedRecentsViewController"] && self.mainSession)
    {
        MXKRecentListViewController *recentListViewController = (MXKRecentListViewController *)destinationViewController;
        recentListViewController.delegate = self;

        // Prepare listDataSource
        MXKInterleavedRecentsDataSource *listDataSource = [[MXKInterleavedRecentsDataSource alloc] init];
        NSArray* accounts = [[MXKAccountManager sharedManager] activeAccounts];
        for (MXKAccount *account in accounts)
        {
            if (account.mxSession)
            {
                [listDataSource addMatrixSession:account.mxSession];
            }
        }
        [recentListViewController displayList:listDataSource];
    }
    else if ([segue.identifier isEqualToString:@"showMXKRoomViewController"] || [segue.identifier isEqualToString:@"showSampleRoomViewController"])
    {
        MXKRoomViewController *roomViewController = (MXKRoomViewController *)destinationViewController;

        // Update the RoomDataSource class at manager level
        [MXKRoomDataSourceManager registerRoomDataSourceClass:MXKRoomDataSource.class];

        MXKRoomDataSourceManager *roomDataSourceManager = [MXKRoomDataSourceManager sharedManagerForMatrixSession:selectedRoom.mxSession];
        [roomDataSourceManager roomDataSourceForRoom:selectedRoom.roomId create:YES onComplete:^(MXKRoomDataSource *roomDataSource) {
            [roomViewController displayRoom:roomDataSource];
        }];
    }
    else if ([segue.identifier isEqualToString:@"showSampleJSQMessagesViewController"])
    {
        MXKSampleJSQMessagesViewController *sampleRoomViewController = (MXKSampleJSQMessagesViewController *)destinationViewController;

        // Update the RoomDataSource class at manager level
        [MXKRoomDataSourceManager registerRoomDataSourceClass:MXKSampleJSQRoomDataSource.class];

        MXKRoomDataSourceManager *roomDataSourceManager = [MXKRoomDataSourceManager sharedManagerForMatrixSession:selectedRoom.mxSession];

        [roomDataSourceManager roomDataSourceForRoom:selectedRoom.roomId create:YES onComplete:^(MXKRoomDataSource *roomDataSource) {

            MXKSampleJSQRoomDataSource *JSQRoomDataSource = (MXKSampleJSQRoomDataSource *)roomDataSource;
            [sampleRoomViewController displayRoom:JSQRoomDataSource];
        }];
    }
    else if ([segue.identifier isEqualToString:@"showMXKRoomMemberListViewController"])
    {
        MXKRoomMemberListViewController *roomMemberListViewController = (MXKRoomMemberListViewController *)destinationViewController;
        roomMemberListViewController.delegate = self;

        MXKRoomMemberListDataSource *listDataSource = [[MXKRoomMemberListDataSource alloc] initWithRoomId:selectedRoom.roomId andMatrixSession:selectedRoom.mxSession];

        [listDataSource finalizeInitialization];

        [roomMemberListViewController displayList:listDataSource];
    }
    else if ([segue.identifier isEqualToString:@"showSampleRoomMembersViewController"])
    {
        MXKSampleRoomMembersViewController *sampleRoomMemberListViewController = (MXKSampleRoomMembersViewController *)destinationViewController;
        sampleRoomMemberListViewController.delegate = self;

        MXKRoomMemberListDataSource *listDataSource = [[MXKRoomMemberListDataSource alloc] initWithRoomId:selectedRoom.roomId andMatrixSession:selectedRoom.mxSession];

        [listDataSource finalizeInitialization];

        [sampleRoomMemberListViewController displayList:listDataSource];
    }
    else if ([segue.identifier isEqualToString:@"showMXKSearchViewController"])
    {
        MXKSearchViewController *searchViewController = (MXKSearchViewController*)destinationViewController;
        MXKSearchDataSource *searchDataSource = [[MXKSearchDataSource alloc] initWithMatrixSession:self.mainSession];

        [searchViewController displaySearch:searchDataSource];
    }
    else if ([segue.identifier isEqualToString:@"showMXKSearchViewControllerForRoom"])
    {
        MXKSearchViewController *searchViewController = (MXKSearchViewController*)destinationViewController;
        MXKSearchDataSource *searchDataSource = [[MXKSearchDataSource alloc] initWithMatrixSession:self.mainSession];
        searchDataSource.roomEventFilter.rooms = @[selectedRoom.roomId];

        [searchViewController displaySearch:searchDataSource];
    }
    else if ([segue.identifier isEqualToString:@"showMXKAuthenticationViewController"])
    {
        MXKAuthenticationViewController *authViewController = (MXKAuthenticationViewController *)destinationViewController;
        authViewController.delegate = self;
        authViewController.defaultHomeServerUrl = @"https://matrix.org";
        authViewController.defaultIdentityServerUrl = @"https://matrix.org";
    }
    else if ([segue.identifier isEqualToString:@"showMXKContactListViewController"])
    {
        MXKContactListViewController *contactsController = (MXKContactListViewController *)destinationViewController;
        NSArray* accounts = [[MXKAccountManager sharedManager] activeAccounts];
        for (MXKAccount *account in accounts)
        {
            if (account.mxSession)
            {
                [contactsController addMatrixSession:account.mxSession];
            }
        }
        contactsController.delegate = self;
    }
    else if ([segue.identifier isEqualToString:@"showMXKAccountDetailsViewController"])
    {
        MXKAccountDetailsViewController *accountViewController = (MXKAccountDetailsViewController *)destinationViewController;
        accountViewController.mxAccount = selectedAccount;
    }
    else if ([segue.identifier isEqualToString:@"showMXKRoomMemberDetailsViewController"])
    {
        MXKRoomMemberDetailsViewController *memberDetails = (MXKRoomMemberDetailsViewController*)destinationViewController;
        [memberDetails displayRoomMember:selectedRoomMember withMatrixRoom:selectedRoom];
        memberDetails.delegate = self;
    }
    else if ([segue.identifier isEqualToString:@"showMXKContactDetailsViewController"])
    {
        MXKContactDetailsViewController *contactDetails = (MXKContactDetailsViewController*)destinationViewController;
        contactDetails.contact = selectedContact;
        contactDetails.delegate = self;
    }
}

#pragma mark - MXKRecentListViewControllerDelegate
- (void)recentListViewController:(MXKRecentListViewController *)recentListViewController didSelectRoom:(NSString *)roomId inMatrixSession:(MXSession *)matrixSession
{
    // Update the selected room and go back to the main page
    selectedRoom = [matrixSession roomWithRoomId:roomId];

    MXRoomSummary *roomSummary = [matrixSession roomSummaryWithRoomId:roomId];
    _selectedRoomDisplayName.text = roomSummary.displayname;

    [self.tableView reloadData];

    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma  mark - MXKRoomMemberListViewControllerDelegate

- (void)roomMemberListViewController:(MXKRoomMemberListViewController *)roomMemberListViewController didSelectMember:(MXRoomMember*)member
{
    MXLogDebug(@"Member (%@) has been selected", member.userId);

    selectedRoomMember = member;

    [self performSegueWithIdentifier:@"showMXKRoomMemberDetailsViewController" sender:self];
}

#pragma mark - MXKAuthenticationViewControllerDelegate

- (void)authenticationViewController:(MXKAuthenticationViewController *)authenticationViewController didLogWithUserId:(NSString*)userId
{
    MXLogDebug(@"New account (%@) has been added", userId);

    // Go back to the main page
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - MXKCallViewControllerDelegate

- (void)dismissCallViewController:(MXKCallViewController *)callViewController completion:(void (^)(void))completion
{
    if (callViewController == currentCallViewController)
    {

        if (callViewController.presentingViewController)
        {
            BOOL callIsEnded = (callViewController.mxCall.state == MXCallStateEnded);
            MXLogDebug(@"Call view controller must be dismissed (%d)", callIsEnded);

            [callViewController dismissViewControllerAnimated:YES completion:^{

                if (!callIsEnded)
                {
                    [self addCallStatusBar];
                }

                if (completion)
                {
                    completion();
                }
            }];

            if (callIsEnded)
            {
                [self removeCallStatusBar];

                // Restore system status bar
                [UIApplication sharedApplication].statusBarHidden = NO;

                // Release properly
                [currentCallViewController destroy];
                currentCallViewController = nil;
            }
        }
        else
        {
            // Here the presentation of the call view controller is in progress
            // Postpone the dismiss
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self dismissCallViewController:callViewController completion:completion];
            });
        }
    }
}

#pragma mark - MXKContactListViewControllerDelegate

- (void)contactListViewController:(MXKContactListViewController *)contactListViewController didSelectContact:(NSString *)contactId
{
    selectedContact = [[MXKContactManager sharedManager] contactWithContactID:contactId];
    MXLogDebug(@"    -> %@ has been selected", selectedContact.displayName);

    [self performSegueWithIdentifier:@"showMXKContactDetailsViewController" sender:self];
}

- (void)contactListViewController:(MXKContactListViewController *)contactListViewController didTapContactThumbnail:(NSString *)contactId
{
    selectedContact = [[MXKContactManager sharedManager] contactWithContactID:contactId];
    MXLogDebug(@"    -> Avatar of %@ has been tapped", selectedContact.displayName);
}

#pragma mark - MXKRoomMemberDetailsViewControllerDelegate

- (void)roomMemberDetailsViewController:(MXKRoomMemberDetailsViewController *)roomMemberDetailsViewController startChatWithMemberId:(NSString *)matrixId completion:(void (^)(void))completion
{
    MXLogDebug(@"    -> Start chat with %@ is requested", matrixId);
}

#pragma mark - MXKContactDetailsViewControllerDelegate

- (void)contactDetailsViewController:(MXKContactDetailsViewController *)contactDetailsViewController startChatWithMatrixId:(NSString *)matrixId completion:(void (^)(void))completion
{
    MXLogDebug(@"    -> Start chat with %@ is requested", matrixId);
}

#pragma mark - MXKCountryPickerViewControllerDelegate

- (void)countryPickerViewController:(MXKCountryPickerViewController*)countryPickerViewController didSelectCountry:(NSString*)isoCountryCode
{
    MXLogDebug(@"    -> Select %@ country", isoCountryCode);
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Call status handling

- (void)addCallStatusBar
{
    // Add a call status bar
    CGSize topBarSize = CGSizeMake(self.view.frame.size.width, 44);

    callStatusBarWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0,0, topBarSize.width,topBarSize.height)];
    callStatusBarWindow.windowLevel = UIWindowLevelStatusBar;

    // Create statusBarButton
    callStatusBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    callStatusBarButton.frame = CGRectMake(0, 0, topBarSize.width,topBarSize.height);
    NSString *btnTitle = @"Return to call";

    [callStatusBarButton setTitle:btnTitle forState:UIControlStateNormal];
    [callStatusBarButton setTitle:btnTitle forState:UIControlStateHighlighted];
    callStatusBarButton.titleLabel.textColor = [UIColor whiteColor];

    [callStatusBarButton setBackgroundColor:[UIColor blueColor]];
    [callStatusBarButton addTarget:self action:@selector(returnToCallView) forControlEvents:UIControlEventTouchUpInside];

    // Place button into the new window
    [callStatusBarWindow addSubview:callStatusBarButton];

    callStatusBarWindow.hidden = NO;
    [self statusBarDidChangeFrame];

    // We need to listen to the system status bar size change events to refresh the root controller frame.
    // Else the navigation bar position will be wrong.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(statusBarDidChangeFrame)
                                                 name:UIApplicationDidChangeStatusBarFrameNotification
                                               object:nil];
}

- (void)removeCallStatusBar
{
    if (callStatusBarWindow)
    {
        // Hide & destroy it
        callStatusBarWindow.hidden = YES;
        [self statusBarDidChangeFrame];
        [callStatusBarButton removeFromSuperview];
        callStatusBarButton = nil;
        callStatusBarWindow = nil;

        // No more need to listen to system status bar changes
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    }
}

- (void)returnToCallView
{
    [self removeCallStatusBar];

    UINavigationController *navigationController = self.navigationController;
    [navigationController.topViewController presentViewController:currentCallViewController animated:YES completion:nil];
}

- (void)statusBarDidChangeFrame
{
    UIApplication *app = [UIApplication sharedApplication];
    UIViewController *rootController = app.keyWindow.rootViewController;

    // Refresh the root view controller frame
    CGRect frame = [[UIScreen mainScreen] applicationFrame];
    if (callStatusBarWindow)
    {
        // Substract the height of call status bar from the frame.
        CGFloat callBarStatusHeight = callStatusBarWindow.frame.size.height;

        CGFloat delta = callBarStatusHeight - frame.origin.y;
        frame.origin.y = callBarStatusHeight;
        frame.size.height -= delta;
    }
    rootController.view.frame = frame;
    [rootController.view setNeedsLayout];
}

@end


text:
<?php

namespace SequelDash;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
		$serviceManager	     = $e->getApplication()->getServiceManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);

		$eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'authPreDispatch'), 100);
		$eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'dispatchError'), 100);
    }

    public function dispatchError($event) {
		$this->authPreDispatch($event);
    }

    /**
     * Authenticate user or redirect to log in
     */
    public function authPreDispatch($event) {
    	if (!SessionManager::isLoggedIn()) {
			if ($event->getRouteMatch()) {
				$exceptions = array('login');

				if ($event->getRouteMatch()->getParam('__CONTROLLER__') == "login"
					&& $event->getRouteMatch()->getParam("action") == "index")
					return; // let them through

				$url = $event->getRequest()->getRequestUri();
				$url = substr($url, strlen($event->getRequest()->getBasePath()));

				SessionManager::setReturnUrl($url);

				$data = (object)array();
				$data->error = 'unauthorized';
				$data->redirectTo = '#/login';
				$stateProvider = new StateProvider;
				$data->state = new \stdclass;
				$stateProvider->prepare($data->state, $event->getRequest());

				die(json_encode($data));
			}
		}
    }

    public function bootstrapSession(MvcEvent $e)
    {
		$session = $e->getApplication()
                     ->getServiceManager()
                     ->get('Zend\Session\SessionManager');
        $session->start();
		$container = new Container('initialized');
        if (!isset($container->init)) {
             $session->regenerateId(true);
             $container->init = 1;
        }
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.sdoward.rxgooglemap;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import rx.observers.TestSubscriber;

import static org.mockito.Mockito.verify;

@RunWith(PowerMockRunner.class)
@PrepareForTest(GoogleMap.class)
public class CameraPositionFuncTest {

    @Mock
    private GoogleMap googleMap;
    @Captor
    private ArgumentCaptor<GoogleMap.OnCameraChangeListener> argumentCaptor;

    @Test
    public void shouldEmmitCameraPosition() throws Exception {
        TestSubscriber<CameraPosition> testSubscriber = new TestSubscriber<>();
        new CameraPositionFunc().call(googleMap)
                .subscribe(testSubscriber);
        verify(googleMap).setOnCameraChangeListener(argumentCaptor.capture());
        CameraPosition cameraPosition = new CameraPosition(new LatLng(1d, 2d), 0, 0, 0);
        argumentCaptor.getValue().onCameraChange(cameraPosition);
        testSubscriber.assertNoErrors();
        testSubscriber.assertValueCount(1);
        testSubscriber.assertValue(cameraPosition);
    }

}


text:
/*
Given a sorted linked list, delete all nodes that have duplicate numbers,
leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <common.hpp>
class Solution1
{
public:
    ListNode *deleteDuplicates(ListNode *head)
    {
        if (head == NULL)
        {
            return NULL;
        }
        ListNode **runner = &head;
        ListNode *scaner = NULL;
        while (*runner != NULL)
        {
            if ((*runner)->next != NULL &&
                (*runner)->val == (*runner)->next->val)
            {
                scaner = *runner;
                while (scaner != NULL && scaner->val == (*runner)->val)
                {
                    scaner = scaner->next;
                }
                *runner = scaner;
            }
            else
            {
                runner = &((*runner)->next);
            }
        }
        return head;
    }
};

//This problem may erase the head pointer of the list.
//get the ref of head to runner, so it could change the head as well

class Solution2
{
public:
    ListNode *deleteDuplicates(ListNode *head)
    {
        if (head == NULL)
        {
            return NULL;
        }
        ListNode dummy = ListNode(0);
        dummy.next = head;
        ListNode *cur = &dummy;

        while (cur != NULL &&
               cur->next != NULL &&
               cur->next->next != NULL)
        {
            if (cur->next->val == cur->next->next->val)
            {
                int repeat = cur->next->val;
                ListNode *rm = cur->next->next;
                while (rm != NULL && rm->val == repeat)
                {
                    rm = rm->next;
                }
                cur->next = rm;
            }
            else
            {
                cur = cur->next;
            }
        }

        return dummy.next;
    }
};


text:
package zmaster587.advancedRocketry.entity;

import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.client.registry.IRenderFactory;
import zmaster587.advancedRocketry.client.render.RendererRocket;

public class OverEngineeredPieceOfSh_RenderFactory implements IRenderFactory<Entity> {

	@Override
	public Render<? super Entity> createRenderFor(RenderManager manager) {
		return new RendererRocket(manager);
	}

}


text:
<editor>
    <help>https://docs.cloudbees.com/docs/cloudbees-cd/latest/plugins/ec-weblogic#CreateTemplate</help>
    <formElement>
        <type>entry</type>
        WLST script absolute path
        <property>wlst_abs_path</property>
        <required>1</required>
        <documentation>
Absolute path to WLST. i.e: '/path/to/wlst.cmd' or 'wlst.sh'. Setting this path will make applying the equal param in procedures unnecessary.
NOTE: You need to install the agent to the machine that has access to the WLST script at least.
        </documentation>
    </formElement>
    <formElement>
        <type>entry</type>
        Domain Directory
        <property>domain_directory</property>
        <documentation>Name of the domain directory from which you want to create the template.</documentation>
        <required>1</required>
    </formElement>
    <formElement>
        <type>entry</type>
        Template name
        <property>template_name</property>
        <documentation>Name (use .jar extension) and location of the domain template to store the domain configuration information. A domain template is a JAR file that contains domain configuration documents, applications, security data, startup scripts, and other information needed to create a WebLogic domain.</documentation>
        <required>1</required>
    </formElement>
</editor>


text:
module ActiveCSV
  module Aggregator
    def group_by(attribute)
      raise "Invalid Attribute #{attribute}" unless valid_attribute?(attribute)
      self.build.collect{|object| object.send(attribute)}.uniq
    end
  end
end


text:
package com.fragmentmaster.app;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import android.util.Log;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Records {

    private static final String TAG = "Records";

    private ArrayList<IMasterFragment> mFragments = new ArrayList<>();

    public void add(IMasterFragment fragment, IMasterFragment target, int requestCode) {
        fragment.setTargetFragment(
                target == null ? null : target.getFragment(), requestCode);
        mFragments.add(fragment);
    }

    public void remove(IMasterFragment fragment) {
        int index = mFragments.indexOf(fragment);
        mFragments.remove(index);

        IMasterFragment f;
        for (int i = index; i < mFragments.size(); i++) {
            f = mFragments.get(i);
            IMasterFragment target = (IMasterFragment) f.getTargetFragment();
            if (target == fragment) {
                f.setTargetFragment(null, -1);
            }
        }
    }

    public int size() {
        return mFragments.size();
    }

    public int indexOf(IMasterFragment fragment) {
        return mFragments.indexOf(fragment);
    }

    public boolean has(IMasterFragment fragment) {
        return mFragments.contains(fragment);
    }

    public List<IMasterFragment> getFragments() {
        return Collections.unmodifiableList(mFragments);
    }

    public Bundle save(FragmentManager fragmentManager) {
        Bundle fragments = null;
        for (int i = 0; i < mFragments.size(); i++) {
            Fragment f = mFragments.get(i).getFragment();
            if (f != null) {
                if (fragments == null) {
                    fragments = new Bundle();
                }
                String key = "f" + i;
                fragmentManager.putFragment(fragments, key, f);
            }
        }
        return fragments;
    }

    public void restore(FragmentManager fragmentManager, Bundle fragments) {
        mFragments.clear();
        if (fragments != null) {
            Iterable<String> keys = fragments.keySet();
            for (String key : keys) {
                if (key.startsWith("f")) {
                    int index = Integer.parseInt(key.substring(1));
                    IMasterFragment f = (IMasterFragment) fragmentManager
                            .getFragment(fragments, key);
                    if (f != null) {
                        while (mFragments.size() <= index) {
                            mFragments.add(null);
                        }
                        f.setMenuVisibility(false);
                        mFragments.set(index, f);
                    } else {
                        Log.w(TAG, "Bad fragment at key " + key);
                    }
                }
            }
        }
    }
}


text:
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License.  See License.txt in the project root for license information.

using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.OData.Extensions;
using System.Web.OData.Formatter.Serialization;
using Microsoft.OData.Edm;
using Microsoft.TestCommon;
using Moq;

namespace System.Web.OData.Builder.Conventions
{
    public class FunctionLinkGenerationConventionTest
    {
        [Fact]
        public void Apply_SetOperationLinkBuilder_ForFunctionBoundToEntity()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var function = builder.EntityType<Customer>().Function("MyFunction").Returns<int>();
            function.Parameter<string>("param");

            // Act
            Assert.Null(function.GetFunctionLink()); // Guard
            Assert.Null(function.GetFeedFunctionLink()); // Guard

            FunctionLinkGenerationConvention convention = new FunctionLinkGenerationConvention();
            convention.Apply(function, builder);

            // Assert
            var functionLink = function.GetFunctionLink();
            Assert.NotNull(functionLink);
            Assert.IsType<Func<ResourceContext, Uri>>(functionLink);

            Assert.Null(function.GetFeedFunctionLink());
        }

        [Fact]
        public void Convention_GeneratesUri_ForFunctionBoundToEntity()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Customer>("Customers");
            var function = builder.EntityType<Customer>().Function("MyFunction").Returns<int>();
            function.Parameter<string>("param");
            IEdmModel model = builder.GetEdmModel();

            // Act
            HttpConfiguration configuration = new HttpConfiguration();
            configuration.MapODataServiceRoute("odata", "odata", model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:123");
            request.SetConfiguration(configuration);
            request.EnableODataDependencyInjectionSupport("odata");

            IEdmEntitySet customers = model.EntityContainer.FindEntitySet("Customers");
            var edmType = model.SchemaElements.OfType<IEdmEntityType>().First(e => e.Name == "Customer");
            var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = customers, Url = request.GetUrlHelper() };
            var entityContext = new ResourceContext(serializerContext, edmType.AsReference(), new Customer { Id = 109 });

            // Assert
            var edmFunction = model.SchemaElements.OfType<IEdmFunction>().First(f => f.Name == "MyFunction");
            Assert.NotNull(edmFunction);

            OperationLinkBuilder functionLinkBuilder = model.GetOperationLinkBuilder(edmFunction);
            Uri link = functionLinkBuilder.BuildLink(entityContext);

            Assert.Equal("http://localhost:123/odata/Customers(109)/Default.MyFunction(param=@param)",
                link.AbsoluteUri);
        }

        [Fact]
        public void Apply_WorksFor_FunctionBoundToCollectionOfEntity()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var function = builder.EntityType<Customer>().Collection.Function("MyFunction").Returns<int>();
            function.Parameter<string>("param");

            // Act
            Assert.Null(function.GetFunctionLink()); // Guard
            Assert.Null(function.GetFeedFunctionLink()); // Guard

            FunctionLinkGenerationConvention convention = new FunctionLinkGenerationConvention();
            convention.Apply(function, builder);

            // Assert
            var functionLink = function.GetFeedFunctionLink();
            Assert.NotNull(functionLink);
            Assert.IsType<Func<ResourceSetContext, Uri>>(functionLink);

            Assert.Null(function.GetFunctionLink());
        }

        [Fact]
        public void Convention_GeneratesUri_ForFunctionBoundToCollectionOfEntity()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Customer>("Customers");
            var function = builder.EntityType<Customer>().Collection.Function("MyFunction").Returns<int>();
            function.Parameter<string>("param");
            IEdmModel model = builder.GetEdmModel();

            // Act
            HttpConfiguration configuration = new HttpConfiguration();
            configuration.MapODataServiceRoute("odata", "odata", model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:123");
            request.SetConfiguration(configuration);
            request.EnableODataDependencyInjectionSupport("odata");

            IEdmEntitySet customers = model.EntityContainer.FindEntitySet("Customers");
            var entityContext = new ResourceSetContext { EntitySetBase = customers, Request = request, Url = request.GetUrlHelper() };

            // Assert
            var edmFunction = model.SchemaElements.OfType<IEdmFunction>().First(f => f.Name == "MyFunction");
            Assert.NotNull(edmFunction);

            OperationLinkBuilder functionLinkBuilder = model.GetOperationLinkBuilder(edmFunction);
            Uri link = functionLinkBuilder.BuildLink(entityContext);

            Assert.Equal("http://localhost:123/odata/Customers/Default.MyFunction(param=@param)",
                link.AbsoluteUri);
        }

        [Fact]
        public void Apply_Doesnot_Override_UserConfiguration()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var customers = builder.EntitySet<Customer>("Customers");
            var function = customers.EntityType.Function("MyFunction").Returns<int>();
            function.HasFunctionLink(ctx => new Uri("http://localhost/FunctionTestWorks"), followsConventions: false);
            FunctionLinkGenerationConvention convention = new FunctionLinkGenerationConvention();
            convention.Apply(function, builder);

            // Act
            IEdmModel model = builder.GetEdmModel();
            var edmCustomers = model.EntityContainer.FindEntitySet("Customers");
            var edmType = model.SchemaElements.OfType<IEdmEntityType>().First(c => c.Name == "Customer");
            var edmFunction = model.SchemaElements.OfType<IEdmFunction>().Single(f => f.Name == "MyFunction");
            Assert.NotNull(edmFunction);

            HttpConfiguration configuration = new HttpConfiguration();
            configuration.MapODataServiceRoute(model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
            request.SetConfiguration(configuration);

            OperationLinkBuilder fuinctionLinkBuilder = model.GetOperationLinkBuilder(edmFunction);

            var serializerContext = new ODataSerializerContext { Model = model, NavigationSource = edmCustomers, Url = request.GetUrlHelper() };
            var entityContext = new ResourceContext(serializerContext, edmType.AsReference(), new Customer { Id = 109 });

            // Assert
            Uri link = fuinctionLinkBuilder.BuildLink(entityContext);
            Assert.Equal("http://localhost/FunctionTestWorks", link.AbsoluteUri);
        }

        [Fact]
        public void Apply_SetsOperationLinkBuilder_OnlyIfFunctionIsBindable()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var function = builder.Function("MyFunction").Returns<int>();
            ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention();

            // Act
            convention.Apply(function, builder);

            // Assert
            IEdmModel model = builder.GetEdmModel();
            var edmFunction = model.EntityContainer.Elements.OfType<IEdmFunctionImport>().Single();
            Assert.NotNull(edmFunction);

            OperationLinkBuilder linkBuilder = model.GetAnnotationValue<OperationLinkBuilder>(edmFunction);
            Assert.Null(linkBuilder);
        }

        [Fact]
        public void Apply_FollowsConventions()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            FunctionConfiguration function = new FunctionConfiguration(builder, "IgnoreAction");
            Mock<IEdmTypeConfiguration> mockBindingParameterType = new Mock<IEdmTypeConfiguration>();
            mockBindingParameterType.Setup(o => o.Kind).Returns(EdmTypeKind.Entity);
            mockBindingParameterType.Setup(o => o.ClrType).Returns(typeof(int));
            function.SetBindingParameter("IgnoreParameter", mockBindingParameterType.Object);
            FunctionLinkGenerationConvention convention = new FunctionLinkGenerationConvention();

            // Act
            convention.Apply(function, builder);

            // Assert
            Assert.True(function.FollowsConventions);
        }

        public class Customer
        {
            public int Id { get; set; }
        }
    }
}


text:
<?php
  require 'login-engine.php';
  $user = authorizeSession($db);
  $name = $user['name'];
  $email = $user['email'];
  echo "Hello! $name. Your email is $email.";
 ?>

 Edit profile
 Log out
 Change password


text:
function resize(object,fig,varargin)

% determine new position
old=get(fig,'Units');
set(fig,'Units','pixels');
position=get(fig,'Position');

if position(3) < object.BPwidth
    position(3)=object.BPwidth;
end

Lmin=3*object.BPheight;
if position(4) < Lmin
    correction=Lmin-position(4);
    position(4)=Lmin;
    position(2)=position(2)-correction;
end

% correct position and restore units
set(fig,'Position',position,'Units',old);

% deal with button panel
if object.BPheight>0
    % probe button panel
    set(object.ButtonPanel,'Units','pixels');
    position=get(object.ButtonPanel,'Position');
    position(4)=object.BPheight;
    set(object.ButtonPanel,'Position',position,'Units','normalized');
    position=get(object.ButtonPanel,'Position');
    % deal with axes panel
    position(2)=position(4);
    position(4)=1-position(2);
    set(object.AxesPanel,'Position',position);
else
    set(object.AxesPanel,'Position',[0 0 1 1]);
end

end


text:
<?php

namespace Package\Providers;

use Pluma\Support\Providers\ServiceProvider;

class PackageServiceProvider extends ServiceProvider
{
    /**
     * Array of observable models.
     *
     * @var array
     */
    protected $observables = [
        [\Package\Models\Package::class, '\Package\Observers\PackageObserver'],
    ];

    /**
     * Registered middlewares on the
     * Service Providers Level.
     *
     * @var mixed
     */
    protected $middlewares = [
        //
    ];

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->bootObservables();
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
package org.eigenbase.rel.rules;

import org.eigenbase.rel.*;
import org.eigenbase.relopt.*;
import org.eigenbase.rex.*;
import org.eigenbase.sql.fun.*;

/**
 * Rule to replace isNotDistinctFromOperator with logical equivalent conditions
 * in a {@link FilterRel}.
 */
public final class RemoveIsNotDistinctFromRule extends RelOptRule {
  //~ Static fields/initializers ---------------------------------------------

  /** The singleton. */
  public static final RemoveIsNotDistinctFromRule INSTANCE =
      new RemoveIsNotDistinctFromRule();

  //~ Constructors -----------------------------------------------------------

  private RemoveIsNotDistinctFromRule() {
    super(operand(FilterRel.class, any()));
  }

  //~ Methods ----------------------------------------------------------------

  public void onMatch(RelOptRuleCall call) {
    FilterRel oldFilterRel = call.rel(0);
    RexNode oldFilterCond = oldFilterRel.getCondition();

    if (RexUtil.findOperatorCall(
        SqlStdOperatorTable.IS_NOT_DISTINCT_FROM,
        oldFilterCond)
        == null) {
      // no longer contains isNotDistinctFromOperator
      return;
    }

    // Now replace all the "a isNotDistinctFrom b"
    // with the RexNode given by RelOptUtil.isDistinctFrom() method

    RemoveIsNotDistinctFromRexShuttle rewriteShuttle =
        new RemoveIsNotDistinctFromRexShuttle(
            oldFilterRel.getCluster().getRexBuilder());

    RelNode newFilterRel =
        RelOptUtil.createFilter(
            oldFilterRel.getChild(),
            oldFilterCond.accept(rewriteShuttle));

    call.transformTo(newFilterRel);
  }

  //~ Inner Classes ----------------------------------------------------------

  /** Shuttle that removes 'x IS NOT DISTINCT FROM y' and converts it
   * to 'CASE WHEN x IS NULL THEN y IS NULL WHEN y IS NULL THEN x IS
   * NULL ELSE x = y END'. */
  private class RemoveIsNotDistinctFromRexShuttle extends RexShuttle {
    RexBuilder rexBuilder;

    public RemoveIsNotDistinctFromRexShuttle(
        RexBuilder rexBuilder) {
      this.rexBuilder = rexBuilder;
    }

    // override RexShuttle
    public RexNode visitCall(RexCall call) {
      RexNode newCall = super.visitCall(call);

      if (call.getOperator()
          == SqlStdOperatorTable.IS_NOT_DISTINCT_FROM) {
        RexCall tmpCall = (RexCall) newCall;
        newCall =
            RelOptUtil.isDistinctFrom(
                rexBuilder,
                tmpCall.operands.get(0),
                tmpCall.operands.get(1),
                true);
      }
      return newCall;
    }
  }
}

// End RemoveIsNotDistinctFromRule.java