text:
//
//  LGIntegration.m
//  AutoPkgr
//
//  Copyright 2015 Eldon Ahrold
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "LGAutoPkgRepo.h"
#import "LGAutoPkgr.h"
#import "LGIntegration+Protocols.h"
#import "LGIntegration.h"

#import "LGAutoPkgTask.h"
#import "LGHostInfo.h"
#import "LGInstaller.h"
#import "LGUninstaller.h"

#ifndef LGINTEGRATION_SUBCLASS
#define LGINTEGRATION_SUBCLASS
#endif

NSString *const kLGNotificationIntegrationStatusDidChange = @"com.lindegroup.autopkgr.notification.integration.status.did.change";

@interface LGIntegration () <LGIntegrationSubclass>
@property (strong, nonatomic, readwrite) LGIntegrationInfo *info;
@end

@interface LGIntegrationInfo ()
- (instancetype)initWithIntegration:(LGIntegration *)integration;
@end

void subclassMustImplement(id className, SEL _cmd)
{
    NSString *reason = [NSString stringWithFormat:@"Subclass of %s must implement the method \"%s\".",
                                                  object_getClassName(className), sel_getName(_cmd)];
    @throw [NSException exceptionWithName:@"SubclassMustImplement"
                                   reason:reason
                                 userInfo:nil];
}

void subclassMustConformToProtocol(id className)
{
    NSString *reason = [NSString stringWithFormat:@"[ EXCEPTION ] %s must conform to at least one LGIntegration protocol",
                                                  object_getClassName(className)];
    @throw [NSException exceptionWithName:@"SubclassMustConform"
                                   reason:reason
                                 userInfo:nil];
}

@implementation LGIntegration {
@private
    void (^_progressUpdateBlock)(NSString *, double);
    void (^_replyErrorBlock)(NSError *);
    NSMutableDictionary *_infoUpdateBlocksDict;
    id<LGProgressDelegate> _origProgressDelegate;

@public
    LGAutoPkgRepo *_repo;
}

@synthesize installedVersion = _installedVersion;
@synthesize remoteVersion = _remoteVersion;
@synthesize gitHubInfo = _gitHubInfo;

// Dispatch queue for synchronizing infoHandler setter and refresh.
+ (dispatch_queue_t)synchronizerQueue
{
    NSString *queueName = quick_formatString(@"com.lindegroup.autopkgr.integration.%@.synchronizer.queue", self.className);
    static dispatch_queue_t dispatch_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dispatch_queue = dispatch_queue_create(queueName.UTF8String, DISPATCH_QUEUE_SERIAL);
    });
    return dispatch_queue;
}

#pragma mark - Protocol conform check
+ (void)initialize
{
    // We only need to check subclasses (and should ignore the super).
    if ((self != [LGIntegration class]) && [self isSubclassOfClass:[LGIntegration class]]) {

        // The subclasses must conform to at least one of the protocols.
        if (([self conformsToProtocol:@protocol(LGIntegrationSharedProcessor)] ||
             [self conformsToProtocol:@protocol(LGIntegrationPackageInstaller)])
            == NO) {
            subclassMustConformToProtocol(self);
        }
    }
}

#pragma mark - Integration
+ (BOOL)isInstalled
{
    if ((self.typeFlags & kLGIntegrationTypeAutoPkgSharedProcessor) && (![self components])) {
        NSPredicate *match = [NSPredicate predicateWithFormat:@"%K == %@", kLGAutoPkgRepoURLKey, [[self class] defaultRepository]];
        return [[LGAutoPkgTask repoList] filteredArrayUsingPredicate:match].count;
    }
    else {
        NSFileManager *fm = [NSFileManager defaultManager];
        for (NSString *file in self.components) {
            if (![fm fileExistsAtPath:file]) {
                return NO;
            }
        }
    }
    return YES;
}

+ (NSString *)summaryResultKey
{
    return nil;
}

+ (BOOL)isUninstallable
{
    return NO;
}

+ (BOOL)meetsRequirements:(NSError *__autoreleasing *)error
{
    return YES;
}

#pragma mark - Init / Dealloc
- (void)dealloc
{
    // nil out the blocks to break retain cycles.
    _progressUpdateBlock = nil;
    _replyErrorBlock = nil;

    DevLog(@"Starting Dealloc %@", self);
    NSMutableDictionary *releaseDict = _infoUpdateBlocksDict;
    [releaseDict enumerateKeysAndObjectsUsingBlock:^(void (^infoUpdate)(LGIntegrationInfo *), id obj, BOOL * stop) {
        infoUpdate = nil;
    }];
    [releaseDict removeAllObjects];
    DevLog(@"Done Dealloc %@", self);
}

- (instancetype)init
{
    if (self = [super init]) {
        LGIntegrationTypeFlags flags = [[self class] typeFlags];
        if (flags & kLGIntegrationTypeInstalledPackage) {
            self.gitHubInfo = [[LGGitHubReleaseInfo alloc] initWithURL:[[self class] gitHubURL]];
        }
        NSString *cloneURL = nil;
        if ((cloneURL = [[self class] defaultRepository])) {
            _repo = [[LGAutoPkgRepo alloc] initWithCloneURL:cloneURL];
        }
    }
    return self;
}

#pragma mark - Subclass responsibility

+ (NSString *)name
{
    subclassMustImplement(self, _cmd);
    return nil;
}

+ (LGIntegrationTypeFlags)typeFlags
{
    LGIntegrationTypeFlags flags = kLGIntegrationTypeUnspecified;
    if ([self conformsToProtocol:@protocol(LGIntegrationSharedProcessor)]) {
        flags += kLGIntegrationTypeAutoPkgSharedProcessor;
    }

    if ([self conformsToProtocol:@protocol(LGIntegrationPackageInstaller)]) {
        flags += kLGIntegrationTypeInstalledPackage;
    }

    if ([self isUninstallable]) {
        flags += kLGIntegrationTypeUninstallableIntegration;
    }

    return flags;
}

+ (NSString *)binary
{
    if ([self typeFlags] & kLGIntegrationTypeInstalledPackage) {
        subclassMustImplement(self, _cmd);
    }
    return nil;
}

+ (NSArray *)components
{
    return nil;
}

+ (NSString *)defaultRepository
{
    if ([self typeFlags] & kLGIntegrationTypeAutoPkgSharedProcessor) {
        subclassMustImplement(self, _cmd);
    }
    return nil;
}

+ (NSString *)gitHubURL
{
    if ([[self class] typeFlags] & kLGIntegrationTypeInstalledPackage) {
        subclassMustImplement(self, _cmd);
    }
    return nil;
}

+ (NSArray *)packageIdentifiers
{
    if ([[self class] typeFlags] & kLGIntegrationTypeInstalledPackage) {
        subclassMustImplement(self, _cmd);
    }
    return nil;
}

+ (NSString *)credits
{
    return nil;
}

+ (NSURL *)homePage
{
    return nil;
}

+ (NSString *)shortName
{
    return nil;
}

#pragma mark - Super implementation
- (void)customInstallActions:(void (^)(NSError *error))reply
{
    reply(nil);
}
- (void)customUninstallActions:(void (^)(NSError *error))reply
{
    reply(nil);
}

- (BOOL)isInstalled
{
    return [[self class] isInstalled];
}

- (NSString *)name
{
    return [[self class] name];
}

- (void)getInfo:(void (^)(LGIntegrationInfo *))reply
{
    /*
     * There are a few terms here that should be clairified.
     * _info = Mapped values for the UI such as
     * _gitHubInfo = raw data obtained from the GitHub API.
     */

    _isRefreshing = YES;
    void (^updateInfoHandlers)() = ^() {
        dispatch_async([[self class] synchronizerQueue], ^{
            self.info = [[LGIntegrationInfo alloc] initWithIntegration:self];
            if (reply || _infoUpdateHandler) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (_infoUpdateHandler) {
                        _infoUpdateHandler(_info);
                    }
                    if (reply) {
                        reply(_info);
                    }
                });
            }
            _isRefreshing = NO;
        });
    };

    NSString *url = [[self class] gitHubURL];
    if (!url) {
        // If there's no URL, check for a default repo. The _repo iVar is
        // initialized during this object's init if it. The repo's status can then
        // be used as the criteria for the integration's status.
        if (_repo && !_repo.status) {
            [_repo getRepoStatus:^(LGAutoPkgRepoStatus status) {
                updateInfoHandlers();
            }];
        }
        else {
            updateInfoHandlers();
        }
    }
    else if (!self.gitHubInfo || self.gitHubInfo.isExpired) {
        DevLog(@"Getting remote GitHub info for %@", self.class);

        LGGitHubJSONLoader *loader = [[LGGitHubJSONLoader alloc] initWithGitHubURL:url];
        loader.apiToken = [LGAutoPkgTask apiToken];

        [loader getReleaseInfo:^(LGGitHubReleaseInfo *gitHubInfo, NSError *error) {
            self.gitHubInfo = gitHubInfo;
            updateInfoHandlers();
        }];
    }
    else {
        DevLog(@"Using cached GitHub info for %@", self.class);
        updateInfoHandlers();
    }
}

- (void)refresh;
{
    [self getInfo:nil];
}

- (LGIntegrationInfo *)info
{
    if (!_info) {
        _info = [[LGIntegrationInfo alloc] initWithIntegration:self];
    }
    return _info;
}

- (NSString *)remoteVersion
{
    if ([[self class] typeFlags] & kLGIntegrationTypeInstalledPackage) {
        return self.gitHubInfo.latestVersion;
    }

    // For now shared processors don't report a version.
    // We could possibly use git to check for an update.
    return nil;
}

- (NSString *)installedVersion
{
    LGIntegrationTypeFlags typeFlags = [[self class] typeFlags];

    if (typeFlags & kLGIntegrationTypeInstalledPackage) {
        NSFileManager *fm = [NSFileManager defaultManager];
        NSString *packageReceipt = [[@"/private/var/db/receipts/" stringByAppendingPathComponent:[[[self class] packageIdentifiers] firstObject]] stringByAppendingPathExtension:@"plist"];

        if ([[self class] isInstalled]) {
            if ([fm fileExistsAtPath:packageReceipt]) {
                NSDictionary *receiptDict = [NSDictionary dictionaryWithContentsOfFile:packageReceipt];
                _installedVersion = receiptDict[@"PackageVersion"];
            }
        }
    }
    else if (typeFlags & kLGIntegrationTypeAutoPkgSharedProcessor) {
        _installedVersion = @"";
    }

    return _installedVersion;
}

- (NSString *)downloadURL
{
    return self.gitHubInfo.latestReleaseDownload;
}

