text:
//
//  ReminderViewController.m
//  BPTracker
//
//  Created by Robert Saccone on 1/30/12.
//  Copyright (c) 2017 Robert Saccone. All rights reserved.
//

#import "ReminderViewController.h"

#import <EventKitUI/EKCalendarChooser.h>
#import <EventKitUI/EKEventEditViewController.h>
#import <EventKitUI/EKEventViewController.h>
#import <SLexUtil/NSDate+UtilityExtensions.h>
#import <SLexUtil/PlatformHelper.h>
#import <SLexUtil/UIViewController+HelperExtensions.h>

#import <SLexUtil/PlatformHelper.h>
#import <SLexUtil/ErrorMsgBuilder.h>
#import <SLexUtil/UIAlertView+Blocks.h>
#import "EventViewAndEditController.h"
#import "TakeReadingCalendarEventMetaData.h"
#import "TableViewUserDefaultsHelper.h"
#import "UserSettingKeys.h"

@interface ReminderViewController () <EKEventEditViewDelegate, EventViewAndEditDelegate, EKCalendarChooserDelegate, UIPopoverControllerDelegate>

- (void)addEvent:(id)sender;
- (void)displayAddEventView;
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
- (void)configureBarButtons:(BOOL)editMode;
- (void)registerForEventStoreChangeNotifications;
- (void)unregisterForEventStoreChangeNotifications;
- (void)reloadEventDataAndTableView;
- (void)registerForApplicationStateChangeNotifications;
- (void)unregisterForApplicationStateChangeNotifications;
- (void)actOnEventStoreUpdatesTimerMethod:(NSTimer*)theTimer;
- (void)displayPendingError;
- (void)selectAndScrollIntoView:(NSIndexPath *)selection;
- (BOOL)processCompletedEditAction;

@property(nonatomic, strong) id<TakeReadingRemindersStore> takeReadingRemindersStore;
@property(nonatomic, strong) UIBarButtonItem *addNewItemButton;
@property(nonatomic, strong) NSDateFormatter *shortStyleDateTimeFormatter;
@property(nonatomic, strong) NSDateFormatter *shortStyleDateNoTimeFormatter;
@property(nonatomic, strong) NSTimer *actOnEventStoreUpdatesTimer;
@property(nonatomic, strong) NSError *pendingErrorToBeProcessed;
@property(nonatomic, strong) TableViewUserDefaultsHelper *tableViewUserDefaultsHelper;
@property(nonatomic, strong) UIPopoverController *eventPopoverController;
@property(nonatomic, assign) BOOL inBackgroundState;
@property(nonatomic, assign) BOOL eventStoreChanged;
@property(nonatomic, assign) BOOL editingEvent;
@property(nonatomic, assign) BOOL registeredEventStoreChangeNotifications;
@property(nonatomic, assign) BOOL registeredApplicationStateNotifications;
@property(nonatomic, assign) BOOL restoreSelectionFromDefaults;

@property(nonatomic, weak) id eventStoreChangeObserver;
@property(nonatomic, weak) id appDidEnterBackgroundObserver;
@property(nonatomic, weak) id appDidBecomeActiveObserver;

@end

@implementation ReminderViewController
{
@private
	id<TakeReadingRemindersStore> takeReadingRemindersStore_;
    NSDateFormatter *shortStyleDateTimeFormatter_;
    NSDateFormatter *shortStyleDateNoTimeFormatter_;
    NSTimer *coalesceEventUpdatesTimer_;
    NSError *pendingErrorToBeProcessed_;
    TableViewUserDefaultsHelper *tableViewUserDefaultsHelper_;
    BOOL restoreSelectionFromDefaults_;
}

@synthesize takeReadingRemindersStore = takeReadingRemindersStore_;
@synthesize addNewItemButton = addNewItemButton_;
@synthesize shortStyleDateTimeFormatter = shortStyleDateTimeFormatter_;
@synthesize shortStyleDateNoTimeFormatter = shortStyleDateNoTimeFormatter_;
@synthesize actOnEventStoreUpdatesTimer = coalesceEventUpdatesTimer_;
@synthesize pendingErrorToBeProcessed = pendingErrorToBeProcessed_;
@synthesize tableViewUserDefaultsHelper = tableViewUserDefaultsHelper_;
@synthesize inBackgroundState;
@synthesize eventStoreChanged;
@synthesize editingEvent;
@synthesize registeredEventStoreChangeNotifications;
@synthesize registeredApplicationStateNotifications;
@synthesize restoreSelectionFromDefaults = restoreSelectionFromDefaults_;

// Designated initializer.
-(id)initWithTakeReadingRemindersStore:(id<TakeReadingRemindersStore>)takeReadingRemindersStore;
{
    if (takeReadingRemindersStore == nil)
    {
        NSLog(@"BPReadingListViewController: nil id<takeReadingRemindersStore> passed!");
        NSAssert(takeReadingRemindersStore != nil, @"managedObjectContext is nil!");

        return nil;
    }

    NSString *nibName = @"ReminderViewController";

    self = [super initWithNibName:nibName bundle:nil];

    if (self != nil)
    {
        takeReadingRemindersStore_ = takeReadingRemindersStore;

        NSArray *keyNames = [NSArray arrayWithObjects:reminderTableViewSectionSelectedKey, reminderTableViewRowSelectedKey, reminderTableViewEditSelectedKey, reminderTableViewSortAscendingKey, nil];

        tableViewUserDefaultsHelper_ = [[TableViewUserDefaultsHelper alloc] initWithKeyNames:keyNames];
        restoreSelectionFromDefaults_ = YES;

        UITabBarItem *tbi = [self tabBarItem];

        [tbi setTitle:NSLocalizedString(@"REMINDER_CONTROLLER_TITLE", nil)];
        UIImage *image = [UIImage imageNamed:@"calendar.png"];
        [tbi setImage:image];

        [self configureBarButtons:NO];
    }

    return self;
}

- (id)init
{
    return [self initWithTakeReadingRemindersStore:nil];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    return [self init];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    NSLog(@"ReminderViewController: viewDidLoad.");

    [super viewDidLoad];
//    self.edgesForExtendedLayout = UIRectEdgeNone;

    self.tableView.rowHeight = 60.0;

    self.title = NSLocalizedString(@"REMINDER_CONTROLLER_TITLE", nil);

    [self configureBarButtons:NO];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];

    self.shortStyleDateTimeFormatter = dateFormatter;

    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];

    self.shortStyleDateNoTimeFormatter = dateFormatter;

    self.editingEvent = NO;
    self.eventStoreChanged = NO;
    self.inBackgroundState = NO;

    [self registerForApplicationStateChangeNotifications];

    [self.tableView reloadData];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)selectAndScrollIntoView:(NSIndexPath *)selection;
{
    NSAssert(selection != nil, @"selection == nil");

    UITableView *tv = self.tableView;
    [tv selectRowAtIndexPath:selection animated:NO scrollPosition:UITableViewScrollPositionNone];
    [tv scrollToRowAtIndexPath:selection atScrollPosition:UITableViewScrollPositionNone animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@"ReminderViewController: viewWillAppear.");

    [super viewWillAppear:animated];

    if (![self processCompletedEditAction] && self.restoreSelectionFromDefaults)
    {
        self.restoreSelectionFromDefaults = NO;

        NSIndexPath *selection = [self.tableViewUserDefaultsHelper getSavedSelection];

        if (selection != nil)
        {
            NSInteger row = selection.row;
            NSUInteger count = self.takeReadingRemindersStore.count;

            if (row < count)
            {
                EKEvent *event = [self.takeReadingRemindersStore reminderEventAtIndex:row];

                NSString *savedId = [[NSUserDefaults standardUserDefaults] objectForKey:reminderTableViewSelectionIdKey];

                if (savedId && ([event.eventIdentifier compare:savedId] == NSOrderedSame))
                {
                    [self selectAndScrollIntoView:selection];

                    if ([self.tableViewUserDefaultsHelper getSavedEditingFlag])
                    {
                        // Don't resume editing if on iPad because the view may not be attached
                        // to a window which will result in an error when the popover that is
                        // used on the iPad is displayed.
                        if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad)
                        {
                            [self tableView:self.tableView didSelectRowAtIndexPath:selection];
                        }
                    }
                }
            }
        }
    }

    if (!self.registeredEventStoreChangeNotifications)
    {
        [self registerForEventStoreChangeNotifications];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    NSLog(@"ReminderViewController: viewDidDAppear.");
}

- (void)viewWillDisappear:(BOOL)animated
{
    NSLog(@"ReminderViewController: viewWillDisappear.");
}

- (void)viewDidDisappear:(BOOL)animated
{
    NSLog(@"ReminderViewController: viewDidDisappear.");
}

#pragma mark - Prcoess Completed Edit Action

- (BOOL)processCompletedEditAction
{
    if (self.editingEvent)
    {
        if (!self.pendingErrorToBeProcessed)
        {
            self.editingEvent = NO;

            [self.tableViewUserDefaultsHelper saveEditingFlag:NO];
        }
        else
        {
            [self displayPendingError];
        }

        return YES;
    }

    return NO;
}

#pragma mark - Error Display and Handling.

- (void)displayPendingError
{
    NSString *title = NSLocalizedString(@"READING_REMINDER_FAILURE_TITLE", nil);
    NSString *msg = [ErrorMsgBuilder build:nil error:self.pendingErrorToBeProcessed];
    NSString *cancel = NSLocalizedString(@"OK_BUTTON_LABEL", @"OK button label");

    self.pendingErrorToBeProcessed = nil;

    UIAlertView * alertView = [[UIAlertView alloc]
                               initWithTitle:title
                               message:msg
                               clickedButtonBlock:^(UIAlertView *alertView, NSInteger buttonIndex)
                               {
                                   abort();
                               }
                               cancelButtonTitle:cancel
                               otherButtonTitles:nil];

    [alertView show];
}

#pragma mark - Refresh View

- (void)reloadEventDataAndTableView;
{
    [self.takeReadingRemindersStore forceDataReload];
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark Add a new event

// If event is nil, a new event is created and added to the specified event store. New events are
// added to the default calendar. An exception is raised if set to an event that is not in the
// specified event store.
- (void)addEvent:(id)sender
{
#if 0
    EKCalendarChooser *calendarChooser = [[EKCalendarChooser alloc]
                                          initWithSelectionStyle:EKCalendarChooserSelectionStyleSingle
                                          displayStyle:EKCalendarChooserDisplayWritableCalendarsOnly
                                          eventStore:self.takeReadingRemindersStore.eventStore];

    calendarChooser.delegate = self;

    calendarChooser.showsDoneButton = YES;
    calendarChooser.showsCancelButton = YES;

    UINavigationController *cntrol = [[UINavigationController alloc] initWithRootViewController:calendarChooser];

    [self presentViewController:cntrol animated:YES completion:nil];

    [calendarChooser release];
    [cntrol release];
#endif

    [self displayAddEventView];
}

- (void)displayAddEventView
{
    const NSTimeInterval appointmentInterval = 15 * 60;

    NSDate *startDate = [NSDate roundUpDate:[NSDate date] toNearestIntervalInMinutes:30];
    NSDate *endDate = [startDate dateByAddingTimeInterval:appointmentInterval];

    EKEvent *newEvent = [EKEvent eventWithEventStore:self.takeReadingRemindersStore.eventStore];

    newEvent.startDate = startDate;
    newEvent.endDate = endDate;

    // When add button is pushed, create an EKEventEditViewController to display the event.
    EKEventEditViewController *addController = [[EKEventEditViewController alloc] initWithNibName:nil bundle:nil];

    // set the addController's event store to the current event store.
    addController.eventStore = self.takeReadingRemindersStore.eventStore;
    addController.editViewDelegate = self;
    addController.event = newEvent;

    self.editingEvent = YES;

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        self.eventPopoverController = [[UIPopoverController alloc] initWithContentViewController:addController];

        [self.eventPopoverController presentPopoverFromBarButtonItem:self.addNewItemButton permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

        self.eventPopoverController.delegate = self;
    }
    else
    {
        [self presentViewController:addController animated:YES completion:NULL];
    }

}

#pragma mark -EKEventEditViewDelegate

// Overriding EKEventEditViewDelegate method to update event store according to user actions
// when a new event has been created.
- (void)eventEditViewController:(EKEventEditViewController *)controller
          didCompleteWithAction:(EKEventEditViewAction)action
{
    BOOL opSucceeded = YES;
    NSError * __autoreleasing error = nil;
    EKEvent *thisEvent = controller.event;

    switch (action)
    {
        case EKEventEditViewActionCanceled:
            // Edit action canceled, do nothing.
            break;

        case EKEventEditViewActionSaved:
            // When user hit "Done" button, save the newly created event to the event store,
            // and reload table view.
            // If the new event is being added to the default calendar, then update its
            // eventsList.
            opSucceeded = [self.takeReadingRemindersStore addReminderEvent:thisEvent eventStore:nil error:&error];
            break;

        case EKEventEditViewActionDeleted:
            // When deleting an event, remove the event from the event store,
            // and reload table view.
            // If deleting an event from the currenly default calendar, then update its
            // eventsList.
            opSucceeded = [self.takeReadingRemindersStore deleteReminderEvent:thisEvent eventStore:nil error:&error];
            break;

        default:
            break;
    }

    if (!opSucceeded)
    {
        self.pendingErrorToBeProcessed = error;
    }

    if (self.eventPopoverController)
    {
        [self.eventPopoverController dismissPopoverAnimated:YES];
        self.eventPopoverController = nil;
        [self processCompletedEditAction];
    }
    else
    {
        // Dismiss the modal view controller
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - Popover Delegate methods

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    self.eventPopoverController = nil;
    [self processCompletedEditAction];
}

#pragma mark - EventViewAndEditDelegate

// Method called when EventViewAndEditController informs that the user has finished editing an event
// that already exists in the store.  Changes in event data will be picked up through event
// change notifications that are registered for via the notification center.
-(void)eventViewAndEditController:(EventViewAndEditController *)controller
            didCompleteWithAction:(EventViewAndEditAction)action
{
    BOOL opSucceeded = YES;
    BOOL popViewController = NO;
    NSError * __autoreleasing error = nil;
    EKEvent *thisEvent = controller.event;

    NSString *origEventId = ((EventViewAndEditController *)controller).origEventId;

    switch (action)
    {
        case EventViewAndEditActionDone:
            // User pressed the "Done" button.
            opSucceeded = [self.takeReadingRemindersStore saveReminderEvent:thisEvent eventStore:nil originalEventId:origEventId error:&error];
            popViewController = YES;
            break;

        case EventViewAndEditActionSaved:
            // Don't pop the view controller on a save because the user
            // is still viewing the event.
            opSucceeded = [self.takeReadingRemindersStore saveReminderEvent:thisEvent eventStore:nil originalEventId:origEventId error:&error];
            if (self.eventPopoverController != nil)
            {
                popViewController = YES;
            }
            break;

        case EventViewAndEditActionResponded:
            // The user responded to a pending event invitation and saved it.
            opSucceeded = [self.takeReadingRemindersStore saveReminderEvent:thisEvent eventStore:nil originalEventId:origEventId error:&error];
            break;

        case EventViewAndEditActionDeleted:
            // The event was deletede when deleting an event, remove the event from the event store.
            opSucceeded = [self.takeReadingRemindersStore deleteReminderEvent:thisEvent eventStore:nil error:&error];
            popViewController = YES;
            break;

        case EventViewAndEditActionCanceled:
            // Editing was canceled.  This event will only come in on the iPad
            // because the view is presented in a popover.
            popViewController = YES;
            break;

        default:
            break;
    }

    popViewController = (!opSucceeded) ? YES : popViewController;

    if (!opSucceeded)
    {
        self.pendingErrorToBeProcessed = error;
    }

    if (popViewController)
    {
        if (self.eventPopoverController)
        {
            [self.eventPopoverController dismissPopoverAnimated:YES];
            self.eventPopoverController = nil;
            [self processCompletedEditAction];
        }
        else
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma mark - EKCalendarChooserDelegate

// These are called when the corresponding button is pressed to dismiss the
// controller. It is up to the recipient to dismiss the chooser.
- (void)calendarChooserDidFinish:(EKCalendarChooser *)calendarChooser
{
    if (self.eventPopoverController)
    {
        [self.eventPopoverController dismissPopoverAnimated:YES];
        self.eventPopoverController = nil;
    }
    else
    {
        // Dismiss the modal view controller
        [self dismissViewControllerAnimated:YES completion:^(void) { [self displayAddEventView]; }];
    }
}

- (void)calendarChooserDidCancel:(EKCalendarChooser *)calendarChooser
{
    if (self.eventPopoverController)
    {
        [self.eventPopoverController dismissPopoverAnimated:YES];
        self.eventPopoverController = nil;
    }
    else
    {
        // Dismiss the modal view controller
        [self dismissViewControllerAnimated:YES completion:nil];
    }

}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return (NSInteger)1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section != 0)
    {
        return 0;
    }
    return self.takeReadingRemindersStore.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return nil;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"ReminderCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}

static NSString *getRepeatIntervalDesc(NSInteger interval,
                                       EKRecurrenceFrequency freq)
{
    NSString *result;

    if (interval == 1)
    {
        NSString *resId = nil;

        switch (freq)
        {
            case EKRecurrenceFrequencyDaily:
                resId = @"DAY";
                break;

            case EKRecurrenceFrequencyWeekly:
                resId = @"WEEK";
                break;

            case EKRecurrenceFrequencyMonthly:
                resId = @"MONTH";
                break;

            case EKRecurrenceFrequencyYearly:
                resId = @"YEAR";
                break;

            default:
                resId = @"DAY";
                NSLog(@"Unexpected event repeat frequency: <%ld>, assuming <%@>", (long)freq, resId);
                break;
        }

        result = [NSString stringWithFormat:NSLocalizedString(@"MULTI-INTERVAL_SINGLE-FREQUENCY_RECURRENCE", nil), NSLocalizedString(resId, nil)];
    }
    else
    {
        NSString *resId = nil;

        switch (freq)
        {
            case EKRecurrenceFrequencyDaily:
                resId = @"DAYS";
                break;

            case EKRecurrenceFrequencyWeekly:
                resId = @"WEEKS";
                break;

            case EKRecurrenceFrequencyMonthly:
                resId = @"MONTHS";
                break;

            case EKRecurrenceFrequencyYearly:
                resId = @"YEARS";
                break;

            default:
                resId = @"DAYS";
                NSLog(@"Unexpected event repeat frequency: <%ld>, assuming <%@>", (long)freq, resId);
                break;
        }

        result = [NSString stringWithFormat:NSLocalizedString(@"MULTI-INTERVAL_MULTI-FREQUENCY_RECURRENCE", nil), interval, NSLocalizedString(resId, nil)];
    }

    return result;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSAssert(cell != nil, @"cell == nil");

    // Configure the cell...
    NSInteger row = indexPath.row;
    NSUInteger count = self.takeReadingRemindersStore.count;

    if (row >= count)
        return;

    EKEvent *event = [self.takeReadingRemindersStore reminderEventAtIndex:row];

    cell.selectionStyle = UITableViewCellSelectionStyleBlue;

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    /* The title text of the cell will be the title of the event */
    cell.textLabel.text = event.title;
    cell.textLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:12.0f];
    cell.detailTextLabel.numberOfLines = 2;

    BOOL alldayEvent = event.allDay;

    NSString *detailText = nil;

    if (!event.hasRecurrenceRules)
    {
        if (alldayEvent)
        {
            NSString *startDateString = [self.shortStyleDateNoTimeFormatter stringFromDate:event.startDate];
            detailText = [NSString stringWithFormat:NSLocalizedString(@"ALL_DAY_REMINDER_EVENT", nil), startDateString];
        }
        else
        {
            NSString *startDateString = [self.shortStyleDateTimeFormatter stringFromDate:event.startDate];
            NSDateComponents *deltaDateComp = [NSDate deltaFromDate:event.startDate toDate:event.endDate];
            NSString *apptDuration = [NSDate durationFromDateComponents:deltaDateComp];

            detailText = [NSString stringWithFormat:NSLocalizedString(@"REMINDER_EVENT_DATE_TIME", nil), startDateString, apptDuration];
         }
    }
    else
    {
        NSString *detailFormatString = nil;
        NSDateFormatter *dateFormatter = nil;

        EKRecurrenceRule *recurRule = (EKRecurrenceRule *)[event.recurrenceRules objectAtIndex:0];

        NSInteger interval = recurRule.interval;
        EKRecurrenceFrequency freq = recurRule.frequency;
        EKRecurrenceEnd *recurEnd = recurRule.recurrenceEnd;

        NSString *occurencesDesc = getRepeatIntervalDesc(interval, freq);
        NSString *terminatingDesc = nil;

        dateFormatter = alldayEvent
                            ? self.shortStyleDateNoTimeFormatter
                            : self.shortStyleDateTimeFormatter;

        if (recurEnd != nil)
        {
            if (recurEnd.endDate != nil)
            {
                terminatingDesc = [dateFormatter stringFromDate:recurEnd.endDate];
                detailFormatString = alldayEvent
                                        ? @"ALL_DAY_RECUR_EVENT_UNTIL_END_DATE"
                                        : @"RECUR_EVENT_UNTIL_END_DATE";
            }
            else
            {
                NSInteger ocurrences = interval * recurEnd.occurrenceCount;

                terminatingDesc = getRepeatIntervalDesc(ocurrences, freq);

                detailFormatString = alldayEvent
                                        ? @"ALL_DAY_RECUR_EVENT_UNTIL_OCCURENCES_REACHED"
                                        : @"RECUR_EVENT_UNTIL_OCCURENCES_REACHED";
            }
        }
        else
        {
            detailFormatString = alldayEvent
                                    ? @"ALL_DAY_RECUR_EVENT"
                                    : @"RECUR_EVENT";
        }

        NSString *startDateString = [dateFormatter stringFromDate:event.startDate];
        NSString *apptDuration = nil;

        if (!alldayEvent)
        {
            NSDateComponents *deltaDateComp
                    = [NSDate deltaFromDate:event.startDate toDate:event.endDate];
            apptDuration = [NSDate durationFromDateComponents:deltaDateComp];
        }

        if (!terminatingDesc)
        {
            if (apptDuration)
            {
                detailText
                    = [NSString stringWithFormat:NSLocalizedString(detailFormatString, nil),
                                        startDateString, apptDuration, occurencesDesc];
            }
            else
            {
                detailText
                = [NSString stringWithFormat:NSLocalizedString(detailFormatString, nil),
                   startDateString, occurencesDesc];
            }
        }
        else
        {
            if (apptDuration)
            {
                detailText
                    = [NSString stringWithFormat:NSLocalizedString(detailFormatString, nil),
                       startDateString, apptDuration, occurencesDesc, terminatingDesc];

            }
            else
            {
                detailText
                    = [NSString stringWithFormat:NSLocalizedString(detailFormatString, nil),
                       startDateString, occurencesDesc, terminatingDesc];
            }
        }
    }

    cell.detailTextLabel.text = detailText;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSError * __autoreleasing error = nil;

        // Delete the row from the data source passing the store since it is our responsiblity to delete
        // the actual event from the calendar.
        if ([self.takeReadingRemindersStore deleteReminderEventAtIndex:indexPath.row eventStore:self.takeReadingRemindersStore.eventStore error:&error])
        {
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
        }
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - TableView Methods

- (void)configureBarButtons:(UINavigationItem *)navItem editMode:(BOOL)editMode
{
    if (navItem == nil)
    {
        return;
    }

    if (navItem.leftBarButtonItem == nil)
    {
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        navItem.leftBarButtonItem = self.editButtonItem;
    }

    if (editMode)
    {
        navItem.rightBarButtonItem = nil;
    }
    else
    {
        UIBarButtonItem *addNewItem = self.addNewItemButton;

        if (addNewItem == nil)
        {
            // Add a '+' bar button for adding a new bp reading.
            addNewItem = [[UIBarButtonItem alloc]
                          initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                          target:self
                          action:@selector(addEvent:)];

            self.addNewItemButton = addNewItem;
        }

        navItem.rightBarButtonItem = addNewItem;
    }
}

- (void)configureBarButtons:(BOOL)editMode
{
    UINavigationItem *navItem = self.navigationItem;

    [self configureBarButtons:navItem editMode:editMode];
}

- (void)setEditing:(BOOL)flag animated:(BOOL)animated
{
	// Always call super implementation of this method,
	// it needs to do work.
	[super setEditing:flag animated:animated];

	NSLog(@"setEditing: flag = %d, animated = %d", flag, animated);

    self.editingEvent = flag;

    [self configureBarButtons:flag];

    /*
    if (flag)
    {
        if (self.registeredEventStoreChangeNotifications)
        {
            [self unregisterForEventStoreChangeNotifications];
        }
    }
    else
    {
        [self reloadEventDataAndTableView];
        [self registerForEventStoreChangeNotifications];
    }
    */

#if 0
	// You need to insert / remove a new row in to the table view.
	if (flag)
	{
		// If entering edit mode, add another row to our table view.
		NSIndexPath *indexPath =
		[NSIndexPath indexPathForRow:[possessions count] inSection:0];

		NSArray *paths = [NSArray arrayWithObject:indexPath];

		[[self tableView] insertRowsAtIndexPaths:paths
								withRowAnimation:UITableViewRowAnimationLeft];
	}
	else
	{
		// If leaving edit mode, remove last row from table view.
		NSIndexPath *indexPath =
		[NSIndexPath indexPathForRow:[possessions count] inSection:0];

		NSArray *paths = [NSArray arrayWithObject:indexPath];

		[[self tableView] deleteRowsAtIndexPaths:paths
								withRowAnimation:UITableViewRowAnimationFade];

	}
#endif
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = (NSUInteger)indexPath.row;

    if (row < self.takeReadingRemindersStore.count)
    {
        [self.tableViewUserDefaultsHelper saveSelectedIndex:indexPath withEditFlag:YES];

        EKEvent *selectedEvent = [self.takeReadingRemindersStore reminderEventAtIndex:row];

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

        [userDefaults setObject:selectedEvent.eventIdentifier
                         forKey:reminderTableViewSelectionIdKey];

        [userDefaults synchronize];

        // When a row in the tableview is selected, create an EventViewControllerCustomDelegate to display the event.
        EventViewAndEditController *eventViewAndEditController = [[EventViewAndEditController alloc] initWithNibName:nil bundle:nil];

        // set the addController's event store to the current event store.
        eventViewAndEditController.event = selectedEvent;
        eventViewAndEditController.origEventId = eventViewAndEditController.event.eventIdentifier;
        eventViewAndEditController.allowsEditing = YES;
        eventViewAndEditController.eventViewAndEditDelegate = self;
        eventViewAndEditController.eventStore = self.takeReadingRemindersStore.eventStore;

        self.editingEvent = YES;

        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            CGRect rowRect = [tableView rectForRowAtIndexPath:indexPath];

            self.eventPopoverController = [[UIPopoverController alloc] initWithContentViewController:eventViewAndEditController];
            [self.eventPopoverController presentPopoverFromRect:rowRect inView:tableView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
            self.eventPopoverController.delegate = self;
        }
        else
        {
            //  Push detailViewController onto the navigation controller stack
            //  If the underlying event gets deleted, detailViewController will remove itself from
            //  the stack and clear its event property.
            [self.navigationController pushViewController:eventViewAndEditController animated:YES];
        }
    }
}

#pragma mark - Event Store Change Notification

- (void)registerForEventStoreChangeNotifications
{
    const NSTimeInterval TimerIntervalInSecs = 1.0f / 3.0f;

    if (!self.registeredEventStoreChangeNotifications)
    {
        self.actOnEventStoreUpdatesTimer = [NSTimer timerWithTimeInterval:TimerIntervalInSecs
                                                                   target:self selector:@selector(actOnEventStoreUpdatesTimerMethod:)
                                                                 userInfo:nil
                                                                  repeats:YES];

        [[NSRunLoop currentRunLoop] addTimer:self.actOnEventStoreUpdatesTimer forMode:NSDefaultRunLoopMode];

        ReminderViewController * __weak weakSelf = self;

        self.eventStoreChangeObserver =
            [[NSNotificationCenter defaultCenter] addObserverForName:EKEventStoreChangedNotification
                                                           object:self.takeReadingRemindersStore.eventStore
                                                            queue:[NSOperationQueue mainQueue]
                                                       usingBlock:^(NSNotification *notification)
                                        {
                                            NSLog(@"ReminderViewController: Did receive EKEventStoreChangedNotification");

                                            weakSelf.eventStoreChanged = YES;
                                        }];

        self.registeredEventStoreChangeNotifications = YES;

        NSLog(@"ReminderViewController -> Registered for Event Store Change Notifications.");
    }
}

- (void)unregisterForEventStoreChangeNotifications
{
    if (self.registeredEventStoreChangeNotifications)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self.eventStoreChangeObserver
                                                        name:EKEventStoreChangedNotification
                                                      object:nil];

        [self.actOnEventStoreUpdatesTimer invalidate];
        self.actOnEventStoreUpdatesTimer = nil;
        self.registeredEventStoreChangeNotifications = NO;

        NSLog(@"ReminderViewController -> Unregistered for Event Store Change Notifications.");
    }
}

- (void)actOnEventStoreUpdatesTimerMethod:(NSTimer*)theTimer
{
    if (!self.editingEvent && [self isVisible])
    {
//        NSLog(@"Timer fired ... Not editing reminders and view is visible.");

        // This timer is guaranteed to fire on the main thread.
        // No need to synchronize since all notifications are being
        // delivered on the main thread as well.
        if (self.eventStoreChanged)
        {
            NSLog(@"Timer fired ... Reloading reminders.");
            self.eventStoreChanged = NO;
            [self reloadEventDataAndTableView];
        }
    }
}

#pragma mark - Application State Change Notifications.

- (void)registerForApplicationStateChangeNotifications
{
    if (!self.registeredApplicationStateNotifications)
    {
        NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];

        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

        ReminderViewController * __weak weakSelf = self;

        self.appDidEnterBackgroundObserver =
            [center addObserverForName:UIApplicationDidEnterBackgroundNotification
                                object:nil
                                 queue:mainQueue
                            usingBlock:^(NSNotification *notification)
             {
                 NSLog(@"ReminderViewController: Did receive UIApplicationDidEnterBackgroundNotification");
                 weakSelf.inBackgroundState = YES;
             }];

        self.appDidBecomeActiveObserver =
             [center addObserverForName:UIApplicationDidBecomeActiveNotification
                                 object:nil
                                  queue:mainQueue
                             usingBlock:^(NSNotification *notification)
            {
                NSLog(@"ReminderViewController: Did receive UIApplicationDidBecomeActiveNotification");

                weakSelf.inBackgroundState = NO;

                if (!weakSelf.editingEvent)
                {
                    [weakSelf registerForEventStoreChangeNotifications];
                }
            }];

        self.registeredApplicationStateNotifications = YES;

        NSLog(@"ReminderViewController -> Registered for application state changes.");
    }
}