#pragma mark - Installer
- (void)install:(id)sender
{
    // Disable the sender to prevent multiple signals
    if ([sender respondsToSelector:@selector(isEnabled)]) {
        [sender setEnabled:NO];
    }

    void (^complete)(NSError *) = ^void(NSError *error) {
        if (error.code == errAuthorizationCanceled) {
            return [self didCompleteInstallAction:sender error:nil];
        }

        [self customInstallActions:^(NSError *customError) {
            NSError *endError = error;
            if (customError && (endError == nil)) {
                endError = customError;
            }
            [self didCompleteInstallAction:sender error:endError];
        }];
    };

    void (^addRepo)() = ^void() {
        NSString *name = self.name;
        if (self.progressDelegate) {
            [self.progressDelegate startProgressWithMessage:[NSString stringWithFormat:@"Adding default AutoPkg repo for %@...", name]];
        }
        if (_repo.isInstalled) {
            [_repo update:^(NSError *error) {
                complete(error);
            }];
        }
        else {
            [_repo install:^(NSError *error) {
                complete(error);
            }];
        }
    };

    LGIntegrationTypeFlags flags = [[self class] typeFlags];
    NSError *error = nil;
    if (![[self class] meetsRequirements:&error]) {
        [self didCompleteInstallAction:sender error:error];
    }
    else if (flags & kLGIntegrationTypeInstalledPackage) {
        NSString *name = [[self class] name];
        NSString *installMessage = [NSString stringWithFormat:@"Installing %@...", [[self class] name]];
        [self.progressDelegate startProgressWithMessage:installMessage];

        LGInstaller *installer = [[LGInstaller alloc] init];
        installer.downloadURL = self.downloadURL;
        installer.progressDelegate = self.progressDelegate;

        [installer runInstaller:name
                          reply:^(NSError *error) {
                              if (!error && _repo) {
                                  addRepo();
                              }
                              else {
                                  complete(error);
                              }
                          }];
    }
    else if (flags & kLGIntegrationTypeAutoPkgSharedProcessor) {
        addRepo();
    }
}

- (void)install:(void (^)(NSString *, double))progress reply:(void (^)(NSError *))reply
{
    if (progress) {
        if (_progressDelegate) {
            _origProgressDelegate = _progressDelegate;
        }
        _progressUpdateBlock = progress;
        _progressDelegate = self;
    }

    if (reply) {
        _replyErrorBlock = reply;
    }

    [self install:nil];
}

#pragma mark - Uninstall
- (void)uninstall:(id)sender
{
    void (^complete)(NSError *) = ^void(NSError *error) {
        if (error.code == errAuthorizationCanceled) {
            return [self didCompleteInstallAction:sender error:error];
        }
        [self customUninstallActions:^(NSError *customError) {
            NSError *endError = error;
            if (customError && !endError) {
                endError = customError;
            }
            [self didCompleteInstallAction:sender error:endError];
        }];
    };

    NSAlert *alert = [[NSAlert alloc] init];
    NSView *upsize = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 450, 0)];
    alert.accessoryView = upsize;

    NSString *messageTextFormat = NSLocalizedString(@"Are you sure you want to uninstall %@?",
                                                    @"NSAlert infoText prompt during uninstall.");
    alert.messageText = quick_formatString(messageTextFormat, self.name);

    NSString *infoTextFormat = NSLocalizedString(@"This includes executables, default repositories, and/or settings?",
                                                 @"NSAlert messageText prompt during uninstall.");
    alert.informativeText = infoTextFormat;

    [alert addButtonWithTitle:@"Uninstall"];
    [alert addButtonWithTitle:@"Cancel"];

    if ([alert runModal] == NSAlertSecondButtonReturn) {
        return complete([LGError errorWithCode:errAuthorizationCanceled]);
    }

    void (^removeRepo)() = ^void() {
        NSString *defaultRepo = [[self class] defaultRepository];
        if ([LGAutoPkgTask version]) {
            LGAutoPkgTask *task = [LGAutoPkgTask repoDeleteTask:defaultRepo];

            [self.progressDelegate startProgressWithMessage:quick_formatString(NSLocalizedString(@"Removing default AutoPkg repo for %@", nil), self.name)];

            if (self.progressDelegate) {
                task.progressDelegate = self.progressDelegate;
            }
            [task launchInBackground:^(NSError *error) {
                complete(error);
            }];
        }
        else {
            complete(nil);
        }
    };

    if ([[self class] isInstalled]) {
        LGIntegrationTypeFlags typeFlags = [[self class] typeFlags];

        if (typeFlags & kLGIntegrationTypeInstalledPackage) {
            LGUninstaller *uninstaller = [[LGUninstaller alloc] init];

            NSString *message = quick_formatString(NSLocalizedString(@"Uninstalling %@...",
                                                                     @"message when integration begins uninstalling"),
                                                   self.name);

            [self.progressDelegate startProgressWithMessage:message];

            if (self.progressDelegate) {
                uninstaller.progressDelegate = self.progressDelegate;
            }

            [uninstaller uninstallPackagesWithIdentifiers:[[self class] packageIdentifiers]
                                                    reply:^(NSError *error) {
                                                        if (!error && (typeFlags & kLGIntegrationTypeAutoPkgSharedProcessor)) {
                                                            removeRepo();
                                                        }
                                                        else {
                                                            complete(error);
                                                        }
                                                    }];
        }
        else if (typeFlags & kLGIntegrationTypeAutoPkgSharedProcessor) {
            removeRepo();
        }
    }
}

- (void)uninstall:(void (^)(NSString *, double))progress reply:(void (^)(NSError *))reply
{
    if (progress) {
        if (_progressDelegate) {
            _origProgressDelegate = _progressDelegate;
        }
        _progressUpdateBlock = progress;
        _progressDelegate = self;
    }

    if (reply) {
        _replyErrorBlock = reply;
    }

    [self uninstall:nil];
}

#pragma mark - Install / Uninstall completion
- (void)didCompleteInstallAction:(id)sender error:(NSError *)error
{
    dispatch_async(dispatch_get_main_queue(), ^{
        BOOL isInstalled = [[self class] isInstalled];
        if ([self.progressDelegate respondsToSelector:@selector(stopProgress:)]) {
            [self.progressDelegate stopProgress:error];
        }

        if ([sender respondsToSelector:@selector(isEnabled)]) {
            [sender setEnabled:YES];
        }

        if ([sender respondsToSelector:@selector(action)]) {
            if ([[self class] isUninstallable]) {
                [sender setAction:isInstalled ? @selector(uninstall:) : @selector(install:)];
            }
        }

        [[NSNotificationCenter defaultCenter] postNotificationName:kLGNotificationIntegrationStatusDidChange object:self];

        if (_origProgressDelegate) {
            _progressDelegate = _origProgressDelegate;
            _origProgressDelegate = nil;
        }

        [self refresh];
    });
}

#pragma mark - Util

- (NSString *)versionTaskWithExec:(NSString *)exec arguments:(NSArray *)arguments
{
    NSString *installedVersion = nil;

    if ([[NSFileManager defaultManager] isExecutableFileAtPath:exec]) {
        NSTask *task = [[NSTask alloc] init];
        task.launchPath = exec;
        task.arguments = arguments;
        task.standardOutput = [NSPipe pipe];

        @try {
            [task launch];
            [task waitUntilExit];

            NSData *data = [[task.standardOutput fileHandleForReading] readDataToEndOfFile];
            if (data) {
                installedVersion = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            }
        }
        @catch (NSException *exception) {
            NSLog(@"There was a problem when executing %@ with args: %@, if the issue persists please open an issue on the AutoPkgr GitHub page.", exec, [arguments componentsJoinedByString:@" "]);
        }
    }
    return installedVersion ?: @"0.0.0";
}

+ (NSError *)requirementsError:(NSString *)reason
{
    NSString *description = quick_formatString(NSLocalizedString(@"Requirements for %@ are not met.", nil), [[self class] name]);
    NSDictionary *userInfo = @{
        NSLocalizedDescriptionKey : description,
        NSLocalizedRecoverySuggestionErrorKey : reason ?: @"",
    };

    return [NSError errorWithDomain:kLGApplicationName code:(4 << 1) userInfo:userInfo];
}

#pragma mark - LGProgress Delegate

- (void)stopProgress:(NSError *)error
{
    if (_replyErrorBlock) {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            _replyErrorBlock(error);
        }];
    }
}

- (void)updateProgress:(NSString *)message progress:(double)progress
{
    if (_progressUpdateBlock) {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            _progressUpdateBlock(message, progress);
        }];
    }
}

- (void)startProgressWithMessage:(NSString *)message { /* Not implemented */}
- (void)bringAutoPkgrToFront { /* Not implemented */}

@end

#pragma mark - Integration Info Object
@implementation LGIntegrationInfo {
    NSString *_name;
    NSString *_shortName;
    LGIntegrationTypeFlags _typeFlags;
    LGIntegrationInstallStatus _status;
    LGAutoPkgRepoStatus _repoStatus;
    BOOL _installed;
}

- (instancetype)initWithIntegration:(LGIntegration *)integration;
{
    if (self = [super init]) {
        _name = [[integration class] name].copy;
        _shortName = [[integration class] shortName].copy;
        _typeFlags = [[integration class] typeFlags];
        _installed = [[integration class] isInstalled];

        _remoteVersion = integration.remoteVersion.copy;
        _installedVersion = integration.installedVersion.copy;

        _repoStatus = integration->_repo.status;
    }
    return self;
}

- (LGIntegrationInstallStatus)status
{
    _status = kLGIntegrationUpToDate;
    if (!_installed) {
        _status = kLGIntegrationNotInstalled;
    }
    else if (!_installedVersion.length) {
        if (_repoStatus) {
            switch (_repoStatus) {
            case kLGAutoPkgRepoNotInstalled: {
                _status = kLGIntegrationNotInstalled;
                break;
            }
            case kLGAutoPkgRepoUpdateAvailable: {
                _status = kLGIntegrationUpdateAvailable;
                break;
            }
            case kLGAutoPkgRepoUpToDate: {
                _status = kLGIntegrationUpToDate;
                break;
            }
            }
        }
        else {
            _status = kLGIntegrationNotInstalled;
        }
    }
    else if (_installedVersion && _remoteVersion) {
        if ([_remoteVersion version_isGreaterThan:_installedVersion]) {
            _status = kLGIntegrationUpdateAvailable;
        }
    }
    return _status;
}

#pragma mark - Mappings