- (void)unregisterForApplicationStateChangeNotifications
{
    if (self.registeredApplicationStateNotifications)
    {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

        [center removeObserver:self.appDidBecomeActiveObserver name:UIApplicationDidBecomeActiveNotification object:nil];
        [center removeObserver:self.appDidEnterBackgroundObserver name:UIApplicationDidEnterBackgroundNotification object:nil];
        self.registeredApplicationStateNotifications = NO;

        NSLog(@"ReminderViewController -> Unregistered for application state changes.");
    }
}

@end


text: export { Store as default } from './-private';

redpajama_set_name: RedPajamaGithub


text:
Function Index
==============

[PostgreSQL PostGIS Geometry/Geography/Box Types](http://postgis.net/docs/reference.html#PostGIS_Types)
----------

* [Geometry](http://postgis.net/docs/Geometry.html)

[Geometry Constructors](http://postgis.net/docs/reference.html#Geometry_Constructors)
----------

* [ST_Box2dFromGeoHash](http://postgis.net/docs/ST_Box2dFromGeoHash.html)
* [ST_GeogFromText](http://postgis.net/docs/ST_GeogFromText.html)
* [ST_GeographyFromText](http://postgis.net/docs/ST_GeographyFromText.html)
* [ST_GeogFromWKB](http://postgis.net/docs/ST_GeogFromWKB.html)
* [ST_GeomCollFromText](http://postgis.net/docs/ST_GeomCollFromText.html)
* [ST_GeomFromEWKB](http://postgis.net/docs/ST_GeomFromEWKB.html)
* [ST_GeomFromEWKT](http://postgis.net/docs/ST_GeomFromEWKT.html)
* [ST_GeomFromGeoHash](http://postgis.net/docs/ST_GeomFromGeoHash.html)
* [ST_GeomFromGML](http://postgis.net/docs/ST_GeomFromGML.html)
* [ST_GeomFromGeoJSON](http://postgis.net/docs/ST_GeomFromGeoJSON.html)
* [ST_GeomFromKML](http://postgis.net/docs/ST_GeomFromKML.html)
* [ST_GeomFromText](http://postgis.net/docs/ST_GeomFromText.html)
* [ST_GeometryFromText](http://postgis.net/docs/ST_GeometryFromText.html)
* [ST_GeomFromWKB](http://postgis.net/docs/ST_GeomFromWKB.html)
* [ST_LineFromMultiPoint](http://postgis.net/docs/ST_LineFromMultiPoint.html)
* [ST_LineFromText](http://postgis.net/docs/ST_LineFromText.html)
* [ST_LineFromWKB](http://postgis.net/docs/ST_LineFromWKB.html)
* [ST_LinestringFromWKB](http://postgis.net/docs/ST_LinestringFromWKB.html)
* [ST_MakeBox2D](http://postgis.net/docs/ST_MakeBox2D.html)
* [ST_3DMakeBox](http://postgis.net/docs/ST_3DMakeBox.html)
* [ST_MakeBox3D](http://postgis.net/docs/ST_MakeBox3D.html)
* [ST_MakeLine](http://postgis.net/docs/ST_MakeLine.html)
* [ST_MakeEnvelope](http://postgis.net/docs/ST_MakeEnvelope.html)
* [ST_MakePolygon](http://postgis.net/docs/ST_MakePolygon.html)
* [ST_MakePoint](http://postgis.net/docs/ST_MakePoint.html)
* [ST_MakePointM](http://postgis.net/docs/ST_MakePointM.html)
* [ST_MLineFromText](http://postgis.net/docs/ST_MLineFromText.html)
* [ST_MPointFromText](http://postgis.net/docs/ST_MPointFromText.html)
* [ST_MPolyFromText](http://postgis.net/docs/ST_MPolyFromText.html)
* [ST_Point](http://postgis.net/docs/ST_Point.html)
* [ST_PointFromGeoHash](http://postgis.net/docs/ST_PointFromGeoHash.html)
* [ST_PointFromText](http://postgis.net/docs/ST_PointFromText.html)
* [ST_PointFromWKB](http://postgis.net/docs/ST_PointFromWKB.html)
* [ST_Polygon](http://postgis.net/docs/ST_Polygon.html)
* [ST_PolygonFromText](http://postgis.net/docs/ST_PolygonFromText.html)

[Geometry Accessors](http://postgis.net/docs/reference.html#Geometry_Accessors)
----------

* [GeometryType](http://postgis.net/docs/GeometryType.html)
* [ST_Boundary](http://postgis.net/docs/ST_Boundary.html)
* [ST_CoordDim](http://postgis.net/docs/ST_CoordDim.html)
* [ST_Dimension](http://postgis.net/docs/ST_Dimension.html)
* [ST_EndPoint](http://postgis.net/docs/ST_EndPoint.html)
* [ST_Envelope](http://postgis.net/docs/ST_Envelope.html)
* [ST_ExteriorRing](http://postgis.net/docs/ST_ExteriorRing.html)
* [ST_GeometryN](http://postgis.net/docs/ST_GeometryN.html)
* [ST_GeometryType](http://postgis.net/docs/ST_GeometryType.html)
* [ST_InteriorRingN](http://postgis.net/docs/ST_InteriorRingN.html)
* [ST_IsClosed](http://postgis.net/docs/ST_IsClosed.html)
* [ST_IsCollection](http://postgis.net/docs/ST_IsCollection.html)
* [ST_IsEmpty](http://postgis.net/docs/ST_IsEmpty.html)
* [ST_IsRing](http://postgis.net/docs/ST_IsRing.html)
* [ST_IsSimple](http://postgis.net/docs/ST_IsSimple.html)
* [ST_IsValid](http://postgis.net/docs/ST_IsValid.html)
* [ST_IsValidReason](http://postgis.net/docs/ST_IsValidReason.html)
* [ST_IsValidDetail](http://postgis.net/docs/ST_IsValidDetail.html)
* [ST_M](http://postgis.net/docs/ST_M.html)
* [ST_NDims](http://postgis.net/docs/ST_NDims.html)
* [ST_NPoints](http://postgis.net/docs/ST_NPoints.html)
* [ST_NRings](http://postgis.net/docs/ST_NRings.html)
* [ST_NumGeometries](http://postgis.net/docs/ST_NumGeometries.html)
* [ST_NumInteriorRings](http://postgis.net/docs/ST_NumInteriorRings.html)
* [ST_NumInteriorRing](http://postgis.net/docs/ST_NumInteriorRing.html)
* [ST_NumPatches](http://postgis.net/docs/ST_NumPatches.html)
* [ST_NumPoints](http://postgis.net/docs/ST_NumPoints.html)
* [ST_PatchN](http://postgis.net/docs/ST_PatchN.html)
* [ST_PointN](http://postgis.net/docs/ST_PointN.html)
* [ST_SRID](http://postgis.net/docs/ST_SRID.html)
* [ST_StartPoint](http://postgis.net/docs/ST_StartPoint.html)
* [ST_Summary](http://postgis.net/docs/ST_Summary.html)
* [ST_X](http://postgis.net/docs/ST_X.html)
* [ST_XMax](http://postgis.net/docs/ST_XMax.html)
* [ST_XMin](http://postgis.net/docs/ST_XMin.html)
* [ST_Y](http://postgis.net/docs/ST_Y.html)
* [ST_YMax](http://postgis.net/docs/ST_YMax.html)
* [ST_YMin](http://postgis.net/docs/ST_YMin.html)
* [ST_Z](http://postgis.net/docs/ST_Z.html)
* [ST_ZMax](http://postgis.net/docs/ST_ZMax.html)
* [ST_Zmflag](http://postgis.net/docs/ST_Zmflag.html)
* [ST_ZMin](http://postgis.net/docs/ST_ZMin.html)

[Geometry Editors](http://postgis.net/docs/reference.html#Geometry_Editors)
----------

* [ST_AddPoint](http://postgis.net/docs/ST_AddPoint.html)
* [ST_Multi](http://postgis.net/docs/ST_Multi.html)
* [ST_Scale](http://postgis.net/docs/ST_Scale.html)
* [ST_SetSRID](http://postgis.net/docs/ST_SetSRID.html)
* [ST_SnapToGrid](http://postgis.net/docs/ST_SnapToGrid.html)
* [ST_Transform](http://postgis.net/docs/ST_Transform.html)
* [ST_Translate](http://postgis.net/docs/ST_Translate.html)
* [ST_TransScale](http://postgis.net/docs/ST_TransScale.html)

[Geometry Outputs](http://postgis.net/docs/reference.html#Geometry_Outputs)
----------

* [ST_AsBinary](http://postgis.net/docs/ST_AsBinary.html)
* [ST_AsEWKB](http://postgis.net/docs/ST_AsEWKB.html)
* [ST_AsEWKT](http://postgis.net/docs/ST_AsEWKT.html)
* [ST_AsGeoJSON](http://postgis.net/docs/ST_AsGeoJSON.html)
* [ST_AsGML](http://postgis.net/docs/ST_AsGML.html)
* [ST_AsHEXEWKB](http://postgis.net/docs/ST_AsHEXEWKB.html)
* [ST_AsKML](http://postgis.net/docs/ST_AsKML.html)
* [ST_AsSVG](http://postgis.net/docs/ST_AsSVG.html)
* [ST_GeoHash](http://postgis.net/docs/ST_GeoHash.html)
* [ST_AsLatLonText](http://postgis.net/docs/ST_AsLatLonText.html)
* [ST_AsText](http://postgis.net/docs/ST_AsText.html)

[Spatial Relationships and Measurements](http://postgis.net/docs/reference.html#Spatial_Relationships_Measurements)
----------

* [ST_3DClosestPoint](http://postgis.net/docs/ST_3DClosestPoint.html)
* [ST_3DDistance](http://postgis.net/docs/ST_3DDistance.html)
* [ST_3DDWithin](http://postgis.net/docs/ST_3DDWithin.html)
* [ST_3DDFullyWithin](http://postgis.net/docs/ST_3DDFullyWithin.html)
* [ST_3DIntersects](http://postgis.net/docs/ST_3DIntersects.html)
* [ST_3DLongestLine](http://postgis.net/docs/ST_3DLongestLine.html)
* [ST_3DMaxDistance](http://postgis.net/docs/ST_3DMaxDistance.html)
* [ST_3DShortestLine](http://postgis.net/docs/ST_3DShortestLine.html)
* [ST_Area](http://postgis.net/docs/ST_Area.html)
* [ST_Azimuth](http://postgis.net/docs/ST_Azimuth.html)
* [ST_Centroid](http://postgis.net/docs/ST_Centroid.html)
* [ST_ClosestPoint](http://postgis.net/docs/ST_ClosestPoint.html)
* [ST_Contains](http://postgis.net/docs/ST_Contains.html)
* [ST_ContainsProperly](http://postgis.net/docs/ST_ContainsProperly.html)
* [ST_Covers](http://postgis.net/docs/ST_Covers.html)
* [ST_CoveredBy](http://postgis.net/docs/ST_CoveredBy.html)
* [ST_Crosses](http://postgis.net/docs/ST_Crosses.html)
* [ST_LineCrossingDirection](http://postgis.net/docs/ST_LineCrossingDirection.html)
* [ST_Disjoint](http://postgis.net/docs/ST_Disjoint.html)
* [ST_Distance](http://postgis.net/docs/ST_Distance.html)
* [ST_HausdorffDistance](http://postgis.net/docs/ST_HausdorffDistance.html)
* [ST_MaxDistance](http://postgis.net/docs/ST_MaxDistance.html)
* [ST_Distance_Sphere](http://postgis.net/docs/ST_Distance_Sphere.html)
* [ST_Distance_Spheroid](http://postgis.net/docs/ST_Distance_Spheroid.html)
* [ST_DFullyWithin](http://postgis.net/docs/ST_DFullyWithin.html)
* [ST_DWithin](http://postgis.net/docs/ST_DWithin.html)
* [ST_Equals](http://postgis.net/docs/ST_Equals.html)
* [ST_HasArc](http://postgis.net/docs/ST_HasArc.html)
* [ST_Intersects](http://postgis.net/docs/ST_Intersects.html)
* [ST_Length](http://postgis.net/docs/ST_Length.html)
* [ST_3DLength](http://postgis.net/docs/ST_3DLength.html)
* [ST_Length3D](http://postgis.net/docs/ST_Length3D.html)
* [ST_Length_Spheroid](http://postgis.net/docs/ST_Length_Spheroid.html)
* [ST_Length2D_Spheroid](http://postgis.net/docs/ST_Length2D_Spheroid.html)
* [ST_LongestLine](http://postgis.net/docs/ST_LongestLine.html)
* [ST_OrderingEquals](http://postgis.net/docs/ST_OrderingEquals.html)
* [ST_Overlaps](http://postgis.net/docs/ST_Overlaps.html)
* [ST_Perimeter](http://postgis.net/docs/ST_Perimeter.html)
* [ST_PointOnSurface](http://postgis.net/docs/ST_PointOnSurface.html)
* [ST_Project](http://postgis.net/docs/ST_Project.html)
* [ST_Relate](http://postgis.net/docs/ST_Relate.html)
* [ST_ShortestLine](http://postgis.net/docs/ST_ShortestLine.html)
* [ST_Touches](http://postgis.net/docs/ST_Touches.html)
* [ST_Within](http://postgis.net/docs/ST_Within.html)

[Geometry Processing](http://postgis.net/docs/reference.html#Geometry_Processing)
----------

* [ST_Buffer](http://postgis.net/docs/ST_Buffer.html)
* [ST_Collect](http://postgis.net/docs/ST_Collect.html)
* [ST_Difference](http://postgis.net/docs/ST_Difference.html)
* [ST_FlipCoordinates](http://postgis.net/docs/ST_FlipCoordinates.html)
* [ST_Intersection](http://postgis.net/docs/ST_Intersection.html)
* [ST_MinimumBoundingCircle](http://postgis.net/docs/ST_MinimumBoundingCircle.html)
* [ST_Shift_Longitude](http://postgis.net/docs/ST_Shift_Longitude.html)
* [ST_Split](http://postgis.net/docs/ST_Split.html)
* [ST_SymDifference](http://postgis.net/docs/ST_SymDifference.html)
* [ST_Union](http://postgis.net/docs/ST_Union.html)


text:
#import "XMInspectorController.h"
#import "XMInspectorModule.h"

#define XMKey_SelectedInspectorModule @"XMeeting_SelectedInspectorModule"
#define XMKey_SelectedToolsModule @"XMeeting_SelectedToolsModule"
#define XMKey_SelectedContactsModule @"XMeeting_SelectedContactsModule"

@interface XMInspectorController (PrivateMethods)

- (id)_initWithName:(NSString *)name;
- (void)_showModule:(XMInspectorModule *)module;
- (void)_setupInterface;
- (void)_resizeView;
- (void)_setMaxAndMinSizes;

- (void)_setFullScreen:(BOOL)flag;
- (void)_adjustWindowLevel;

- (NSString *)_loadSelectedModuleFromPreferences;
- (void)_storeSelectedModuleInPreferences:(NSString *)selectedModule;

@end

@implementation XMInspectorController

#pragma mark Class Methods

static XMInspectorController *inspectorInstance = nil;
static XMInspectorController *toolsInstance = nil;
static XMInspectorController *contactsInstance;

+ (XMInspectorController *)inspectorWithTag:(XMInspectorControllerTag)tag
{
  if (tag == XMInspectorControllerTag_Inspector) {
    if (inspectorInstance == nil) {
      inspectorInstance = [[XMInspectorController alloc] _initWithName:NSLocalizedString(@"XM_INSPECTOR_INFO", @"")];
    }

    return inspectorInstance;
  } else if (tag == XMInspectorControllerTag_Tools) {
    if (toolsInstance == nil) {
      toolsInstance = [[XMInspectorController alloc] _initWithName:NSLocalizedString(@"XM_INSPECTOR_TOOLS", @"")];
    }

    return toolsInstance;
  } else if (tag == XMInspectorControllerTag_Contacts) {
    if (contactsInstance == nil) {
      contactsInstance = [[XMInspectorController alloc] _initWithName:NSLocalizedString(@"XM_INSPECTOR_CONTACTS", @"")];
    }

    return contactsInstance;
  }

  return nil;
}

+ (void)closeAllInspectors
{
  [inspectorInstance close];
  [toolsInstance close];
  [contactsInstance close];
}

+ (void)setFullScreen:(BOOL)flag
{
  [XMInspectorController closeAllInspectors];

  [inspectorInstance _setFullScreen:flag];
  [toolsInstance _setFullScreen:flag];
  [contactsInstance _setFullScreen:flag];
}

#pragma mark -
#pragma mark Init & Dealloc Methods

- (id)init
{
  [self doesNotRecognizeSelector:_cmd];
  [self release];
  return nil;
}

- (id)_initWithName:(NSString *)theName
{
  self = [super init];

  modules = nil;
  name = [theName copy];

  return self;
}

- (void)awakeFromNib
{
  [self _setupInterface];
}

- (void)dealloc
{
  [modules release];
  [name release];

  [super dealloc];
}

- (void)setModules:(NSArray *)theModules
{
  modules = [theModules copy];
}

#pragma mark -
#pragma mark Action Methods

- (IBAction)changePage:(id)sender
{
  XMInspectorModule *newModule = (XMInspectorModule *)[modules objectAtIndex:[pageController selectedSegment]];
  [self _showModule:newModule];
}

#pragma mark -
#pragma mark XMInspectorModule methods

- (void)moduleSizeChanged:(XMInspectorModule *)module
{
  [self _resizeView];
  [self _setMaxAndMinSizes];
}

- (void)moduleStatusChanged:(XMInspectorModule *)module
{
  unsigned index = [modules indexOfObject:module];

  if (index == NSNotFound) {
    return;
  }

  [pageController setEnabled:[module isEnabled] forSegment:index];

  if (module == activeModule && [module isEnabled] == YES) {
    // selecting the first enabled module
    unsigned count = [modules count];
    for (unsigned i = 0; i < count; i++) {
      if (i == index) {
        continue;
      }
      XMInspectorModule *theModule = (XMInspectorModule *)[modules objectAtIndex:i];

      if ([theModule isEnabled] == YES) {
        [self _showModule:theModule];
        return;
      }
    }

    [self _showModule:nil];
  }
}

#pragma mark -
#pragma mark Public Methods

- (void)show
{
  if (panel == nil) {
    // loading the Nib file. The panel is shown automatically
    // inside -_showModule:
    [NSBundle loadNibNamed:@"XMInspector" owner:self];
  } else {
    [self _adjustWindowLevel];
    if ([panel isVisible] == NO) {
      [activeModule becomeActiveModule];
      [panel orderFront:self];
    }
  }
}

- (void)showModule:(XMInspectorModule *)module
{
  unsigned index = [modules indexOfObject:module];

  if (index == NSNotFound) {
    return;
  }

  [self show];
  [pageController setSelectedSegment:index];
  [self _showModule:module];
}

- (void)close
{
  [panel orderOut:self];
}

#pragma mark -
#pragma mark NSWindow delegate methods

- (void)windowWillClose:(NSNotification *)notif
{
  [activeModule becomeInactiveModule];
}

#pragma mark -
#pragma mark Private Methods

- (void)_showModule:(XMInspectorModule *)module
{
  if (module == activeModule) {
    return;
  }

  [activeModule becomeInactiveModule];
  [contentBox setContentView:nil];

  activeModule = module;

  [self _resizeView];

  [contentBox setContentView:[activeModule contentView]];

  [self _adjustWindowLevel];
  [panel orderFront:self];

  [activeModule becomeActiveModule];

  [self _setMaxAndMinSizes];

  [self _storeSelectedModuleInPreferences:[module identifier]];
}

- (void)_setupInterface
{
  [panel setTitle:name];
  [panel setHidesOnDeactivate:NO];

  unsigned moduleCount = [modules count];
  [pageController setSegmentCount:moduleCount];

  NSString *selectedModule = [self _loadSelectedModuleFromPreferences];
  unsigned selectedModuleIndex = 0;

  for (unsigned i = 0; i < moduleCount; i++) {
    XMInspectorModule *curModule = (XMInspectorModule *)[modules objectAtIndex:i];

    if ([[curModule identifier] isEqualToString:selectedModule]) {
      selectedModuleIndex = i;
    }

    [pageController setLabel:[curModule name] forSegment:i];
    [pageController setImage:[curModule image] forSegment:i];
    [pageController setEnabled:[curModule isEnabled] forSegment:i];
    [pageController setWidth:0 forSegment:i]; //autosize
    [[pageController cell] setToolTip:[curModule name] forSegment:i];
  }

  [pageController setSelectedSegment:selectedModuleIndex];
  [self _showModule:(XMInspectorModule *)[modules objectAtIndex:selectedModuleIndex]];
}

- (void)_resizeView
{
  NSRect panelFrame = [panel frame];
  NSSize boxSize = [contentBox frame].size;
  NSSize moduleSize = [activeModule contentViewSize];

  float deltaX = moduleSize.width - boxSize.width;
  float deltaY = moduleSize.height - boxSize.height;

  panelFrame.size.width += deltaX;
  panelFrame.size.height += deltaY;
  panelFrame.origin.y -= deltaY;

  [panel setFrame:panelFrame display:YES animate:YES];
}

- (void)_setMaxAndMinSizes
{
  NSRect frame = [panel frame];
  NSSize currentSize = [activeModule contentViewSize];
  NSSize newMinSize = [activeModule contentViewMinSize];
  NSSize newMaxSize = [activeModule contentViewMaxSize];

  NSSize minSize = frame.size;
  int heightDifference = (int)currentSize.height - (int)newMinSize.height;
  int widthDifference = (int)currentSize.width - (int)newMinSize.width;
  minSize.height -= heightDifference;
  minSize.width -= widthDifference;
  [panel setMinSize:minSize];

  NSSize maxSize = frame.size;
  heightDifference = (int)newMaxSize.height - (int)currentSize.height;
  widthDifference = (int)newMaxSize.width - (int)currentSize.width;
  maxSize.height += heightDifference;
  maxSize.width += widthDifference;
  [panel setMaxSize:maxSize];

  BOOL windowIsResizable = ((minSize.width != maxSize.width) || (minSize.height != maxSize.height));

  [panel setShowsResizeIndicator:windowIsResizable];
}

- (void)_setFullScreen:(BOOL)flag
{
  isFullScreen = flag;
}

- (void)_adjustWindowLevel
{
  if (isFullScreen) {
    [panel setLevel:NSScreenSaverWindowLevel];
  } else {
    [panel setLevel:NSNormalWindowLevel];
  }
}

- (NSString *)_loadSelectedModuleFromPreferences
{
  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  if (self == inspectorInstance) {
    return [userDefaults stringForKey:XMKey_SelectedInspectorModule];
  } else if (self == toolsInstance) {
    return [userDefaults stringForKey:XMKey_SelectedToolsModule];
  } else if (self == contactsInstance) {
    return [userDefaults stringForKey:XMKey_SelectedContactsModule];
  }
  return nil;
}

- (void)_storeSelectedModuleInPreferences:(NSString *)selectedModule
{
  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  if (self == inspectorInstance) {
    [userDefaults setObject:selectedModule forKey:XMKey_SelectedInspectorModule];
  } else if (self == toolsInstance) {
    [userDefaults setObject:selectedModule forKey:XMKey_SelectedToolsModule];
  } else if (self == contactsInstance) {
    [userDefaults setObject:selectedModule forKey:XMKey_SelectedContactsModule];
  }
}

@end


text:
#ifndef JANET_UTIL_H_defined
#define JANET_UTIL_H_defined

#ifndef JANET_AMALG
#include "features.h"
#include <janet.h>
#endif

#include <stdio.h>
#include <errno.h>

/* Handle runtime errors */
#ifndef janet_exit
#include <stdio.h>
#define janet_exit(m) do { \
    printf("C runtime error at line %d in file %s: %s\n",\
        __LINE__,\
        __FILE__,\
        (m));\
    exit(1);\
} while (0)
#endif

#define janet_assert(c, m) do { \
    if (!(c)) janet_exit((m)); \
} while (0)

/* What to do when out of memory */
#ifndef JANET_OUT_OF_MEMORY
#include <stdio.h>
#define JANET_OUT_OF_MEMORY do { printf("janet out of memory\n"); exit(1); } while (0)
#endif

/* Omit docstrings in some builds */
#ifndef JANET_BOOTSTRAP
#define JDOC(x) NULL
#define JANET_NO_BOOTSTRAP
#else
#define JDOC(x) x
#endif

/* Utils */
#define janet_maphash(cap, hash) ((uint32_t)(hash) & (cap - 1))
extern const char janet_base64[65];
int32_t janet_array_calchash(const Janet *array, int32_t len);
int32_t janet_kv_calchash(const JanetKV *kvs, int32_t len);
int32_t janet_string_calchash(const uint8_t *str, int32_t len);
int32_t janet_tablen(int32_t n);
void safe_memcpy(void *dest, const void *src, size_t len);
void janet_buffer_push_types(JanetBuffer *buffer, int types);
const JanetKV *janet_dict_find(const JanetKV *buckets, int32_t cap, Janet key);
Janet janet_dict_get(const JanetKV *buckets, int32_t cap, Janet key);
void janet_memempty(JanetKV *mem, int32_t count);
void *janet_memalloc_empty(int32_t count);
JanetTable *janet_get_core_table(const char *name);
const void *janet_strbinsearch(
    const void *tab,
    size_t tabcount,
    size_t itemsize,
    const uint8_t *key);
void janet_buffer_format(
    JanetBuffer *b,
    const char *strfrmt,
    int32_t argstart,
    int32_t argc,
    Janet *argv);

/* Inside the janet core, defining globals is different
 * at bootstrap time and normal runtime */
#ifdef JANET_BOOTSTRAP
#define janet_core_def janet_def
#define janet_core_cfuns janet_cfuns
#else
void janet_core_def(JanetTable *env, const char *name, Janet x, const void *p);
void janet_core_cfuns(JanetTable *env, const char *regprefix, const JanetReg *cfuns);
#endif

/* Initialize builtin libraries */
void janet_lib_io(JanetTable *env);
void janet_lib_math(JanetTable *env);
void janet_lib_array(JanetTable *env);
void janet_lib_tuple(JanetTable *env);
void janet_lib_buffer(JanetTable *env);
void janet_lib_table(JanetTable *env);
void janet_lib_fiber(JanetTable *env);
void janet_lib_os(JanetTable *env);
void janet_lib_string(JanetTable *env);
void janet_lib_marsh(JanetTable *env);
void janet_lib_parse(JanetTable *env);
#ifdef JANET_ASSEMBLER
void janet_lib_asm(JanetTable *env);
#endif
void janet_lib_compile(JanetTable *env);
void janet_lib_debug(JanetTable *env);
#ifdef JANET_PEG
void janet_lib_peg(JanetTable *env);
#endif
#ifdef JANET_TYPED_ARRAY
void janet_lib_typed_array(JanetTable *env);
#endif
#ifdef JANET_INT_TYPES
void janet_lib_inttypes(JanetTable *env);
#endif
#ifdef JANET_THREADS
void janet_lib_thread(JanetTable *env);
#endif

#endif


text:
from enum import Enum
from azure.core import CaseInsensitiveEnumMeta

class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Defines the action to take on rule match."""

    ALLOW = "Allow"
    BLOCK = "Block"
    LOG = "Log"
    REDIRECT = "Redirect"

class AggregationInterval(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """The aggregation interval of the Timeseries."""

    HOURLY = "Hourly"
    DAILY = "Daily"

class Availability(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Indicates whether the name is available."""

    AVAILABLE = "Available"
    UNAVAILABLE = "Unavailable"

class BackendEnabledState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Whether to enable use of this backend. Permitted values are 'Enabled' or 'Disabled'."""

    ENABLED = "Enabled"
    DISABLED = "Disabled"

class CustomHttpsProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Provisioning status of Custom Https of the frontendEndpoint."""

    ENABLING = "Enabling"
    ENABLED = "Enabled"
    DISABLING = "Disabling"
    DISABLED = "Disabled"
    FAILED = "Failed"

class CustomHttpsProvisioningSubstate(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Provisioning substate shows the progress of custom HTTPS enabling/disabling process step by
    step.
    """

    SUBMITTING_DOMAIN_CONTROL_VALIDATION_REQUEST = "SubmittingDomainControlValidationRequest"
    PENDING_DOMAIN_CONTROL_VALIDATION_R_EQUEST_APPROVAL = "PendingDomainControlValidationREquestApproval"
    DOMAIN_CONTROL_VALIDATION_REQUEST_APPROVED = "DomainControlValidationRequestApproved"
    DOMAIN_CONTROL_VALIDATION_REQUEST_REJECTED = "DomainControlValidationRequestRejected"
    DOMAIN_CONTROL_VALIDATION_REQUEST_TIMED_OUT = "DomainControlValidationRequestTimedOut"
    ISSUING_CERTIFICATE = "IssuingCertificate"
    DEPLOYING_CERTIFICATE = "DeployingCertificate"
    CERTIFICATE_DEPLOYED = "CertificateDeployed"
    DELETING_CERTIFICATE = "DeletingCertificate"
    CERTIFICATE_DELETED = "CertificateDeleted"

class CustomRuleEnabledState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Describes if the custom rule is in enabled or disabled state. Defaults to Enabled if not
    specified.
    """

    DISABLED = "Disabled"
    ENABLED = "Enabled"

class DynamicCompressionEnabled(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Whether to use dynamic compression for cached content."""

    ENABLED = "Enabled"
    DISABLED = "Disabled"

class EndpointType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """The type of endpoint."""

    AFD = "AFD"
    AZURE_REGION = "AzureRegion"
    CDN = "CDN"
    ATM = "ATM"

class EnforceCertificateNameCheckEnabledState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Whether to enforce certificate name check on HTTPS requests to all backend pools. No effect on
    non-HTTPS requests.
    """

    ENABLED = "Enabled"
    DISABLED = "Disabled"

class FrontDoorCertificateSource(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Defines the source of the SSL certificate."""

    AZURE_KEY_VAULT = "AzureKeyVault"
    FRONT_DOOR = "FrontDoor"

class FrontDoorCertificateType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Defines the type of the certificate used for secure connections to a frontendEndpoint."""

    DEDICATED = "Dedicated"

class FrontDoorEnabledState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Operational status of the Front Door load balancer. Permitted values are 'Enabled' or
    'Disabled'.
    """

    ENABLED = "Enabled"
    DISABLED = "Disabled"

class FrontDoorForwardingProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Protocol this rule will use when forwarding traffic to backends."""

    HTTP_ONLY = "HttpOnly"
    HTTPS_ONLY = "HttpsOnly"
    MATCH_REQUEST = "MatchRequest"

class FrontDoorHealthProbeMethod(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Configures which HTTP method to use to probe the backends defined under backendPools."""

    GET = "GET"
    HEAD = "HEAD"

class FrontDoorProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Accepted protocol schemes."""

    HTTP = "Http"
    HTTPS = "Https"

class FrontDoorQuery(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Treatment of URL query terms when forming the cache key."""

    STRIP_NONE = "StripNone"
    STRIP_ALL = "StripAll"
    STRIP_ONLY = "StripOnly"
    STRIP_ALL_EXCEPT = "StripAllExcept"

class FrontDoorRedirectProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """The protocol of the destination to where the traffic is redirected."""

    HTTP_ONLY = "HttpOnly"
    HTTPS_ONLY = "HttpsOnly"
    MATCH_REQUEST = "MatchRequest"

class FrontDoorRedirectType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """The redirect type the rule will use when redirecting traffic."""

    MOVED = "Moved"
    FOUND = "Found"
    TEMPORARY_REDIRECT = "TemporaryRedirect"
    PERMANENT_REDIRECT = "PermanentRedirect"

class FrontDoorResourceState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Resource status of the Front Door or Front Door SubResource."""

    CREATING = "Creating"
    ENABLING = "Enabling"
    ENABLED = "Enabled"
    DISABLING = "Disabling"
    DISABLED = "Disabled"
    DELETING = "Deleting"
    MIGRATING = "Migrating"
    MIGRATED = "Migrated"

class FrontDoorTlsProtocolType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Defines the TLS extension protocol that is used for secure delivery."""

    SERVER_NAME_INDICATION = "ServerNameIndication"

class HeaderActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Which type of manipulation to apply to the header."""

    APPEND = "Append"
    DELETE = "Delete"
    OVERWRITE = "Overwrite"

class HealthProbeEnabled(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Whether to enable health probes to be made against backends defined under backendPools. Health
    probes can only be disabled if there is a single enabled backend in single enabled backend
    pool.
    """

    ENABLED = "Enabled"
    DISABLED = "Disabled"

class LatencyScorecardAggregationInterval(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """LatencyScorecardAggregationInterval."""

    DAILY = "Daily"
    WEEKLY = "Weekly"
    MONTHLY = "Monthly"

class ManagedRuleEnabledState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Describes if the managed rule is in enabled or disabled state."""

    DISABLED = "Disabled"
    ENABLED = "Enabled"

class ManagedRuleExclusionMatchVariable(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """The variable type to be excluded."""

    REQUEST_HEADER_NAMES = "RequestHeaderNames"
    REQUEST_COOKIE_NAMES = "RequestCookieNames"
    QUERY_STRING_ARG_NAMES = "QueryStringArgNames"
    REQUEST_BODY_POST_ARG_NAMES = "RequestBodyPostArgNames"
    REQUEST_BODY_JSON_ARG_NAMES = "RequestBodyJsonArgNames"

class ManagedRuleExclusionSelectorMatchOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Comparison operator to apply to the selector when specifying which elements in the collection
    this exclusion applies to.
    """

    EQUALS = "Equals"
    CONTAINS = "Contains"
    STARTS_WITH = "StartsWith"
    ENDS_WITH = "EndsWith"
    EQUALS_ANY = "EqualsAny"

class ManagedRuleSetActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Defines the action to take when a managed rule set score threshold is met."""

    BLOCK = "Block"
    LOG = "Log"
    REDIRECT = "Redirect"

class MatchProcessingBehavior(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """If this rule is a match should the rules engine continue running the remaining rules or stop.
    If not present, defaults to Continue.
    """

    CONTINUE = "Continue"
    STOP = "Stop"

class MatchVariable(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Request variable to compare with."""

    REMOTE_ADDR = "RemoteAddr"
    REQUEST_METHOD = "RequestMethod"
    QUERY_STRING = "QueryString"
    POST_ARGS = "PostArgs"
    REQUEST_URI = "RequestUri"
    REQUEST_HEADER = "RequestHeader"
    REQUEST_BODY = "RequestBody"
    COOKIES = "Cookies"
    SOCKET_ADDR = "SocketAddr"

class MinimumTLSVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """The minimum TLS version required from the clients to establish an SSL handshake with Front
    Door.
    """

    ONE0 = "1.0"
    ONE2 = "1.2"

class NetworkExperimentResourceState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Defines the server side resource status."""

    CREATING = "Creating"
    ENABLING = "Enabling"
    ENABLED = "Enabled"
    DISABLING = "Disabling"
    DISABLED = "Disabled"
    DELETING = "Deleting"

class NetworkOperationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Status of the Azure async operation."""

    IN_PROGRESS = "InProgress"
    SUCCEEDED = "Succeeded"
    FAILED = "Failed"

class Operator(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Comparison type to use for matching with the variable value."""

    ANY = "Any"
    IP_MATCH = "IPMatch"
    GEO_MATCH = "GeoMatch"
    EQUAL = "Equal"
    CONTAINS = "Contains"
    LESS_THAN = "LessThan"
    GREATER_THAN = "GreaterThan"
    LESS_THAN_OR_EQUAL = "LessThanOrEqual"
    GREATER_THAN_OR_EQUAL = "GreaterThanOrEqual"
    BEGINS_WITH = "BeginsWith"
    ENDS_WITH = "EndsWith"
    REG_EX = "RegEx"

class PolicyEnabledState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Describes if the policy is in enabled or disabled state. Defaults to Enabled if not specified."""

    DISABLED = "Disabled"
    ENABLED = "Enabled"

class PolicyMode(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Describes if it is in detection mode or prevention mode at policy level."""

    PREVENTION = "Prevention"
    DETECTION = "Detection"

class PolicyRequestBodyCheck(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Describes if policy managed rules will inspect the request body content."""

    DISABLED = "Disabled"
    ENABLED = "Enabled"

class PolicyResourceState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Resource status of the policy."""

    CREATING = "Creating"
    ENABLING = "Enabling"
    ENABLED = "Enabled"
    DISABLING = "Disabling"
    DISABLED = "Disabled"
    DELETING = "Deleting"

class PrivateEndpointStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """The Approval status for the connection to the Private Link."""

    PENDING = "Pending"
    APPROVED = "Approved"
    REJECTED = "Rejected"
    DISCONNECTED = "Disconnected"
    TIMEOUT = "Timeout"

class ResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Type of Front Door resource used in CheckNameAvailability."""

    MICROSOFT_NETWORK_FRONT_DOORS = "Microsoft.Network/frontDoors"
    MICROSOFT_NETWORK_FRONT_DOORS_FRONTEND_ENDPOINTS = "Microsoft.Network/frontDoors/frontendEndpoints"

class RoutingRuleEnabledState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled'."""

    ENABLED = "Enabled"
    DISABLED = "Disabled"

class RulesEngineMatchVariable(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Match Variable."""

    IS_MOBILE = "IsMobile"
    REMOTE_ADDR = "RemoteAddr"
    REQUEST_METHOD = "RequestMethod"
    QUERY_STRING = "QueryString"
    POST_ARGS = "PostArgs"
    REQUEST_URI = "RequestUri"
    REQUEST_PATH = "RequestPath"
    REQUEST_FILENAME = "RequestFilename"
    REQUEST_FILENAME_EXTENSION = "RequestFilenameExtension"
    REQUEST_HEADER = "RequestHeader"
    REQUEST_BODY = "RequestBody"
    REQUEST_SCHEME = "RequestScheme"

class RulesEngineOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Describes operator to apply to the match condition."""

    ANY = "Any"
    IP_MATCH = "IPMatch"
    GEO_MATCH = "GeoMatch"
    EQUAL = "Equal"
    CONTAINS = "Contains"
    LESS_THAN = "LessThan"
    GREATER_THAN = "GreaterThan"
    LESS_THAN_OR_EQUAL = "LessThanOrEqual"
    GREATER_THAN_OR_EQUAL = "GreaterThanOrEqual"
    BEGINS_WITH = "BeginsWith"
    ENDS_WITH = "EndsWith"

class RuleType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Describes type of rule."""

    MATCH_RULE = "MatchRule"
    RATE_LIMIT_RULE = "RateLimitRule"

class SessionAffinityEnabledState(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled'."""

    ENABLED = "Enabled"
    DISABLED = "Disabled"

class SkuName(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Name of the pricing tier."""

    CLASSIC_AZURE_FRONT_DOOR = "Classic_AzureFrontDoor"
    STANDARD_AZURE_FRONT_DOOR = "Standard_AzureFrontDoor"
    PREMIUM_AZURE_FRONT_DOOR = "Premium_AzureFrontDoor"

class State(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """The state of the Experiment."""

    ENABLED = "Enabled"
    DISABLED = "Disabled"

class TimeseriesAggregationInterval(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """TimeseriesAggregationInterval."""

    HOURLY = "Hourly"
    DAILY = "Daily"

class TimeseriesType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """The type of Timeseries."""

    MEASUREMENT_COUNTS = "MeasurementCounts"
    LATENCY_P50 = "LatencyP50"
    LATENCY_P75 = "LatencyP75"
    LATENCY_P95 = "LatencyP95"

class Transform(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Describes what transforms are applied before matching."""

    LOWERCASE = "Lowercase"
    UPPERCASE = "Uppercase"
    TRIM = "Trim"
    URL_DECODE = "UrlDecode"
    URL_ENCODE = "UrlEncode"
    REMOVE_NULLS = "RemoveNulls"

class TransformType(str, Enum, metaclass=CaseInsensitiveEnumMeta):
    """Describes what transforms applied before matching."""

    LOWERCASE = "Lowercase"
    UPPERCASE = "Uppercase"
    TRIM = "Trim"
    URL_DECODE = "UrlDecode"
    URL_ENCODE = "UrlEncode"
    REMOVE_NULLS = "RemoveNulls"


text:
package lila.puzzle

import akka.stream.scaladsl._
import play.api.libs.json._
import reactivemongo.akkastream.cursorProducer
import reactivemongo.api.ReadPreference
import scala.concurrent.duration._

import lila.common.config.MaxPerSecond
import lila.common.Json.jodaWrites
import lila.db.dsl._
import lila.user.User

final class PuzzleActivity(
    colls: PuzzleColls
)(implicit
    ec: scala.concurrent.ExecutionContext,
    system: akka.actor.ActorSystem
) {

  import PuzzleActivity._
  import BsonHandlers._
  import JsonView._

  def stream(config: Config): Source[String, _] =
    Source futureSource {
      colls.round.map {
        _.find($doc(PuzzleRound.BSONFields.user -> config.user.id))
          .sort($sort desc PuzzleRound.BSONFields.date)
          .batchSize(config.perSecond.value)
          .cursor[PuzzleRound](ReadPreference.secondaryPreferred)
          .documentSource(config.max | Int.MaxValue)
          .grouped(config.perSecond.value)
          .throttle(1, 1 second)
          .mapAsync(1)(enrich)
          .mapConcat(identity)
          .map { json =>
            s"${Json.stringify(json)}\n"
          }
      }
    }

  private def enrich(rounds: Seq[PuzzleRound]): Fu[Seq[JsObject]] =
    colls.puzzle {
      _.primitiveMap[Puzzle.Id, Double](
        ids = rounds.map(_.id.puzzleId),
        field = s"${Puzzle.BSONFields.glicko}.r",
        fieldExtractor = _.child("glicko").flatMap(_ double "r")
      ) map { ratings =>
        rounds flatMap { round =>
          ratings get round.id.puzzleId map { puzzleRating =>
            Json.obj(
              "id"           -> round.id.puzzleId,
              "date"         -> round.date,
              "win"          -> round.win,
              "puzzleRating" -> puzzleRating.toInt
            )
          }
        }
      }
    }
}

object PuzzleActivity {

  case class Config(
      user: User,
      max: Option[Int] = None,
      perSecond: MaxPerSecond
  )
}


text:
void runtime·sigpanic(void);

// This code is also used for the 386 tracebacks.
// Use uintptr for an appropriate word-sized integer.

// Generic traceback.  Handles runtime stack prints (pcbuf == nil),
// the runtime.Callers function (pcbuf != nil), as well as the garbage
// collector (callback != nil).  A little clunky to merge these, but avoids
// duplicating the code and all its subtlety.
int32
runtime·gentraceback(uintptr pc0, uintptr sp0, uintptr lr0, G *gp, int32 skip, uintptr *pcbuf, int32 max, void (*callback)(Stkframe*, void*), void *v, bool printall)
{
	int32 i, n, nprint, line;
	uintptr tracepc;
	bool waspanic, printing;
	Func *f, *flr;
	Stkframe frame;
	Stktop *stk;
	String file;

	USED(lr0);

	if(pc0 == ~(uintptr)0 && sp0 == ~(uintptr)0) { // Signal to fetch saved values from gp.
		if(gp->syscallstack != (uintptr)nil) {
			pc0 = gp->syscallpc;
			sp0 = gp->syscallsp;
		} else {
			pc0 = gp->sched.pc;
			sp0 = gp->sched.sp;
		}
	}

	nprint = 0;
	runtime·memclr((byte*)&frame, sizeof frame);
	frame.pc = pc0;
	frame.sp = sp0;
	waspanic = false;
	printing = pcbuf==nil && callback==nil;

	// If the PC is zero, it's likely a nil function call.
	// Start in the caller's frame.
	if(frame.pc == 0) {
		frame.pc = *(uintptr*)frame.sp;
		frame.sp += sizeof(uintptr);
	}

	f = runtime·findfunc(frame.pc);
	if(f == nil) {
		if(callback != nil) {
			runtime·printf("runtime: unknown pc %p\n", frame.pc);
			runtime·throw("unknown pc");
		}
		return 0;
	}
	frame.fn = f;

	n = 0;
	stk = (Stktop*)gp->stackbase;
	while(n < max) {
		// Typically:
		//	pc is the PC of the running function.
		//	sp is the stack pointer at that program counter.
		//	fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
		//	stk is the stack containing sp.
		//	The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.

		if(frame.pc == (uintptr)runtime·lessstack) {
			// Hit top of stack segment.  Unwind to next segment.
			frame.pc = stk->gobuf.pc;
			frame.sp = stk->gobuf.sp;
			frame.lr = 0;
			frame.fp = 0;
			frame.fn = nil;
			if(printing && runtime·showframe(nil, gp))
				runtime·printf("----- stack segment boundary -----\n");
			stk = (Stktop*)stk->stackbase;

			f = runtime·findfunc(frame.pc);
			if(f == nil) {
				runtime·printf("runtime: unknown pc %p after stack split\n", frame.pc);
				if(callback != nil)
					runtime·throw("unknown pc");
			}
			frame.fn = f;
			continue;
		}
		f = frame.fn;

		// Found an actual function.
		// Derive frame pointer and link register.
		if(frame.fp == 0) {
			frame.fp = frame.sp + runtime·funcspdelta(f, frame.pc);
			frame.fp += sizeof(uintptr); // caller PC
		}
		if(runtime·topofstack(f)) {
			frame.lr = 0;
			flr = nil;
		} else {
			if(frame.lr == 0)
				frame.lr = ((uintptr*)frame.fp)[-1];
			flr = runtime·findfunc(frame.lr);
			if(flr == nil) {
				runtime·printf("runtime: unexpected return pc for %s called from %p\n", runtime·funcname(f), frame.lr);
				if(callback != nil)
					runtime·throw("unknown caller pc");
			}
		}

		frame.varp = (byte*)frame.fp - sizeof(uintptr);

		// Derive size of arguments.
		// Most functions have a fixed-size argument block,
		// so we can use metadata about the function f.
		// Not all, though: there are some variadic functions
		// in package runtime and reflect, and for those we use call-specific
		// metadata recorded by f's caller.
		if(callback != nil || printing) {
			frame.argp = (byte*)frame.fp;
			if(f->args != ArgsSizeUnknown)
				frame.arglen = f->args;
			else if(flr == nil)
				frame.arglen = 0;
			else if(frame.lr == (uintptr)runtime·lessstack)
				frame.arglen = stk->argsize;
			else if((i = runtime·funcarglen(flr, frame.lr)) >= 0)
				frame.arglen = i;
			else {
				runtime·printf("runtime: unknown argument frame size for %s called from %p [%s]\n",
					runtime·funcname(f), frame.lr, flr ? runtime·funcname(flr) : "?");
				if(callback != nil)
					runtime·throw("invalid stack");
				frame.arglen = 0;
			}
		}

		if(skip > 0) {
			skip--;
			goto skipped;
		}

		if(pcbuf != nil)
			pcbuf[n] = frame.pc;
		if(callback != nil)
			callback(&frame, v);
		if(printing) {
			if(printall || runtime·showframe(f, gp)) {
				// Print during crash.
				//	main(0x1, 0x2, 0x3)
				//		/home/rsc/go/src/runtime/x.go:23 +0xf
				//
				tracepc = frame.pc;	// back up to CALL instruction for funcline.
				if(n > 0 && frame.pc > f->entry && !waspanic)
					tracepc--;
				runtime·printf("%s(", runtime·funcname(f));
				for(i = 0; i < frame.arglen/sizeof(uintptr); i++) {
					if(i >= 5) {
						runtime·prints(", ...");
						break;
					}
					if(i != 0)
						runtime·prints(", ");
					runtime·printhex(((uintptr*)frame.argp)[i]);
				}
				runtime·prints(")\n");
				line = runtime·funcline(f, tracepc, &file);
				runtime·printf("\t%S:%d", file, line);
				if(frame.pc > f->entry)
					runtime·printf(" +%p", (uintptr)(frame.pc - f->entry));
				if(m->throwing > 0 && gp == m->curg)
					runtime·printf(" fp=%p", frame.fp);
				runtime·printf("\n");
				nprint++;
			}
		}
		n++;

	skipped:
		waspanic = f->entry == (uintptr)runtime·sigpanic;

		// Do not unwind past the bottom of the stack.
		if(flr == nil)
			break;

		// Unwind to next frame.
		frame.fn = flr;
		frame.pc = frame.lr;
		frame.lr = 0;
		frame.sp = frame.fp;
		frame.fp = 0;
	}

	if(pcbuf == nil && callback == nil)
		n = nprint;

	return n;
}

void
runtime·printcreatedby(G *gp)
{
	int32 line;
	uintptr pc, tracepc;
	Func *f;
	String file;

	// Show what created goroutine, except main goroutine (goid 1).
	if((pc = gp->gopc) != 0 && (f = runtime·findfunc(pc)) != nil &&
		runtime·showframe(f, gp) && gp->goid != 1) {
		runtime·printf("created by %s\n", runtime·funcname(f));
		tracepc = pc;	// back up to CALL instruction for funcline.
		if(pc > f->entry)
			tracepc -= PCQuantum;
		line = runtime·funcline(f, tracepc, &file);
		runtime·printf("\t%S:%d", file, line);
		if(pc > f->entry)
			runtime·printf(" +%p", (uintptr)(pc - f->entry));
		runtime·printf("\n");
	}
}

void
runtime·traceback(uintptr pc, uintptr sp, uintptr lr, G *gp)
{
	int32 n;

	USED(lr);

	if(gp->status == Gsyscall) {
		// Override signal registers if blocked in system call.
		pc = gp->syscallpc;
		sp = gp->syscallsp;
	}

	// Print traceback. By default, omits runtime frames.
	// If that means we print nothing at all, repeat forcing all frames printed.
	n = runtime·gentraceback(pc, sp, 0, gp, 0, nil, TracebackMaxFrames, nil, nil, false);
	if(n == 0)
		n = runtime·gentraceback(pc, sp, 0, gp, 0, nil, TracebackMaxFrames, nil, nil, true);
	if(n == TracebackMaxFrames)
		runtime·printf("...additional frames elided...\n");
	runtime·printcreatedby(gp);
}

int32
runtime·callers(int32 skip, uintptr *pcbuf, int32 m)
{
	uintptr pc, sp;

	sp = runtime·getcallersp(&skip);
	pc = (uintptr)runtime·getcallerpc(&skip);

	return runtime·gentraceback(pc, sp, 0, g, skip, pcbuf, m, nil, nil, false);
}


text:
.. _continuous-gausshyper:

Gauss Hypergeometric Distribution
=================================

The two shape parameters are :math:`\alpha>0,\,\beta>0`.  The support is :math:`x\in\left[0,1\right]`.

.. math::

     \text{Let }C=\frac{1}{B\left(\alpha,\beta\right)\,_{2}F_{1}\left(\gamma,\alpha;\alpha+\beta;-z\right)}

.. math::
   :nowrap:

    \begin{eqnarray*} f\left(x;\alpha,\beta,\gamma,z\right) & = & Cx^{\alpha-1}\frac{\left(1-x\right)^{\beta-1}}{\left(1+zx\right)^{\gamma}}\\ \mu_{n}^{\prime} & = & \frac{B\left(n+\alpha,\beta\right)}{B\left(\alpha,\beta\right)}\frac{\,_{2}F_{1}\left(\gamma,\alpha+n;\alpha+\beta+n;-z\right)}{\,_{2}F_{1}\left(\gamma,\alpha;\alpha+\beta;-z\right)}\end{eqnarray*}

Implementation: `scipy.stats.gausshyper`


text:
void CScriptGameObject::SetTipText (LPCSTR tip_text)
{
	CUsableScriptObject	*l_tpUseableScriptObject = smart_cast<CUsableScriptObject*>(&object());
	if (!l_tpUseableScriptObject)
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"SetTipText. Reason: the object is not usable");
	else l_tpUseableScriptObject->set_tip_text(tip_text);
}

void CScriptGameObject::SetTipTextDefault ()
{
	CUsableScriptObject	*l_tpUseableScriptObject = smart_cast<CUsableScriptObject*>(&object());
	if (!l_tpUseableScriptObject)
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"SetTipTextDefault . Reason: the object is not usable");
	else l_tpUseableScriptObject->set_tip_text_default();
}

void CScriptGameObject::SetNonscriptUsable(bool nonscript_usable)
{
	CUsableScriptObject	*l_tpUseableScriptObject = smart_cast<CUsableScriptObject*>(&object());
	if (!l_tpUseableScriptObject)
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"SetNonscriptUsable . Reason: the object is not usable");
	else l_tpUseableScriptObject->set_nonscript_usable(nonscript_usable);
}

Fvector CScriptGameObject::GetCurrentDirection()
{
	CProjector	*obj = smart_cast<CProjector*>(&object());
	if (!obj) {
		ai().script_engine().script_log		(ScriptStorage::eLuaMessageTypeError,"Script Object : cannot access class member GetCurrentDirection!");
		return Fvector().set(0.f,0.f,0.f);
	}
	return obj->GetCurrentDirection();
}

CScriptGameObject::CScriptGameObject		(CGameObject *game_object)
{
	m_game_object	= game_object;
	m_lua_state		= NULL;
	R_ASSERT2		(m_game_object,"Null actual object passed!");
}

CScriptGameObject::~CScriptGameObject		()
{
}

CScriptGameObject *CScriptGameObject::Parent				() const
{
	CGameObject		*l_tpGameObject = smart_cast<CGameObject*>(object().H_Parent());
	if (l_tpGameObject)
		return		(l_tpGameObject->lua_game_object());
	else
		return		(0);
}

int	CScriptGameObject::clsid				() const
{
	return			(object().clsid());
}

LPCSTR CScriptGameObject::Name				() const
{
	return			(*object().cName());
}

shared_str CScriptGameObject::cName				() const
{
	return			(object().cName());
}

LPCSTR CScriptGameObject::Section				() const
{
	return			(*object().cNameSect());
}

void CScriptGameObject::Kill					(CScriptGameObject* who)
{
	CEntity				*l_tpEntity = smart_cast<CEntity*>(&object());
	if (!l_tpEntity) {
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"%s cannot access class member Kill!",*object().cName());
		return;
	}
	if (!l_tpEntity->AlreadyDie())
		l_tpEntity->KillEntity					(who ? who->object().ID() : object().ID());
	else
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"attempt to kill dead object %s",*object().cName());

}

bool CScriptGameObject::Alive					() const
{
	CEntity				*entity	= smart_cast<CEntity*>(&object());
	if (!entity) {
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"CSciptEntity : cannot access class member Alive!");
		return			(false);
	}
	return				(!!entity->g_Alive());
}

ALife::ERelationType CScriptGameObject::GetRelationType	(CScriptGameObject* who)
{
	CEntityAlive		*l_tpEntityAlive1 = smart_cast<CEntityAlive*>(&object());
	if (!l_tpEntityAlive1) {
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"%s cannot access class member GetRelationType!",*object().cName());
		return ALife::eRelationTypeDummy;
	}

	CEntityAlive		*l_tpEntityAlive2 = smart_cast<CEntityAlive*>(&who->object());
	if (!l_tpEntityAlive2) {
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"%s cannot apply GetRelationType method for non-alive object!",*who->object().cName());
		return ALife::eRelationTypeDummy;
	}

	return l_tpEntityAlive1->tfGetRelationType(l_tpEntityAlive2);
}

template <typename T>
IC	T	*CScriptGameObject::action_planner()
{
	CAI_Stalker				*manager = smart_cast<CAI_Stalker*>(&object());
	if (!manager)
		ai().script_engine().script_log				(ScriptStorage::eLuaMessageTypeError,"CAI_Stalker : cannot access class member action_planner!");
	return					(&manager->brain());
}

CScriptActionPlanner		*script_action_planner(CScriptGameObject *obj)
{
	return					(obj->action_planner<CScriptActionPlanner>());
}

void CScriptGameObject::set_enemy_callback	(const luabind::functor<bool> &functor)
{
	CCustomMonster			*monster = smart_cast<CCustomMonster*>(&object());
	if (!monster) {
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"CCustomMonster : cannot access class member set_enemy_callback!");
		return;
	}
	monster->memory().enemy().useful_callback().set(functor);
}

void CScriptGameObject::set_enemy_callback	(const luabind::functor<bool> &functor, const luabind::object &object)
{
	CCustomMonster			*monster = smart_cast<CCustomMonster*>(&this->object());
	if (!monster) {
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"CCustomMonster : cannot access class member set_enemy_callback!");
		return;
	}
	monster->memory().enemy().useful_callback().set(functor,object);
}

void CScriptGameObject::set_enemy_callback	()
{
	CCustomMonster			*monster = smart_cast<CCustomMonster*>(&object());
	if (!monster) {
		ai().script_engine().script_log			(ScriptStorage::eLuaMessageTypeError,"CCustomMonster : cannot access class member set_enemy_callback!");
		return;
	}
	monster->memory().enemy().useful_callback().clear();
}

void CScriptGameObject::SetCallback(GameObject::ECallbackType type, const luabind::functor<void> &functor)
{
	object().callback(type).set(functor);
}

void CScriptGameObject::SetCallback(GameObject::ECallbackType type, const luabind::functor<void> &functor, const luabind::object &object)
{
	this->object().callback(type).set(functor, object);
}

void CScriptGameObject::SetCallback(GameObject::ECallbackType type)
{
	object().callback(type).clear();
}

void CScriptGameObject::set_fastcall(const luabind::functor<bool> &functor, const luabind::object &object)
{

	CPHScriptGameObjectCondition* c=xr_new<CPHScriptGameObjectCondition>(object,functor,m_game_object);
	CPHDummiAction*				  a=xr_new<CPHDummiAction>();
	CPHSriptReqGObjComparer cmpr(m_game_object);
	Level().ph_commander_scripts().remove_calls(&cmpr);
	Level().ph_commander_scripts().add_call(c,a);

}
void CScriptGameObject::set_const_force(const Fvector &dir,float value,u32 time_interval)
{
	CPhysicsShell	*shell=object().cast_physics_shell_holder()->PPhysicsShell();
	if(!ph_world)	{
		ai().script_engine().script_log				(ScriptStorage::eLuaMessageTypeError,"set_const_force : ph_world do not exist!");
		return;
	}
	if(!shell){
		ai().script_engine().script_log				(ScriptStorage::eLuaMessageTypeError,"set_const_force : object %s has no physics shell!",*object().cName());
		return;
	}

	Fvector force;force.set(dir);force.mul(value);
	CPHConstForceAction *a=	xr_new<CPHConstForceAction>(shell,force);
	CPHExpireOnStepCondition *cn=xr_new<CPHExpireOnStepCondition>();
	cn->set_time_interval(time_interval);
	ph_world->AddCall(cn,a);

}


text:
package org.xbmc.kore.host.actions;

/*
 * This file is a part of the Kore project.
 */

import android.content.Context;

import org.xbmc.kore.R;
import org.xbmc.kore.host.HostCompositeAction;
import org.xbmc.kore.host.HostConnection;
import org.xbmc.kore.jsonrpc.method.Player;
import org.xbmc.kore.jsonrpc.method.Playlist;
import org.xbmc.kore.jsonrpc.type.PlayerType;
import org.xbmc.kore.jsonrpc.type.PlaylistType;
import org.xbmc.kore.utils.LogUtils;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * Opens or queues a video URL on Kodi.
 */
public class OpenSharedUrl extends HostCompositeAction<Boolean> {
    private static final String TAG = LogUtils.makeLogTag(OpenSharedUrl.class);

    private final Context context;
    private final String url;
    private final String notificationTitle;
    private final String notificationText;
    private final boolean queue;
    private final int playlistType;

    /**
     * Creates the composite action
     * @param context Context
     * @param url The url to play
     * @param notificationTitle The title of the notification to be shown when the host is currently playing a video
     * @param notificationText The notification to be shown when the host is currently playing a video
     * @param queue Whether to open or queue the item
     * @param playlistType Playlist type to queue to
     */
    public OpenSharedUrl(Context context, String url, String notificationTitle, String notificationText, boolean queue, int playlistType) {
        this.context = context;
        this.url = url;
        this.notificationTitle = notificationTitle;
        this.notificationText = notificationText;
        this.queue = queue;
        this.playlistType = playlistType;
    }

    /**
     * @return whether the host is currently playing a video. If so, the shared url
     * is added to the playlist and not played immediately.
     * @throws Error when any of the commands sent fails
     * @throws InterruptedException when {@code cancel(true)} is called on the resulting
     * future while waiting on one of the internal futures.
     */
    @Override
    public Boolean execInBackground() throws ExecutionException, InterruptedException {
        int stage = R.string.error_get_active_player;
        try {
            List<PlayerType.GetActivePlayersReturnType> players =
                    hostConnection.execute(new Player.GetActivePlayers())
                                  .get();
            boolean mediaIsPlaying = false;
            for (PlayerType.GetActivePlayersReturnType player : players) {
                if (player.type.equals(PlayerType.GetActivePlayersReturnType.VIDEO)) {
                    mediaIsPlaying = true;
                    break;
                }
            }

            stage = R.string.error_queue_media_file;
            if (!mediaIsPlaying) {
                LogUtils.LOGD(TAG, "Clearing playlist number " + playlistType);
                hostConnection.execute(new Playlist.Clear(playlistType))
                              .get();
            }

            PlaylistType.Item item = new PlaylistType.Item();
            item.file = url;
            if (queue) {
                // Queue media file to playlist:
                LogUtils.LOGD(TAG, "Queueing file");
                hostConnection.execute(new Playlist.Add(playlistType, item))
                              .get();

                if (!mediaIsPlaying) {
                    stage = R.string.error_play_media_file;
                    hostConnection.execute(new Player.Open(Player.Open.TYPE_PLAYLIST, playlistType))
                                  .get();
                } else {
                    // no get() to ignore the exception that will be thrown by OkHttp
                    hostConnection.execute(new Player.Notification(notificationTitle, notificationText));
                }
            } else {
                // Don't queue, just play the media file directly:
                stage = R.string.error_play_media_file;
                hostConnection.execute(new Player.Open(item))
                              .get();
            }

            return mediaIsPlaying;
        } catch (ExecutionException e) {
            throw new ExecutionException(context.getString(stage, e.getMessage()), e.getCause());
        }
    }
}


text:
> ⚠  NOTE: Please don't use the PR description for communication, use comments instead.

## Description (Required)

_
A short description of the overall goals of the pull request.
Optional: Is it a fix? maintenance? new feature?
_

## Other changes (e.g. bug fixes, UI tweaks, refactors)

_
Minor changes goes here. In general we should avoid that but sometimes it's much easier / faster to add a quick fix for a bug we noticed during development.
_

## TODO

> ⚠  NOTE: Please make sure all items are checked or remove the TODO list before closing the PR

- [ ] Add unit test
- [ ] Add super cool feature
- [ ] Add documentation
- [ ] Fix comment

## Scripts
** New scripts**:

- `script` : script details

## Deps

**New dependencies**:

- `dependency` : dependency details

**New dev dependencies**:

- `devDependency` : dependency details

> ⚠  NOTE: Use special keywords to close / connect the PR with the issue(s) it solves or contributes to

(Resolves | Closes | Contributes to) #1234


text:
playground
==========

playground, tutorials and more


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m151206_183702_auth_items extends Migration
{
    public $models = [
        'Category',
        'CustomerCustomerDemo',
        'CustomerDemographic',
        'Customer',
        'Employee',
        'EmployeeTerritory',
        'OrderDetail',
        'Order',
        'Product',
        'Region',
        'Shipper',
        'Supplier',
        'Territory',
        'User',
    ];

    public function safeUp()
    {
        $auth = Yii::$app->authManager;
        $role = $auth->createRole('admin');
        $auth->add($role);

        foreach ($this->models as $model) {
            foreach (['create', 'read', 'update', 'delete'] as $opName) {
                $authItem = $auth->createPermission('app\\models\\' . $model . '.' . $opName);
                $auth->add($authItem);
                $auth->addChild($role, $authItem);
            }
        }

        $auth->assign($role, 1); // default admin user
    }

    public function safeDown()
    {
        $auth = Yii::$app->authManager;
        $auth->remove($auth->getRole('admin'));

        foreach ($this->models as $model) {
            foreach (['create', 'read', 'update', 'delete'] as $opName) {
                $item = $auth->getPermission('app\\models\\' . $model . '.' . $opName);
                if ($item !== null) {
                    $auth->remove($item);
                }
            }
        }
    }
}


text:
Originally published: 2014-11-08 19:10:57
Last updated: 2014-11-08 19:10:58
Author: Barry Walker

Not Quite So Simple QuickTime Player, Python Audio Capture.

This DEMO code captures a function to generate a user 5 second Audio sample in Apple *.aifc format.
It is then converted to DC quailty *.WAV format.

It uses default shell system files to do the task.

An AppleScript is created to do the sample but due to the limitations of QT Player there is a 1.5 second delay to allow QuickTine Player to start up.
It is not entirely quiet but unobtrusive enough as to be like quiet mode...

This is again a means a signal capture for an AudioScope without the need for special tools or installs.

Read the code for more information.

IMPORTANT!!! This DEMO WILL delete all *.aifc files inside the default $HOME/Movies directory, so be aware.

A simple ALSA one is on its way too...

It actually works on Python 3.4.1 but I have no idea if it works below Python 2.5.6...

Bazza...