- (NSImage *)statusImage
{
    NSImage *stausImage = nil;
    switch (self.status) {
    case kLGIntegrationNotInstalled:
        stausImage = [NSImage LGStatusNone];
        break;
    case kLGIntegrationUpdateAvailable:
        stausImage = [NSImage LGStatusUpdateAvailable];
        break;
    case kLGIntegrationUpToDate:
        stausImage = [NSImage LGStatusUpToDate];
        break;
    }
    return stausImage;
}

- (NSString *)statusString
{
    NSString *statusString = @"";
    switch (self.status) {
    case kLGIntegrationNotInstalled:
        statusString = quick_formatString(NSLocalizedString(@"%@ not installed.",
                                                            @"status message when not integration is not installed"),
                                          _name);
        break;
    case kLGIntegrationUpdateAvailable:
        statusString = quick_formatString(NSLocalizedString(@"%@ %@ update now available.",
                                                            @"Status message when integration update is available."),
                                          _name, self.remoteVersion ?: @"");
        break;
    case kLGIntegrationUpToDate:
        statusString = quick_formatString(NSLocalizedString(@"%@ %@ installed.",
                                                            @"Status message when integration is up to date."),
                                          _name, self.installedVersion ?: @"");
        break;
    }
    return [statusString stringByReplacingOccurrencesOfString:@"  " withString:@" "];
}

- (BOOL)needsInstalled
{
    switch (self.status) {
    case kLGIntegrationNotInstalled:
    case kLGIntegrationUpdateAvailable:
        return YES;
    case kLGIntegrationUpToDate:
        return NO;
    }
}

- (NSString *)installButtonTitle
{
    NSString *title = @"";
    switch (self.status) {
    case kLGIntegrationUpToDate:
        if (_typeFlags & kLGIntegrationTypeUninstallableIntegration) {
            title = @"Uninstall ";
            break;
        }
    case kLGIntegrationNotInstalled:
        title = @"Install ";
        break;
    case kLGIntegrationUpdateAvailable:
        title = @"Update ";
        break;
    }
    return [title stringByAppendingString:_shortName ?: _name];
}

- (BOOL)installButtonEnabled
{
    switch (self.status) {
    case kLGIntegrationNotInstalled:
    case kLGIntegrationUpdateAvailable:
        return YES;
    case kLGIntegrationUpToDate:
        return (_typeFlags & kLGIntegrationTypeUninstallableIntegration);
    }
}

- (SEL)installButtonTargetAction
{
    if ((self.status == kLGIntegrationUpToDate) && (_typeFlags | kLGIntegrationTypeUninstallableIntegration)) {
        return @selector(uninstall:);
    }
    else {
        return @selector(install:);
    }
}

- (NSString *)configureButtonTitle
{
    NSString *title = @"???";
    switch (self.status) {
    case kLGIntegrationNotInstalled:
        title = @"Install ";
        break;
    case kLGIntegrationUpToDate:
    case kLGIntegrationUpdateAvailable:
        title = @"Configure ";
        break;
    }
    title = [title stringByAppendingString:_shortName ?: _name];
    return [title stringByAppendingString:@"..."];
}

- (BOOL)configureButtonEnabled
{
    return YES;
}

- (SEL)configureButtonTargetAction
{
    SEL selector = nil;

    if (self.status != kLGIntegrationNotInstalled) {
        selector = NSSelectorFromString(@"configure:");
    }
    else {
        selector = @selector(install:);
    }
    return selector;
}

@end


text:
import React, { Component } from 'react';
import Button               from './Common/button'

import GroupsPage           from './GroupsPage'
import UserProfilePage      from './UserProfilePage'
import GroupsInvitePage     from './GroupsInvitePage'
import EventFeed            from './EventFeed'
import CreateMarker         from './CreateMarker'
import markersApi           from '../Utils/markersApi'
import messagesApi          from '../Utils/messagesApi'
import Firebase             from 'firebase'
import QuestionBox          from './QuestionBox'

import MapView              from 'react-native-maps'
import CustomCallout        from './CustomCallout'

import {
  StyleSheet,
  PropTypes,
  View,
  Text,
  Dimensions,
  TouchableOpacity,
  NavigatorIOS,
  AlertIOS,
  Image,
  TouchableHighlight,
  LinkingIOS,
  Animated
} from 'react-native';

var { width, height } = Dimensions.get('window');

const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const SPACE = 0.01;

class GoogleMap extends Component {
 componentWillMount(){
    this.markerRef.on("value", function(res) {
      var allMarkers = [];
      for(var i in res.val()) {
        allMarkers.push(res.val()[i])
      }
      this.setState({
        markers: allMarkers
      })
      this.render()
    }.bind(this))
   }

  constructor(props) {
    super(props);
    this.markerRef = new Firebase('https://ralli.firebaseio.com/markers');
    this.state = {
      bounceValue: new Animated.Value(0),
      region: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      },
      markers: ["placeholder"]
    };
  }

  onMarkerPress() {}

  onPressGroups() {
    this.props.navigator.push ({
      title: 'Groups Page',
      component: GroupsPage,
      passProps: {userData: this.props.userData, userId: this.props.userId}
    })
  }

  onPressProfile() {
    this.props.navigator.push ({
      title: 'Profile Page',
      component: UserProfilePage,
      passProps: {userData: this.props.userData, userId: this.props.userId}
    })
  }

  onPressFeed() {
    this.props.navigator.push ({
      title: 'Feed',
      component: EventFeed,
      passProps: {userData: this.props.userData, userId: this.props.userId}
    })
  }

  onPressCreateMarker () {
    this.props.navigator.push ({
      title: 'Make a Rally',
      component: CreateMarker,
      passProps: {
        userId: this.props.userId,
        userData: this.props.userData
      }
    })
  }

  onPressSurprise() {
    // function to get a a random number between range because js
    if (this.props.userData.markers) {
      function getRandomIntInclusive(min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
      }
      // need latest array of user markers (realtime)
      let len = this.props.userData.markers.length
      let eventIndex = getRandomIntInclusive(0, len)
      let randEventId = this.props.userData.markers[eventIndex]

      new Firebase('https://ralli.firebaseio.com/markers/' + randEventId)
        .once("value")
        .then((res) =>
        this.props.navigator.push ({
          title: 'Surprise',
          component: QuestionBox,
          passProps: {
            userId: this.props.userId,
            userData: this.props.userData,
            eventInfo: res.val()
          }
        })
      )
    } else {
      AlertIOS.alert(
       'Sorry ' + this.props.userData.username,
       "Looks like you've not been invited to any events."
      )
    }
  }

  iAmGoingButton(item) {
    let eventOwnerId = item.creator;
    let message = this.props.userData.username + " is going to your event: " + item.title
    messagesApi.individualUserMessenger(eventOwnerId, message)
  }

  onRegionChange(region) {
    this.state.region = region;
  }

  onLikeButton() {
    this.state.bounceValue.setValue(1.5);
    Animated.spring(
      this.state.bounceValue,
      {
        toValue: 0.8,
        friction: 1,
      }
    ).start();
  }

  markerCenter() {
  }

  render() {
    const { region, markers } = this.state;
    let markersList = this.state.markers.map((item, index) => {
    return (
      <MapView.Marker
        ref="m3"
        key={index}
        image={this.state.iconLoaded ? 'markerLoaded' : 'marker'}
        showsUserLocation={true}
        followUserLocation={true}
        coordinate={markers[index].coordinate}
        calloutAnchor={{ x: 0.1, y: 0.1 }}
        calloutOffset={{ x: -8, y: 29 }}
      >
        <Image source={require('./Common/other-small-icon.png')} onLoadEnd={() => {if (!this.state.iconLoaded) this.setState({iconLoaded: true});}}/>
        <MapView.Callout tooltip>
          <TouchableOpacity onPress={this.markerCenter.bind(this)}>
            <CustomCallout style={styles.calloutOpacity}>
              <View style={styles.wrapper}>
                <Text style={styles.calloutHeader}>{markers[index].title}</Text>
              </View>
              <Text style={styles.calloutText}> {markers[index].address}</Text>
              <Text style={styles.calloutText}> {markers[index].description}</Text>
              <Text style={styles.calloutText}> {markers[index].timeStart}</Text>
              <Text style={styles.calloutText}> Group: {markers[index].groups}</Text>
              <Image style={styles.calloutImage} source={require('./Common/sbpete.png')}/>
              <Button onPress={this.iAmGoingButton.bind(this, item)} text="I'm Going"></Button>
            </CustomCallout>
          </TouchableOpacity>
        </MapView.Callout>
      </MapView.Marker>

      )
    });
      return (
        <View style={styles.container}>
          <MapView style={styles.map}
          initialRegion={region}
          showsUserLocation={true}
          followUserLocation={true}>
          {markersList}
          </MapView>
          <View style={styles.buttonContainer}>
            <TouchableOpacity onPress={this.onPressGroups.bind(this)} style={[styles.bubble, styles.button]}>
              <Image source={require('./Common/usergroup.png')} style={styles.icongood} />
            </TouchableOpacity>
            <TouchableOpacity onPress={this.onPressProfile.bind(this)} style={[styles.bubble, styles.button]}>
              <Image source={require('./Common/profile.png')} style={styles.icon}/>
            </TouchableOpacity>
            <TouchableOpacity onPress={this.onPressCreateMarker.bind(this)} style={[styles.bubble, styles.button]}>
              <Image source={require('./Common/Untitled.png')} style={styles.middleicon}/>
            </TouchableOpacity>
            <TouchableOpacity onPress={this.onPressFeed.bind(this)} style={[styles.bubble, styles.button]}>
              <Image source={require('./Common/activityfeed.png')} style={styles.icon} />
            </TouchableOpacity>
            <TouchableOpacity onPress={this.onPressSurprise.bind(this)} style={[styles.bubble, styles.button]}>
              <Image source={require('./Common/question.png')} style={styles.icon} />
            </TouchableOpacity>
          </View>
        </View>
      );
  }
}

let styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  map: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'red',
  },
  bubble: {
    flex: 1,
    backgroundColor: 'rgba(255,255,255,0.7)',
    paddingHorizontal: 18,
    paddingVertical: 12,
  },
  latlng: {
    width: 200,
    alignItems: 'stretch',
  },
  button: {
    height: height * .08,
    width: width * .20,
    alignItems: 'center',
    justifyContent: 'center'
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'flex-end',
    backgroundColor: 'transparent',

  },
  calloutHeader: {
    fontSize: 24,
    color: '#fff',
    marginBottom: 5,
    flex: 1
  },
  calloutText: {
    color: '#fff',
    flex: 1
  },
  calloutOpacity: {
    borderRadius: 8,
    opacity: .8
  },
  icon: {
    height: 25,
    width: 25,
  },
  icongood: {
    height: 32,
    width: 32,
  },
  middleicon: {
    height: 33,
    width: 33
  },
  calloutImage: {
    height: height * .15,
    width: width * .25,
    alignSelf: 'center',
    marginTop: 5,
    borderRadius: 3,
    borderWidth: 1,
  },
  wrapper: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  likebutton: {
    marginTop: -10,
    flex: 1,
    height: 32,
    width: 22
  }
});

GoogleMap.propTypes = {
  userData: React.PropTypes.object.isRequired,
  userId: React.PropTypes.string.isRequired
};

export default GoogleMap

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.ec2.model.transform;

import java.util.ArrayList;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * ServiceDetail StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ServiceDetailStaxUnmarshaller implements Unmarshaller<ServiceDetail, StaxUnmarshallerContext> {

    public ServiceDetail unmarshall(StaxUnmarshallerContext context) throws Exception {
        ServiceDetail serviceDetail = new ServiceDetail();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return serviceDetail;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("serviceName", targetDepth)) {
                    serviceDetail.setServiceName(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("serviceId", targetDepth)) {
                    serviceDetail.setServiceId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("serviceType", targetDepth)) {
                    serviceDetail.withServiceType(new ArrayList<ServiceTypeDetail>());
                    continue;
                }

                if (context.testExpression("serviceType/item", targetDepth)) {
                    serviceDetail.withServiceType(ServiceTypeDetailStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("availabilityZoneSet", targetDepth)) {
                    serviceDetail.withAvailabilityZones(new ArrayList<String>());
                    continue;
                }

                if (context.testExpression("availabilityZoneSet/item", targetDepth)) {
                    serviceDetail.withAvailabilityZones(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("owner", targetDepth)) {
                    serviceDetail.setOwner(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("baseEndpointDnsNameSet", targetDepth)) {
                    serviceDetail.withBaseEndpointDnsNames(new ArrayList<String>());
                    continue;
                }

                if (context.testExpression("baseEndpointDnsNameSet/item", targetDepth)) {
                    serviceDetail.withBaseEndpointDnsNames(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("privateDnsName", targetDepth)) {
                    serviceDetail.setPrivateDnsName(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("privateDnsNameSet", targetDepth)) {
                    serviceDetail.withPrivateDnsNames(new ArrayList<PrivateDnsDetails>());
                    continue;
                }

                if (context.testExpression("privateDnsNameSet/item", targetDepth)) {
                    serviceDetail.withPrivateDnsNames(PrivateDnsDetailsStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("vpcEndpointPolicySupported", targetDepth)) {
                    serviceDetail.setVpcEndpointPolicySupported(BooleanStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("acceptanceRequired", targetDepth)) {
                    serviceDetail.setAcceptanceRequired(BooleanStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("managesVpcEndpoints", targetDepth)) {
                    serviceDetail.setManagesVpcEndpoints(BooleanStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("payerResponsibility", targetDepth)) {
                    serviceDetail.setPayerResponsibility(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("tagSet", targetDepth)) {
                    serviceDetail.withTags(new ArrayList<Tag>());
                    continue;
                }

                if (context.testExpression("tagSet/item", targetDepth)) {
                    serviceDetail.withTags(TagStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("privateDnsNameVerificationState", targetDepth)) {
                    serviceDetail.setPrivateDnsNameVerificationState(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("supportedIpAddressTypeSet", targetDepth)) {
                    serviceDetail.withSupportedIpAddressTypes(new ArrayList<String>());
                    continue;
                }

                if (context.testExpression("supportedIpAddressTypeSet/item", targetDepth)) {
                    serviceDetail.withSupportedIpAddressTypes(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return serviceDetail;
                }
            }
        }
    }

    private static ServiceDetailStaxUnmarshaller instance;

    public static ServiceDetailStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new ServiceDetailStaxUnmarshaller();
        return instance;
    }
}


text:
This is a really simple webhook implementation that gets Api.ai classification JSON (i.e. a JSON output of Api.ai /query endpoint) and returns a fulfillment response.

More info about Api.ai webhooks could be found here:
[Api.ai Webhook](https://docs.api.ai/docs/webhook)

# Deploy to:
[![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy)

# What does the service do?
It's a simple echo service that takes `resolvedQuery` and `action` fields from the Api.ai JSON reponse and echoes them back in into `speech` and `displayTest` fields in the fulfillment JSON.


text:
package reconciler

import (
	"testing"

	"github.com/google/go-cmp/cmp"
	"k8s.io/apimachinery/pkg/types"
)

func TestLeaderAwareFuncs(t *testing.T) {
	laf := LeaderAwareFuncs{}
	wantBkt := UniversalBucket()
	wantKey := types.NamespacedName{
		Namespace: "foo",
		Name:      "bar",
	}
	called := false
	wantFunc := func(gotBkt Bucket, gotKey types.NamespacedName) {
		called = true
		if !cmp.Equal(gotKey, wantKey) {
			t.Error("key (-want, +got) =", cmp.Diff(wantKey, gotKey))
		}
		if !cmp.Equal(gotBkt, wantBkt) {
			t.Error("bucket (-want, +got) =", cmp.Diff(wantBkt, gotBkt))
		}
	}

	laf.PromoteFunc = func(bkt Bucket, gotFunc func(Bucket, types.NamespacedName)) error {
		if gotFunc == nil {
			t.Error("PromoteFunc should not be called with nil gotFunc")
			return nil
		}

		gotFunc(bkt, wantKey)
		if !called {
			t.Error("gotFunc didn't call wantFunc!")
		}

		// IsLeaderFor takes the bucket's lock, so make sure that the callback
		// we provide is not called while the lock is still held by calling a
		// function that we know takes the lock.
		if !laf.IsLeaderFor(wantKey) {
			t.Error("IsLeaderFor() = false, wanted true")
		}
		return nil
	}
	laf.DemoteFunc = func(bkt Bucket) {
		// Check that we're not called while the lock is held,
		// and that we are no longer leader.
		if laf.IsLeaderFor(wantKey) {
			t.Error("IsLeaderFor() = true, wanted false")
		}
	}

	// We don't start as leader.
	if laf.IsLeaderFor(wantKey) {
		t.Error("IsLeaderFor() = true, wanted false")
	}

	// After Promote we are leader.
	laf.Promote(wantBkt, wantFunc)
	if !laf.IsLeaderFor(wantKey) {
		t.Error("IsLeaderFor() = false, wanted true")
	}

	// After Demote we are not leader.
	laf.Demote(wantBkt)
	if laf.IsLeaderFor(wantKey) {
		t.Error("IsLeaderFor() = true, wanted false")
	}

	// We should elide calls with a nil enq
	laf.Promote(wantBkt, nil)
}


text:
package custom_metrics

import (
	"github.com/enmasseproject/enmasse/version"
	"github.com/prometheus/client_golang/prometheus"
	"os"
	customMetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
)

// Custom metrics
var (
	versionInfo = prometheus.NewGauge(
		prometheus.GaugeOpts{
			Name:        "version",
			Help:        "Enmasse Operator version and product version",
			ConstLabels: prometheus.Labels{"name": "enmasse-operator", "operator_version": version.Version, "version": os.Getenv("VERSION")},
		},
	)
)

func Init() {
	// Register custom metrics with the global prometheus registry
	customMetrics.Registry.MustRegister(versionInfo)
}


text:
package com.googlecode.wickedcharts.highcharts.options;

import com.googlecode.wickedcharts.highcharts.json.LowercaseEnum;

/**
 * Defines the type of an axis.
 *
 * @see <a
 *      href="http://api.highcharts.com/highcharts#Axis.type">http://api.highcharts.com/highcharts#Axis.type</a>
 * @author Tom Hombergs (tom.hombergs@gmail.com)
 *
 */
public enum AxisType implements LowercaseEnum {

	LINEAR,

	DATETIME,

	LOGARITHMIC;

}


text:
import type {ComponentStory, ComponentMeta} from '@storybook/react';
import type {BarsProps} from './Bars';

import React from 'react';

import {Chart} from './Chart';
import {Bars} from './Bars';
import {Transform} from './Transform';

export default {
    title: 'Components/Graphics/Bars',
    component: Bars
} as ComponentMeta<typeof Bars>;

const series1 = [{
    data: [1, 2, 4]
}];

const series2 = [{
    data: [1, 2, 3]
}, {
    data: [5, 7, 11]
}, {
    data: [13, 17, 19]
}];

const series3 = [{
    data: [1, 2, 3]
}, {
    data: [5, {y: 7, color: 'violet'}, 11]
}, {
    data: [13, 17, 19]
}];

const Template: ComponentStory<typeof Bars> = (args) => <Chart width={600} height={300}>
    <Bars {...args} />
</Chart>;

export const Story1 = Template.bind({});
Story1.storyName = 'default';
Story1.args = {
    series: series1,
    minY: 0
};

export const Story2 = Template.bind({});
Story2.storyName = 'three series';
Story2.args = {
    series: series2,
    minY: 0
};

export const Story3 = Template.bind({});
Story3.storyName = 'without minY';
Story3.args = {
    series: series2
};

export const Story4 = Template.bind({});
Story4.storyName = 'bar styles and mouse events';
Story4.args = {
    series: series2,
    minY: 0,
    groupPadding: '3%',
    innerPadding: '0.5%',
    barAttributes: {
        onMouseMove: e => e.target.style.fillOpacity = 1,
        onMouseLeave: e => e.target.style.fillOpacity = 0.25
    },
    barStyle: {
        fillOpacity: 0.25,
        transition: 'all 250ms'
    }
};
Story4.parameters = {
    playroom: {
        code: `
<Chart
  layerWidth={600}
  layerHeight={300}
  series={${JSON.stringify(series2)}}
  minY={0}
>
  <Bars
    groupPadding="3%"
    innerPadding="0.5%"
    barAttributes={{
      onMouseMove: e => e.target.style.fillOpacity = 1,
      onMouseLeave: e => e.target.style.fillOpacity = 0.25
    }}
    barStyle={{
      fillOpacity: 0.25,
      transition: 'all 250ms'
    }}
  />
</Chart>
`.trim()
    }
};

export const Story5 = Template.bind({});
Story5.storyName = 'colors';
Story5.args = {
    series: series3,
    minY: 0,
    colors: 'category10',
    innerPadding: '0.5%',
    groupPadding: '3%'
};

export const Story6: ComponentStory<typeof Bars> = ({series, ...args}: BarsProps) => (
    <Chart width={600} height={300} series={series}>
        <Transform method='stack'>
            <Bars {...args} />
        </Transform>
    </Chart>
);
Story6.storyName = 'stacked';
Story6.args = {
    series: series2,
    combined: true,
    innerPadding: '2%'
};

export const Story7: ComponentStory<typeof Bars> = ({series, ...args}: BarsProps) => (
    <Chart width={600} height={300} series={series}>
        <Transform method='stack'>
            <Bars {...args} />
        </Transform>
    </Chart>
);
Story7.storyName = 'stacked and not-combined';
Story7.args = {
    series: series2,
    innerPadding: '2%'
};

export const Story8: ComponentStory<typeof Bars> = ({series, ...args}: BarsProps) => (
    <Chart width={600} height={300} series={series}>
        <Transform method={['stack', 'rotate']}>
            <Bars {...args} />
        </Transform>
    </Chart>
);
Story8.storyName = 'horizontal stacked';
Story8.args = {
    series: series2,
    combined: true,
    innerPadding: '2%'
};


text:
require 'wavefile'
require 'numru/fftw3'

module MusicDetector
  class FeatureVectorExtractor

    attr_reader :config

    # @param [MusicDetector::Configuration] config config to process music file
    def initialize(config)
      @config = config
    end

    # @param [String] file      path of the input audio file
    # @param [Float]  seektime  seek time in the audio file (in seconds)
    # @param [Float]  duration  duration in the audio file (in seconds)
    # @return [NArray<Float>]   extracted feature vector
    def extract_from(file:, seektime:, duration:)
      # read audio file
      wave, samplerate = read_audio_file(file: file, seektime: seektime, duration: duration)

      # do fft and make frequency spectrum
      length      = wave.length / 2
      spectrum    = NumRu::FFTW3.fft(wave, NumRu::FFTW3::FORWARD).abs[0...length]
      frequencies = NArray.to_na((0...length).map { |i| i.to_f / length * samplerate / 2 }) # frequencies of each element in spectrum

      # bandpath filter (to faster computation)
      spectrum, frequencies = band_path_filter(spectrum: spectrum, frequencies: frequencies)

      # prepare for analysis
      log_frequencies = NMath::log(frequencies)
      log_temperament = NMath::log(equal_temperament)

      log_bin_freq_half_bandwidth    = (log_temperament[1] - log_temperament[0]) / 2.0
      log_in_tune_freq_threshold     = log_bin_freq_half_bandwidth * @config.in_tune_cents / 100.0
      log_out_of_tune_freq_threshold = log_bin_freq_half_bandwidth * @config.out_of_tune_cents / 100.0

      log_temperament.map do |log_bin_center_freq|
        # indices of the target bin (for spectrum)
        log_bin_indices = (log_frequencies - log_bin_center_freq).abs < log_bin_freq_half_bandwidth

        # extract the target bin
        target_log_frequencies = log_frequencies[log_bin_indices]
        target_spectrum        = spectrum[log_bin_indices]

        # calc ratio between in-tune and out-of-tune powers
        target_in_tune_indices     = (target_log_frequencies - log_bin_center_freq).abs <= log_in_tune_freq_threshold
        target_out_of_tune_indices = (target_log_frequencies - log_bin_center_freq).abs >  log_out_of_tune_freq_threshold

        in_tune_power     = target_spectrum[target_in_tune_indices].mean
        out_of_tune_power = target_spectrum[target_out_of_tune_indices].mean

        in_tune_power / out_of_tune_power
      end.sort.reverse
    end

    private

    def read_audio_file(file:, seektime:, duration:)
      mono_wave = nil
      samplerate = nil

      WaveFile::Reader.new(file) do |sound|
        samplerate = sound.format.sample_rate
        channels = sound.format.channels

        # seek
        sound.read((seektime * samplerate).round)

        # read
        sample_count = (duration * samplerate).round
        mono_wave = NArray.sint(sample_count)

        sound.read(sample_count).samples.each.with_index do |sample, i|
          case sample
          when Array
            mono_wave[i] = sample.inject(&:+) / channels # normalize to monoral
            mono_wave[i] *= (2 ** (bits_per_sample - 1)) if Float === sample.first
          when Fixnum
            mono_wave[i] = sample
          when Float
            mono_wave[i] = sample * (2 ** (bits_per_sample - 1))
          else
            raise StandardError("unsupported file: #{file}")
          end
        end
      end

      [mono_wave, samplerate]
    end

    def band_path_filter(spectrum:, frequencies:)
      hpf_freq = @config.a * 2 ** ((@config.temperament_range.first - 1) / 12.0)
      lpf_freq = @config.a * 2 ** ((@config.temperament_range.last + 1) / 12.0)

      bpf_indices = (hpf_freq < frequencies) * (frequencies < lpf_freq)
      spectrum    = spectrum[bpf_indices]
      frequencies = frequencies[bpf_indices]
      [spectrum, frequencies]
    end

    def equal_temperament
      NArray.to_na(@config.temperament_range.map { |i| @config.a * 2 ** (i / 12.0) })
    end
  end
end


text:
package com.dwarfholm.activitystats.braizhauler;

import java.util.HashMap;

import org.bukkit.entity.Player;

public class ASData {
	private HashMap <String, ASPlayer> playerlist;
	private ASDatabase database;
	private ActivityStats plugin;

	public ASData(ActivityStats plugin)	{
		this.plugin = plugin;
		playerlist = new HashMap<String, ASPlayer>();
		database = new ASDatabase(plugin);
	}

	public void createDatabase() {
		database.createTables();
	}

	public void recordOnline() {
		if (playerlist!=null && !playerlist.isEmpty())	{
			for (ASPlayer player:playerlist.values())	{
				if ( plugin.getServer().getPlayer(player.getName()) != null)	{
					player.curPeriod.addOnline();
					plugin.info(player.getName() + " Online");
				}
			}
		}
	}

	public void checkRollovers() {
		if( plugin.PeriodRolloverDue())	{
			for (String sPlayer:playerlist.keySet())	{
				plugin.info("paying " + sPlayer);
				plugin.payPlayer(playerlist.get(sPlayer));
			}

			if( plugin.DayRolloverDue() || plugin.WeekRolloverDue() || plugin.MonthRolloverDue() )	{
				saveAll();
				if ( plugin.DayRolloverDue() )
					database.rolloverDay();
				if ( plugin.WeekRolloverDue() )
					database.rolloverWeek();
				if ( plugin.MonthRolloverDue() )
					database.rolloverMonth();
				loadOnlinePlayers();
			}
			rolloverPeriod();
			saveAll();
			Player pPlayer;
			for (ASPlayer player:playerlist.values())	{
				pPlayer = plugin.getServer().getPlayer(player.getName());
				if ( pPlayer == null )	{
					plugin.info("removing " + player.getName());
					playerlist.remove(player.getName());
				} else
					plugin.autoPromoterCheck(pPlayer);
			}

		}
	}

	public void loadPlayer(String player)	{
		database.loadPlayer(player);
	}

	public void savePlayer(String name) {
		savePlayer(playerlist.get(name));
	}

	public void savePlayer(ASPlayer player) {
		database.updatePlayer(player);
	}

	public void setPlayer(ASPlayer player)	{
		playerlist.put(player.getName(), player);
	}

	public ASPlayer getPlayer(String name)	{
		return playerlist.get(name);
	}

	public void rolloverPeriod()	{
		for(String player: playerlist.keySet())	{
			playerlist.get(player).rolloverPeriod();
		}
		plugin.rolledoverPeriod();
	}

	public void loadOnlinePlayers() {
		for (Player player: plugin.getServer().getOnlinePlayers() )
			loadPlayer(player.getName());
	}
	public void saveAll()	{
		for (ASPlayer player:playerlist.values())
			database.updatePlayer(player);
	}

	public void fetchRemotePlayerlist() {
		database.fetchRemotePlayerList();
	}
}


text:
from __future__ import absolute_import
import math

from st2common.runners.base_action import Action
from six.moves import range

class PascalRowAction(Action):
    def run(self, **kwargs):
        # We call list values to verify that log messages are not duplicated when
        # datastore service is used
        try:
            self.action_service.list_values()
        except Exception:
            pass

        self.logger.info("test info log message")
        self.logger.debug("test debug log message")
        self.logger.error("test error log message")
        return PascalRowAction._compute_pascal_row(**kwargs)

    @staticmethod
    def _compute_pascal_row(row_index=0):
        print("Pascal row action")

        if row_index == "a":
            return False, "This is suppose to fail don't worry!!"
        elif row_index == "b":
            return None
        elif row_index == "complex_type":
            result = PascalRowAction()
            return (False, result)
        elif row_index == "c":
            return False, None
        elif row_index == "d":
            return "succeeded", [1, 2, 3, 4]
        elif row_index == "e":
            return [1, 2]
        elif row_index == 5:
            return [
                math.factorial(row_index)
                / (math.factorial(i) * math.factorial(row_index - i))
                for i in range(row_index + 1)
            ]
        elif row_index == "f":
            raise ValueError("Duplicate traceback test")
        else:
            return True, [
                math.factorial(row_index)
                / (math.factorial(i) * math.factorial(row_index - i))
                for i in range(row_index + 1)
            ]


text:
import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import css from './input.module.scss';

function Input({type='text', value, className, onChange, onFocus, onBlur, placeholder, readonly} = {}, ref) {
    return (
        <input
            className={cn(css.el, className)}
            type={type}
            onChange={onChange}
            onFocus={onFocus}
            onBlur={onBlur}
            ref={ref}
            value={value}
            readOnly={readonly}
            placeholder={placeholder}
        />
    );
}

Input.propTypes = {
    type: PropTypes.string,
    className: PropTypes.string,
    onChange: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    placeholder: PropTypes.string,
    value: PropTypes.string,
    readonly: PropTypes.bool,
};

export default React.forwardRef(Input);


text:
/**
 * This is a generated file. Do not edit or your changes will be lost
 */

@interface EduRutgersModuleModuleAssets : NSObject
{
}
- (NSData*) moduleAsset;
- (NSData*) resolveModuleAsset:(NSString*)path;

@end


text:
(function () {
    angular.module('hcare').component('patientList', {
        templateUrl: 'main/components/electronic-patient-record/patient-list/patient-list.html',
        controller: PatientListController
    });

    var Patient = models.Patient;
    PatientListController.$inject = ['$uibModal', 'DataService', 'toaster'];

    function PatientListController($uibModal, DataService, toaster) {
        var ctrl = this;

        /**
         * Model
         */
        ctrl.patients = [];
        ctrl.currentPatient = new Patient();
        ctrl.DataService = DataService;
        ctrl.toaster = toaster;

        ctrl.openAddPatientModal = openAddPatientModal;
        ctrl.getData = getData;

        /**
         * To manage the tab selection
         */
        ctrl.selected = false;

        ctrl.$onInit = getData;

        function getData() {
            DataService.getPatientRecords()
                .then(function (response) {
                    if (response.status == '200') {
                        ctrl.patients = response.data.payload.map(function (patient) {
                            patient.DateOfBirth = new Date(patient.DateOfBirth);
                            return patient
                        })
                    } else {
                        displayError()
                    }
                })
                .catch(function (error) {
                    displayError()
                })
        }

        function openAddPatientModal(resolve) {
            console.log(resolve);
            var addPatientModalInstance = $uibModal.open({
                templateUrl: 'main/components/electronic-patient-record/patient-list/add-patient-modal.html',
                controller: 'addPatientModalController',
                controllerAs: '$ctrl',
                resolve: {
                    patient: function () {
                        return resolve;
                    }
                }
            });

            addPatientModalInstance.result.then(function (patient, editing) {
                ctrl.getData();
                var message = "You successfully ";
                message += editing ? 'edited' : 'added';
                message += ' a patient';
                ctrl.toaster.success(message)
            }, function () {
                //modal dismissed
            });
        }

        //Private methods
        function displayError(message) {
            var msg = 'There was an error!';
            if (message) {msg += '\n Message: ' + message}
            toaster.error(msg)
        }
    }

})();


text:
#ifndef TUPTABLE_H
#define TUPTABLE_H

#include "access/htup.h"
#include "access/tupdesc.h"
#include "storage/buf.h"

/*----------
 * The executor stores tuples in a "tuple table" which is a List of
 * independent TupleTableSlots.  There are several cases we need to handle:
 *		1. physical tuple in a disk buffer page
 *		2. physical tuple constructed in palloc'ed memory
 *		3. "minimal" physical tuple constructed in palloc'ed memory
 *		4. "virtual" tuple consisting of Datum/isnull arrays
 *
 * The first two cases are similar in that they both deal with "materialized"
 * tuples, but resource management is different.  For a tuple in a disk page
 * we need to hold a pin on the buffer until the TupleTableSlot's reference
 * to the tuple is dropped; while for a palloc'd tuple we usually want the
 * tuple pfree'd when the TupleTableSlot's reference is dropped.
 *
 * A "minimal" tuple is handled similarly to a palloc'd regular tuple.
 * At present, minimal tuples never are stored in buffers, so there is no
 * parallel to case 1.  Note that a minimal tuple has no "system columns".
 * (Actually, it could have an OID, but we have no need to access the OID.)
 *
 * A "virtual" tuple is an optimization used to minimize physical data
 * copying in a nest of plan nodes.  Any pass-by-reference Datums in the
 * tuple point to storage that is not directly associated with the
 * TupleTableSlot; generally they will point to part of a tuple stored in
 * a lower plan node's output TupleTableSlot, or to a function result
 * constructed in a plan node's per-tuple econtext.  It is the responsibility
 * of the generating plan node to be sure these resources are not released
 * for as long as the virtual tuple needs to be valid.  We only use virtual
 * tuples in the result slots of plan nodes --- tuples to be copied anywhere
 * else need to be "materialized" into physical tuples.  Note also that a
 * virtual tuple does not have any "system columns".
 *
 * It is also possible for a TupleTableSlot to hold both physical and minimal
 * copies of a tuple.  This is done when the slot is requested to provide
 * the format other than the one it currently holds.  (Originally we attempted
 * to handle such requests by replacing one format with the other, but that
 * had the fatal defect of invalidating any pass-by-reference Datums pointing
 * into the existing slot contents.)  Both copies must contain identical data
 * payloads when this is the case.
 *
 * The Datum/isnull arrays of a TupleTableSlot serve double duty.  When the
 * slot contains a virtual tuple, they are the authoritative data.  When the
 * slot contains a physical tuple, the arrays contain data extracted from
 * the tuple.  (In this state, any pass-by-reference Datums point into
 * the physical tuple.)  The extracted information is built "lazily",
 * ie, only as needed.  This serves to avoid repeated extraction of data
 * from the physical tuple.
 *
 * A TupleTableSlot can also be "empty", holding no valid data.  This is
 * the only valid state for a freshly-created slot that has not yet had a
 * tuple descriptor assigned to it.  In this state, tts_isempty must be
 * TRUE, tts_shouldFree FALSE, tts_tuple NULL, tts_buffer InvalidBuffer,
 * and tts_nvalid zero.
 *
 * The tupleDescriptor is simply referenced, not copied, by the TupleTableSlot
 * code.  The caller of ExecSetSlotDescriptor() is responsible for providing
 * a descriptor that will live as long as the slot does.  (Typically, both
 * slots and descriptors are in per-query memory and are freed by memory
 * context deallocation at query end; so it's not worth providing any extra
 * mechanism to do more.  However, the slot will increment the tupdesc
 * reference count if a reference-counted tupdesc is supplied.)
 *
 * When tts_shouldFree is true, the physical tuple is "owned" by the slot
 * and should be freed when the slot's reference to the tuple is dropped.
 *
 * If tts_buffer is not InvalidBuffer, then the slot is holding a pin
 * on the indicated buffer page; drop the pin when we release the
 * slot's reference to that buffer.  (tts_shouldFree should always be
 * false in such a case, since presumably tts_tuple is pointing at the
 * buffer page.)
 *
 * tts_nvalid indicates the number of valid columns in the tts_values/isnull
 * arrays.  When the slot is holding a "virtual" tuple this must be equal
 * to the descriptor's natts.  When the slot is holding a physical tuple
 * this is equal to the number of columns we have extracted (we always
 * extract columns from left to right, so there are no holes).
 *
 * tts_values/tts_isnull are allocated when a descriptor is assigned to the
 * slot; they are of length equal to the descriptor's natts.
 *
 * tts_mintuple must always be NULL if the slot does not hold a "minimal"
 * tuple.  When it does, tts_mintuple points to the actual MinimalTupleData
 * object (the thing to be pfree'd if tts_shouldFreeMin is true).  If the slot
 * has only a minimal and not also a regular physical tuple, then tts_tuple
 * points at tts_minhdr and the fields of that struct are set correctly
 * for access to the minimal tuple; in particular, tts_minhdr.t_data points
 * MINIMAL_TUPLE_OFFSET bytes before tts_mintuple.  This allows column
 * extraction to treat the case identically to regular physical tuples.
 *
 * tts_slow/tts_off are saved state for slot_deform_tuple, and should not
 * be touched by any other code.
 *----------
 */
typedef struct TupleTableSlot
{
	NodeTag		type;
	bool		tts_isempty;	/* true = slot is empty */
	bool		tts_shouldFree; /* should pfree tts_tuple? */
	bool		tts_shouldFreeMin;		/* should pfree tts_mintuple? */
	bool		tts_slow;		/* saved state for slot_deform_tuple */
	HeapTuple	tts_tuple;		/* physical tuple, or NULL if virtual */
	TupleDesc	tts_tupleDescriptor;	/* slot's tuple descriptor */
	MemoryContext tts_mcxt;		/* slot itself is in this context */
	Buffer		tts_buffer;		/* tuple's buffer, or InvalidBuffer */
	int			tts_nvalid;		/* # of valid values in tts_values */
	Datum	   *tts_values;		/* current per-attribute values */
	bool	   *tts_isnull;		/* current per-attribute isnull flags */
	MinimalTuple tts_mintuple;	/* minimal tuple, or NULL if none */
	HeapTupleData tts_minhdr;	/* workspace for minimal-tuple-only case */
	long		tts_off;		/* saved state for slot_deform_tuple */
} TupleTableSlot;

#define TTS_HAS_PHYSICAL_TUPLE(slot)  \
	((slot)->tts_tuple != NULL && (slot)->tts_tuple != &((slot)->tts_minhdr))

/*
 * TupIsNull -- is a TupleTableSlot empty?
 */
#define TupIsNull(slot) \
	((slot) == NULL || (slot)->tts_isempty)

/* in executor/execTuples.c */
extern TupleTableSlot *MakeTupleTableSlot(void);
extern TupleTableSlot *ExecAllocTableSlot(List **tupleTable);
extern void ExecResetTupleTable(List *tupleTable, bool shouldFree);
extern TupleTableSlot *MakeSingleTupleTableSlot(TupleDesc tupdesc);
extern void ExecDropSingleTupleTableSlot(TupleTableSlot *slot);
extern void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc);
extern TupleTableSlot *ExecStoreTuple(HeapTuple tuple,
			   TupleTableSlot *slot,
			   Buffer buffer,
			   bool shouldFree);
extern TupleTableSlot *ExecStoreMinimalTuple(MinimalTuple mtup,
					  TupleTableSlot *slot,
					  bool shouldFree);
extern TupleTableSlot *ExecClearTuple(TupleTableSlot *slot);
extern TupleTableSlot *ExecStoreVirtualTuple(TupleTableSlot *slot);
extern TupleTableSlot *ExecStoreAllNullTuple(TupleTableSlot *slot);
extern HeapTuple ExecCopySlotTuple(TupleTableSlot *slot);
extern MinimalTuple ExecCopySlotMinimalTuple(TupleTableSlot *slot);
extern HeapTuple ExecFetchSlotTuple(TupleTableSlot *slot);
extern MinimalTuple ExecFetchSlotMinimalTuple(TupleTableSlot *slot);
extern Datum ExecFetchSlotTupleDatum(TupleTableSlot *slot);
extern HeapTuple ExecMaterializeSlot(TupleTableSlot *slot);
extern TupleTableSlot *ExecCopySlot(TupleTableSlot *dstslot,
			 TupleTableSlot *srcslot);

/* in access/common/heaptuple.c */
extern Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull);
extern void slot_getallattrs(TupleTableSlot *slot);
extern void slot_getsomeattrs(TupleTableSlot *slot, int attnum);
extern bool slot_attisnull(TupleTableSlot *slot, int attnum);

#endif   /* TUPTABLE_H */


text:
var group__usb__interface__gr =
[
    [ "USB Device Interface", "group__usbd__interface__gr.html", "group__usbd__interface__gr" ],
    [ "USB Host Interface", "group__usbh__interface__gr.html", "group__usbh__interface__gr" ],
    [ "USB Speed", "group___u_s_b__speed.html", "group___u_s_b__speed" ],
    [ "USB Endpoint Type", "group___u_s_b__endpoint__type.html", "group___u_s_b__endpoint__type" ]
];


text:
import ROOT
import sys

from math import *
from array import *

filename = "/Users/musthero/Documents/Yura/Applications/TMVA-v4.2.0/test/output_electrons_v2_25per.root"

profile = ROOT.TProfile("RECTCuts", "RECTCuts", 100, 0, 1, "s");

# Get TTree
file = ROOT.TFile.Open(filename)
tree = file.JINRTree2_el2

# Declare variables of interest
m_el_pass_Loose_Triggers = array('i', [0])
m_el_pt = array('f',[0])
m_el_eta = array('f',[0])
m_el_sigd0PV = array('f',[0])
m_el_z0SinTheta = array('f',[0])
m_el_topoetcone20_pt = array('f',[0])
m_el_ptvarcone20_pt = array('f',[0])
m_el_isTightLH = array('i',[0])
m_el_truthOrigin = array('i', [0])
m_el_isolationFixedCutTight = array('i', [0])

# Training

# Link variables of interest to the tree
tree.SetBranchAddress( "m_el_pt", m_el_pt )
tree.SetBranchAddress( "m_el_eta", m_el_eta )
tree.SetBranchAddress( "m_el_sigd0PV", m_el_sigd0PV )
tree.SetBranchAddress( "m_el_z0SinTheta", m_el_z0SinTheta )
tree.SetBranchAddress( "m_el_topoetcone20_pt", m_el_topoetcone20_pt )
tree.SetBranchAddress( "m_el_ptvarcone20_pt", m_el_ptvarcone20_pt )
tree.SetBranchAddress( "m_el_isTightLH", m_el_isTightLH )
tree.SetBranchAddress( "m_el_truthOrigin", m_el_truthOrigin )
tree.SetBranchAddress( "m_el_pass_Loose_Triggers", m_el_pass_Loose_Triggers )
tree.SetBranchAddress( "m_el_isolationFixedCutTight", m_el_isolationFixedCutTight )

# Declare counting variables
prompt_all = 0; prompt_pass = 0;
nonprompt_all = 0; nonprompt_pass = 0; nonprompt_rej = 0;

c = 0
#for e in file.JINRTree:
while tree.GetEntry(c):
    c = c + 1

    if (c % 100000 == 0):
        print "Event number %i" % c
        sys.stdout.flush()

    if not (m_el_isTightLH[0]==1 and m_el_pass_Loose_Triggers[0]==1):
        continue

    isprompt = 1 if m_el_truthOrigin[0] in (12, ) else 0
    # if m_el_truthOrigin[0] in (12, ):    # WBoson        = 12
    #    isprompt = 1
    # elif m_el_truthOrigin[0] in (26, ):  # BottomMeson   = 26
    #    isprompt = 0
    # else:
    #    isprompt = -1
    # if isprompt < 0: continue

    prompt_all += 1 if isprompt == 1 else 0
    nonprompt_all += 1 if isprompt == 0 else 0

    # Apply standard cuts
    if m_el_z0SinTheta[0] < 0.5 and m_el_sigd0PV[0] < 5 and m_el_isolationFixedCutTight[0] == 1:
        prompt_pass += 1 if isprompt == 1 else 0
        nonprompt_pass += 1 if isprompt == 0 else 0

    #print "Unable to figure out lepton type (prompt/non-prompt)"
    #ROOT.gApplication.Terminate()

nonprompt_rej = nonprompt_all - nonprompt_pass
sig_eff_val = float(prompt_pass)/prompt_all
sig_eff_err = (1/float(prompt_all))*sqrt(prompt_pass*(1-float(prompt_pass)/prompt_all))
bkg_rej_val = float(nonprompt_rej)/nonprompt_all
bkg_rej_err = (1/float(nonprompt_all))*sqrt(nonprompt_rej*(1-float(nonprompt_rej)/nonprompt_all))

print filename,":"
print "    Sig eff:", sig_eff_val
print "    Sig eff error:", sig_eff_err
print "    Bkg rej:", bkg_rej_val
print "    Bkg rej error:", bkg_rej_err
print "    Prompt all,pass:", prompt_all,prompt_pass
print "    Non-prompt all,rej:", nonprompt_all,nonprompt_rej

print "(%f,%f,%f,%f)" % (sig_eff_val, bkg_rej_val, sig_eff_err, bkg_rej_err)

profile.Fill(sig_eff_val, bkg_rej_val, 1)
file.Close()

profile.SetLineColor(2)
profile.SetLineWidth(6)
profile.Draw()


text:
namespace mana {

class Attribute;
using Attribute_ptr = std::shared_ptr<Attribute>;
using AttrType = size_t;

class Attribute {

public:
  template <typename A>
  static AttrType type();

  virtual ~Attribute() {}

private:
  static AttrType next_attr_type() {
    static AttrType counter;
    return ++counter;
  }
};

template <typename A>
AttrType Attribute::type() {
  static_assert(std::is_base_of<Attribute, A>::value, "A is not an Attribute");
  static AttrType id = Attribute::next_attr_type();
  return id;
}

}; // < namespace mana

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<root>
	<Account>
		<CustomerName>John Doe</CustomerName>
		<BusinessEntityName>John Doe</BusinessEntityName>
		<Customer_Category_Reference_Type>Customer_Category_ID
		</Customer_Category_Reference_Type>
		<Customer_Category_Reference_Value>CUSTOMER_CATEGORY-5
		</Customer_Category_Reference_Value>
		<Customer_Status_Reference_Type>Business_Entity_Status_Value_ID
		</Customer_Status_Reference_Type>
		<Customer_Status_Reference_Value>ACTIVE
		</Customer_Status_Reference_Value>
	</Account>
</root>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Login</title>

        <link rel="stylesheet" href="css/login.css">

      <form action="" method="post" class="form form--login">

          Username
          <input id="login__username" type="text" class="form__input" placeholder="Username" required>

          Password
          <input id="login__password" type="password" class="form__input" placeholder="Password" required>

          <input type="submit" value="Sign In">

      </form>

Not a member? Sign up now


text:
Munch
=====

A experimental dependency-based task manager.

To run munch, type *sbt run*

To run the unit tests, type *sbt test*

To package in uberjar, type *sbt assembly*

TODO
====

* move "checklist" package to "munch"
* support tasks with only dependencies (like default)
* update JavacPlugin to not require a temp directory


text:
class AddsZoneCreatedAtToProjectContributiosnEndpoint < ActiveRecord::Migration
 def up
    execute <<-SQL
CREATE OR REPLACE VIEW "1".project_contributions AS
 SELECT c.anonymous,
    c.project_id,
    c.id,
    public.thumbnail_image(u.*) AS profile_img_thumbnail,
    u.id AS user_id,
    u.name AS user_name,
        CASE
            WHEN public.is_owner_or_admin(p.user_id) THEN c.value
            ELSE NULL::numeric
        END AS value,
    public.waiting_payment(pa.*) AS waiting_payment,
    public.is_owner_or_admin(p.user_id) AS is_owner_or_admin,
    ut.total_contributed_projects,
    public.zone_timestamp(c.created_at) AS created_at
   FROM ((((public.contributions c
     JOIN public.users u ON ((c.user_id = u.id)))
     JOIN public.projects p ON ((p.id = c.project_id)))
     JOIN public.payments pa ON ((pa.contribution_id = c.id)))
     LEFT JOIN "1".user_totals ut ON ((ut.user_id = u.id)))
  WHERE ((public.was_confirmed(c.*) OR public.waiting_payment(pa.*)) AND ((NOT c.anonymous) OR public.is_owner_or_admin(p.user_id)));
    SQL
  end

  def down
    execute <<-SQL
CREATE OR REPLACE VIEW "1".project_contributions AS
 SELECT c.anonymous,
    c.project_id,
    c.id,
    public.thumbnail_image(u.*) AS profile_img_thumbnail,
    u.id AS user_id,
    u.name AS user_name,
        CASE
            WHEN public.is_owner_or_admin(p.user_id) THEN c.value
            ELSE NULL::numeric
        END AS value,
    public.waiting_payment(pa.*) AS waiting_payment,
    public.is_owner_or_admin(p.user_id) AS is_owner_or_admin,
    ut.total_contributed_projects,
    c.created_at
   FROM ((((public.contributions c
     JOIN public.users u ON ((c.user_id = u.id)))
     JOIN public.projects p ON ((p.id = c.project_id)))
     JOIN public.payments pa ON ((pa.contribution_id = c.id)))
     LEFT JOIN "1".user_totals ut ON ((ut.user_id = u.id)))
  WHERE ((public.was_confirmed(c.*) OR public.waiting_payment(pa.*)) AND ((NOT c.anonymous) OR public.is_owner_or_admin(p.user_id)));
    SQL
  end
end


text:
package gw.internal.gosu.ir.compiler.bytecode.expression;

import gw.internal.gosu.ir.compiler.bytecode.AbstractBytecodeCompiler;
import gw.internal.gosu.ir.compiler.bytecode.IRBytecodeContext;
import gw.internal.gosu.ir.compiler.bytecode.IRBytecodeCompiler;
import gw.lang.ir.expression.IRNewExpression;
import gw.lang.ir.IRType;
import gw.lang.ir.IRExpression;
import gw.lang.ir.IRTypeConstants;
import gw.internal.ext.org.objectweb.asm.Opcodes;
import gw.internal.ext.org.objectweb.asm.MethodVisitor;

public class IRNewExpressionCompiler extends AbstractBytecodeCompiler {

  public static void compile( IRNewExpression expression, IRBytecodeContext context ) {
    MethodVisitor mv = context.getMv();
    mv.visitTypeInsn( Opcodes.NEW, expression.getOwnersType().getSlashName() );
    mv.visitInsn( Opcodes.DUP );

    for (IRExpression arg : expression.getArgs()) {
      IRBytecodeCompiler.compileIRExpression( arg, context );
    }

    StringBuilder descriptor = new StringBuilder();
    descriptor.append("(");
    for (IRType param : expression.getParameterTypes()) {
      descriptor.append(param.getDescriptor());
    }
    descriptor.append(")");
    descriptor.append(IRTypeConstants.pVOID().getDescriptor());

    mv.visitMethodInsn( Opcodes.INVOKESPECIAL,
                        expression.getOwnersType().getSlashName(),
                        "<init>",
                        descriptor.toString() );
  }
}


text:
goog.provide('weapi.CameraAnimator');

goog.require('goog.events');
goog.require('goog.fx.Animation');
goog.require('goog.fx.Animation.EventType');
goog.require('goog.fx.AnimationSerialQueue');
goog.require('goog.fx.Transition.EventType');
goog.require('goog.math');

goog.require('weapi.utils');

/**
 * @param {!weapi.Camera} camera Camera to be animated by this object.
 * @constructor
 */
weapi.CameraAnimator = function(camera) {

  /**
   * @type {!weapi.Camera}
   * @private
   */
  this.camera_ = camera;

  /**
   * @type {goog.fx.AnimationSerialQueue}
   * @private
   */
  this.animation_ = null;
};

/**
 * @define {number} Animation duration in seconds.
 */
weapi.CameraAnimator.CAMERA_ANIMATION_DURATION = 3;

/**
 * @define {number} How much can the camera climb (or descent)
 *                  (in meters of altitude per meters of surface distance).
 */
weapi.CameraAnimator.CAMERA_ANIMATION_MAX_ASCENT = 0.2;

/**
 * TODO: use CameraFlightPath ?
 * Initiate and start the animation to given location.
 * @param {number} latitude Latitude in radians.
 * @param {number} longitude Longitude in radians.
 * @param {number=} opt_altitude Altitude (otherwise unchanged).
 * @param {number=} opt_heading Heading (otherwise 0).
 * @param {number=} opt_tilt Tilt (otherwise 0).
 * @param {boolean=} opt_targetPosition If true, the camera is position in
 *                                      such a way, that the camera target is
 *                                      [latitude, longitude] (default false).
 * @param {number=} opt_duration Duration of the animation in seconds.
 */
weapi.CameraAnimator.prototype.flyTo = function(latitude, longitude,
                                                opt_altitude,
                                                opt_heading, opt_tilt,
                                                opt_targetPosition,
                                                opt_duration) {
  var cam = this.camera_;

  if (opt_targetPosition) {
    var newPos = weapi.Camera.calculatePositionForGivenTarget(
        latitude, longitude, opt_altitude || cam.getPos()[2],
        opt_heading, opt_tilt);

    latitude = newPos[0];
    longitude = newPos[1];
  }

  if (goog.isDefAndNotNull(this.animation_)) {
    this.onEnd_();
  }

  var srcPos = cam.getPos();
  var curAlt = srcPos[2];
  var dstAlt = opt_altitude || curAlt;

  // Validates start and end location so that
  // the animation goes through the shortest path.
  var lonStart = goog.math.modulo(srcPos[1], 2 * Math.PI);
  var lonEnd = goog.math.modulo(longitude, 2 * Math.PI);

  var lonDiff = lonStart - lonEnd;
  if (lonDiff < -Math.PI) {
    lonStart += 2 * Math.PI;
  } else if (lonDiff > Math.PI) {
    lonEnd += 2 * Math.PI;
  }

  var start_ = [srcPos[0], lonStart, curAlt, cam.getHeading(), cam.getTilt()];
  var end_ = [latitude, lonEnd, dstAlt, opt_heading || 0, opt_tilt || 0];

  //in-out quintic
  var supereasing = function(t) {
    var t2 = t * t;
    var t3 = t * t * t;
    return 6 * t3 * t2 + -15 * t2 * t2 + 10 * t3;
  };
  var supereasing_f = function(t) {return 2 * supereasing(t / 2);};
  var halfVal = supereasing(0.5);
  var supereasing_l = function(t) {
    return (supereasing(0.5 + t / 2) - halfVal) / (1 - halfVal);
  };

  var animationAlteringEvents = [goog.fx.Transition.EventType.BEGIN,
                                 goog.fx.Animation.EventType.ANIMATE,
                                 goog.fx.Transition.EventType.END,
                                 goog.fx.Transition.EventType.FINISH];

  this.animation_ = new goog.fx.AnimationSerialQueue();

  var duration =
      1000 * (opt_duration || weapi.CameraAnimator.CAMERA_ANIMATION_DURATION);

  if (opt_altitude) {
    var distance = weapi.utils.calculateDistance(srcPos[0], srcPos[1],
                                                 latitude, longitude);

    var topPoint = Math.min(curAlt, dstAlt) +
                   distance * weapi.CameraAnimator.CAMERA_ANIMATION_MAX_ASCENT;

    //Don't allow the topPoint to be lower than highest of the two points
    if (topPoint < Math.max(curAlt, dstAlt)) {
      topPoint = (curAlt + dstAlt) / 2;
    }

    var top = [];
    top[0] = (start_[0] + end_[0]) / 2;
    top[1] = (start_[1] + end_[1]) / 2;
    top[2] = topPoint;
    top[3] = (start_[3] + end_[3]) / 2;
    top[4] = (start_[4] + end_[4]) / 2;

    var ascentAnim = new goog.fx.Animation(start_, top,
                                           duration / 2, supereasing_f);

    var descentAnim = new goog.fx.Animation(top, end_,
                                            duration / 2, supereasing_l);

    goog.events.listen(ascentAnim, animationAlteringEvents,
                       this.onEverythingAnimate_, false, this);

    goog.events.listen(descentAnim, animationAlteringEvents,
                       this.onEverythingAnimate_, false, this);

    this.animation_.add(ascentAnim);
    this.animation_.add(descentAnim);
  } else {
    //single animation when altitude is not changing
    var anim = new goog.fx.Animation(start_, end_, duration, supereasing);

    goog.events.listen(anim, animationAlteringEvents,
                       this.onEverythingAnimate_, false, this);

    this.animation_.add(anim);
  }

  goog.events.listen(this.animation_, goog.fx.Transition.EventType.END,
                     this.onEnd_, false, this);

  this.animation_.play();
};

/**
 * Animate everything except altitude
 * @param {goog.events.Event} e The event.
 * @private
 */
weapi.CameraAnimator.prototype.onEverythingAnimate_ = function(e) {
  this.camera_.setPosHeadingAndTilt(e.coords[0], e.coords[1], e.coords[2],
                                    e.coords[3], e.coords[4]);
};

/**
 * Called when animation ends
 * @private
 */
weapi.CameraAnimator.prototype.onEnd_ = function() {
  if (goog.isDefAndNotNull(this.animation_)) {
    this.animation_.dispose();
    this.animation_ = null;
  }
};

/**
 * If the animation is in progress, cancel it
 */
weapi.CameraAnimator.prototype.cancel = function() {
  this.onEnd_();
};


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding field 'Category.workflow'
        db.add_column('workflows_category', 'workflow', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='categories', null=True, to=orm['workflows.Workflow']), keep_default=False)

    def backwards(self, orm):

        # Deleting field 'Category.workflow'
        db.delete_column('workflows_category', 'workflow_id')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'workflows.abstractinput': {
            'Meta': {'object_name': 'AbstractInput'},
            'default': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'multi': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'parameter': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'parameter_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'short_name': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
            'variable': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'widget': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'inputs'", 'to': "orm['workflows.AbstractWidget']"})
        },
        'workflows.abstractoption': {
            'Meta': {'ordering': "['name']", 'object_name': 'AbstractOption'},
            'abstract_input': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'to': "orm['workflows.AbstractInput']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'value': ('django.db.models.fields.TextField', [], {'blank': 'True'})
        },
        'workflows.abstractoutput': {
            'Meta': {'object_name': 'AbstractOutput'},
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'short_name': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
            'variable': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'widget': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'outputs'", 'to': "orm['workflows.AbstractWidget']"})
        },
        'workflows.abstractwidget': {
            'Meta': {'object_name': 'AbstractWidget'},
            'action': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'widgets'", 'to': "orm['workflows.Category']"}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'has_progress_bar': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'image': ('workflows.thumbs.ThumbnailField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'interaction_view': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}),
            'interactive': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'post_interact_action': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}),
            'treeview_image': ('workflows.thumbs.ThumbnailField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'widgets'", 'null': 'True', 'to': "orm['auth.User']"}),
            'visualization_view': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}),
            'wsdl': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
            'wsdl_method': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200', 'blank': 'True'})
        },
        'workflows.category': {
            'Meta': {'ordering': "['name']", 'object_name': 'Category'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['workflows.Category']"}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'categories'", 'null': 'True', 'to': "orm['auth.User']"}),
            'workflow': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'categories'", 'null': 'True', 'to': "orm['workflows.Workflow']"})
        },
        'workflows.connection': {
            'Meta': {'object_name': 'Connection'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'input': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'connections'", 'to': "orm['workflows.Input']"}),
            'output': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'connections'", 'to': "orm['workflows.Output']"}),
            'workflow': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'connections'", 'to': "orm['workflows.Workflow']"})
        },
        'workflows.data': {
            'Meta': {'object_name': 'Data'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'key': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'value': ('django.db.models.fields.TextField', [], {})
        },
        'workflows.input': {
            'Meta': {'object_name': 'Input'},
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'inner_output': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'outer_input_rel'", 'null': 'True', 'to': "orm['workflows.Output']"}),
            'multi_id': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'outer_output': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inner_input_rel'", 'null': 'True', 'to': "orm['workflows.Output']"}),
            'parameter': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'parameter_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'short_name': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
            'value': ('picklefield.fields.PickledObjectField', [], {'null': 'True'}),
            'variable': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'widget': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'inputs'", 'to': "orm['workflows.Widget']"})
        },
        'workflows.option': {
            'Meta': {'ordering': "['name']", 'object_name': 'Option'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'input': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'to': "orm['workflows.Input']"}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})
        },
        'workflows.output': {
            'Meta': {'object_name': 'Output'},
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'inner_input': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'outer_output_rel'", 'null': 'True', 'to': "orm['workflows.Input']"}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'outer_input': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inner_output_rel'", 'null': 'True', 'to': "orm['workflows.Input']"}),
            'short_name': ('django.db.models.fields.CharField', [], {'max_length': '5'}),
            'value': ('picklefield.fields.PickledObjectField', [], {'null': 'True'}),
            'variable': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
            'widget': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'outputs'", 'to': "orm['workflows.Widget']"})
        },
        'workflows.userprofile': {
            'Meta': {'object_name': 'UserProfile'},
            'active_workflow': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'users'", 'null': 'True', 'to': "orm['workflows.Workflow']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'userprofile'", 'unique': 'True', 'to': "orm['auth.User']"})
        },
        'workflows.widget': {
            'Meta': {'object_name': 'Widget'},
            'abstract_widget': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'instances'", 'null': 'True', 'to': "orm['workflows.AbstractWidget']"}),
            'error': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'finished': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'interaction_waiting': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'progress': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'running': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'type': ('django.db.models.fields.CharField', [], {'default': "'regular'", 'max_length': '50'}),
            'workflow': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'widgets'", 'to': "orm['workflows.Workflow']"}),
            'x': ('django.db.models.fields.IntegerField', [], {}),
            'y': ('django.db.models.fields.IntegerField', [], {})
        },
        'workflows.workflow': {
            'Meta': {'ordering': "['name']", 'object_name': 'Workflow'},
            'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'default': "'Untitled workflow'", 'max_length': '200'}),
            'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'template_parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['workflows.Workflow']", 'null': 'True', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'workflows'", 'to': "orm['auth.User']"}),
            'widget': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'workflow_link'", 'unique': 'True', 'null': 'True', 'to': "orm['workflows.Widget']"})
        }
    }

    complete_apps = ['workflows']