text:
UGlobalHotkeys::UGlobalHotkeys(QWidget *parent)
    : QWidget(parent)
{
    #if defined(Q_OS_LINUX)
    qApp->installNativeEventFilter(this);
    QWindow wndw;
    void* v = qApp->platformNativeInterface()->nativeResourceForWindow("connection", &wndw);
    X11Connection = (xcb_connection_t*)v;
    X11Wid = xcb_setup_roots_iterator(xcb_get_setup(X11Connection)).data->root;
    X11KeySymbs = xcb_key_symbols_alloc(X11Connection);
    #endif
}

void UGlobalHotkeys::registerHotkey(const QString& keySeq, size_t id) {
    registerHotkey(UKeySequence(keySeq), id);
}

void UGlobalHotkeys::registerHotkey(const UKeySequence& keySeq, size_t id) {
    if (keySeq.Size() == 0) {
        throw UException("Empty hotkeys");
    }
    if (Registered.find(id) != Registered.end()) {
        unregisterHotkey(id);
    }
    #if defined(Q_OS_WIN)
    size_t winMod = 0;
    size_t key = VK_F2;

    for (size_t i = 0; i != keySeq.Size(); i++) {
        if (keySeq[i] == Qt::Key_Control) {
            winMod |= MOD_CONTROL;
        } else if (keySeq[i] == Qt::Key_Alt) {
            winMod |= MOD_ALT;
        } else if (keySeq[i] == Qt::Key_Shift) {
            winMod |= MOD_SHIFT;
        } else if (keySeq[i] == Qt::Key_Meta) {
            winMod |= MOD_WIN;
        } else {
            key = QtKeyToWin(keySeq[i]);
        }
    }

    if (!RegisterHotKey((HWND)winId(), id, winMod, key)) {
        qDebug() << "Error activating hotkey!";
    } else {
        Registered.insert(id);
    }
    #elif defined(Q_OS_LINUX)
    regLinuxHotkey(keySeq, id);
    #endif
}

void UGlobalHotkeys::unregisterHotkey(size_t id) {
    Q_ASSERT(Registered.find(id) != Registered.end() && "Unregistered hotkey");
    #if defined(Q_OS_WIN)
    UnregisterHotKey((HWND)winId(), id);
    #elif defined(Q_OS_LINUX)
    unregLinuxHotkey(id);
    #endif
    Registered.remove(id);
}

void UGlobalHotkeys::unregisterAllHotkeys()
{
#ifdef Q_OS_WIN
    for (size_t id : Registered)
        this->unregisterHotkey(id);
#elif defined(Q_OS_LINUX)
    for (size_t id :Registered.keys())
        this->unregisterHotkey(id);
#endif
}

UGlobalHotkeys::~UGlobalHotkeys() {
    #if defined(Q_OS_WIN)
    for (QSet<size_t>::iterator i = Registered.begin(); i != Registered.end(); i++) {
        UnregisterHotKey((HWND)winId(), *i);
    }
    #elif defined(Q_OS_LINUX)
    xcb_key_symbols_free(X11KeySymbs);
    #endif
}

#if defined(Q_OS_WIN)
bool UGlobalHotkeys::winEvent(MSG * message, long * result) {
    Q_UNUSED(result);
    if (message->message == WM_HOTKEY) {
        size_t id = message->wParam;
        Q_ASSERT(Registered.find(id) != Registered.end() && "Unregistered hotkey");
        emit activated(id);
    }
    return false;
}

bool UGlobalHotkeys::nativeEvent(const QByteArray &eventType,
                                       void *message, long *result)
{
    Q_UNUSED(eventType);
    return winEvent((MSG*)message, result);
}

#elif defined(Q_OS_LINUX)

bool UGlobalHotkeys::nativeEventFilter(const QByteArray &eventType, void *message, long *result) {
    Q_UNUSED(eventType);
    Q_UNUSED(result);
    return linuxEvent(static_cast<xcb_generic_event_t*>(message));
}

bool UGlobalHotkeys::linuxEvent(xcb_generic_event_t *message)
{
    if ( (message->response_type & ~0x80) == XCB_KEY_PRESS ) {
        xcb_key_press_event_t *ev = (xcb_key_press_event_t*)message;
        auto ind = Registered.key( {ev->detail, (ev->state & ~XCB_MOD_MASK_2)} );

        if (ind == 0) // this is not hotkeys
            return false;

        emit activated(ind);
        return true;
    }
    return false;
}

void UGlobalHotkeys::regLinuxHotkey(const UKeySequence &keySeq, size_t id)
{
    UHotkeyData data;
    UKeyData keyData = QtKeyToLinux(keySeq);

    xcb_keycode_t *keyC = xcb_key_symbols_get_keycode(X11KeySymbs, keyData.key);

    data.keyCode = *keyC;
    data.mods = keyData.mods;

    xcb_grab_key(X11Connection, 1, X11Wid, data.mods, data.keyCode, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
    // NumLk
    xcb_grab_key(X11Connection, 1, X11Wid, data.mods | XCB_MOD_MASK_2, data.keyCode,XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);

    Registered.insert(id, data);
}

void UGlobalHotkeys::unregLinuxHotkey(size_t id)
{
    UHotkeyData data = Registered.take(id);
    xcb_ungrab_key(X11Connection, data.keyCode, X11Wid, data.mods);
    xcb_ungrab_key(X11Connection, data.keyCode, X11Wid, data.mods | XCB_MOD_MASK_2);
}
#endif

redpajama_set_name: RedPajamaGithub


text:
<PROJECTGENERATOR>
    <INCLUDES PLATFORM="ALL">
        <ITEM NAME="../../platform/gucefMT/include/gucefMT_dvmtoswrap.h" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/src/gucefMT_dvmtoswrap.c" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/include/gucefMT_mutex.h" TYPE="FILE" />
        <ITEM NAME="../../platform/gucefMT/src/gucefMT_MUTEX.c" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/include/gucefMT_DVRWLOCK.h" TYPE="FILE" />
        <ITEM NAME="../../platform/gucefMT/src/gucefMT_DVRWLOCK.c" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/include/gucefMT_CMutex.h" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/src/gucefMT_CMutex.cpp" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/include/gucefMT_CScopeMutex.h" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/src/gucefMT_CScopeMutex.cpp" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/include/gucefMT_CILockable.h" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/src/gucefMT_CILockable.cpp" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/include/gucefMT_CReadWriteLock.h" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/src/gucefMT_CReadWriteLock.cpp" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/include/gucefMT_CScopeRwLock.h" TYPE="FILE" />
		<ITEM NAME="../../platform/gucefMT/src/gucefMT_CScopeRwLock.cpp" TYPE="FILE" />
    </INCLUDES>
</PROJECTGENERATOR>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="TypeScriptCompiler">
    <option name="typeScriptServiceDirectory" value="$PROJECT_DIR$/node_modules/typescript/lib" />
    <option name="trackFileSystemChanges" value="false" />
    <option name="useConfig" value="true" />
    <option name="versionType" value="SERVICE_DIRECTORY" />
  </component>
</project>


text:
require_relative '../../spec_helper'
require_relative 'fixtures/classes'

ruby_version_is "3.1"..."3.2" do
  describe "Method#private?" do
    it "returns false when the method is public" do
      obj = MethodSpecs::Methods.new
      obj.method(:my_public_method).private?.should == false
    end

    it "returns false when the method is protected" do
      obj = MethodSpecs::Methods.new
      obj.method(:my_protected_method).private?.should == false
    end

    it "returns true when the method is private" do
      obj = MethodSpecs::Methods.new
      obj.method(:my_private_method).private?.should == true
    end
  end
end


text:
#import "WMFAppViewController.h"
#import "Wikipedia-Swift.h"

// Frameworks
@import Masonry;
#import <Tweaks/FBTweakInline.h>
#import "PiwikTracker+WMFExtensions.h"

//Utility
#import "NSDate+Utilities.h"
#import "MWKDataHousekeeping.h"
#import "NSUserActivity+WMFExtensions.h"
// Networking
#import "SavedArticlesFetcher.h"
#import "SessionSingleton.h"
#import "AssetsFileFetcher.h"
#import "QueuesSingleton.h"

// Model
#import "MediaWikiKit.h"
#import "MWKSearchResult.h"

// Views
#import "UIViewController+WMFStoryboardUtilities.h"
#import "UIViewController+WMFHideKeyboard.h"
#import "UIFont+WMFStyle.h"
#import "WMFStyleManager.h"
#import "UIApplicationShortcutItem+WMFShortcutItem.h"

// View Controllers
#import "WMFExploreViewController.h"
#import "WMFSearchViewController.h"
#import "WMFArticleListTableViewController.h"
#import "DataMigrationProgressViewController.h"
#import "WMFWelcomeViewController.h"
#import "WMFArticleBrowserViewController.h"
#import "WMFNearbyListViewController.h"
#import "UIViewController+WMFSearch.h"
#import "UINavigationController+WMFHideEmptyToolbar.h"

#import "AppDelegate.h"
#import "WMFRandomSectionController.h"
#import "WMFNearbySectionController.h"
#import "WMFRandomArticleFetcher.h"

/**
 *  Enums for each tab in the main tab bar.
 *
 *  @warning Be sure to update `WMFAppTabCount` when these enums change, and always initialize the first enum to 0.
 *
 *  @see WMFAppTabCount
 */
typedef NS_ENUM (NSUInteger, WMFAppTabType){
    WMFAppTabTypeExplore = 0,
    WMFAppTabTypeSaved,
    WMFAppTabTypeRecent
};

/**
 *  Number of tabs in the main tab bar.
 *
 *  @warning Kept as a separate constant to prevent switch statements from being considered inexhaustive. This means we
 *           need to make sure it's manually kept in sync by ensuring:
 *              - The tab enum we increment is the last one
 *              - The first tab enum is initialized to 0
 *
 *  @see WMFAppTabType
 */
static NSUInteger const WMFAppTabCount = WMFAppTabTypeRecent + 1;

static NSTimeInterval const WMFTimeBeforeRefreshingExploreScreen = 24 * 60 * 60;

@interface WMFAppViewController ()<UITabBarControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) IBOutlet UIView* splashView;
@property (nonatomic, strong) UITabBarController* rootTabBarController;

@property (nonatomic, strong, readonly) WMFExploreViewController* exploreViewController;
@property (nonatomic, strong, readonly) WMFArticleListTableViewController* savedArticlesViewController;
@property (nonatomic, strong, readonly) WMFArticleListTableViewController* recentArticlesViewController;

@property (nonatomic, strong) WMFLegacyImageDataMigration* imageMigration;
@property (nonatomic, strong) SavedArticlesFetcher* savedArticlesFetcher;
@property (nonatomic, strong) WMFRandomArticleFetcher* randomFetcher;
@property (nonatomic, strong) SessionSingleton* session;
@property (nonatomic, strong) WMFSavedPageSpotlightManager* spotlightManager;

@property (nonatomic) BOOL isPresentingOnboarding;

/// Use @c rootTabBarController instead.
- (UITabBarController*)tabBarController NS_UNAVAILABLE;

@end

@implementation WMFAppViewController

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

- (BOOL)isPresentingOnboarding {
    return [self.presentedViewController isKindOfClass:[WMFWelcomeViewController class]];
}

#pragma mark - Setup

- (void)loadMainUI {
    if (self.rootTabBarController) {
        return;
    }
    UITabBarController* tabBar = [[UIStoryboard storyboardWithName:@"WMFTabBarUI" bundle:nil] instantiateInitialViewController];
    [self addChildViewController:tabBar];
    [self.view addSubview:tabBar.view];
    [tabBar.view mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.and.bottom.and.leading.and.trailing.equalTo(self.view);
    }];
    [tabBar didMoveToParentViewController:self];
    self.rootTabBarController = tabBar;
    [self configureTabController];
    [self configureExploreViewController];
    [self configureArticleListController:self.savedArticlesViewController];
    [self configureArticleListController:self.recentArticlesViewController];
    [[self class] wmf_setSearchButtonDataStore:self.dataStore];
}

- (void)configureTabController {
    self.rootTabBarController.delegate = self;

    for (WMFAppTabType i = 0; i < WMFAppTabCount; i++) {
        UINavigationController* navigationController = [self navigationControllerForTab:i];
        navigationController.delegate = self;
    }
}

- (void)configureExploreViewController {
    [self.exploreViewController setDataStore:[self dataStore]];
}

- (void)configureArticleListController:(WMFArticleListTableViewController*)controller {
    controller.dataStore = self.session.dataStore;
}

#pragma mark - Notifications

- (void)appWillEnterForegroundWithNotification:(NSNotification*)note {
    [self resumeApp];
}

- (void)appDidEnterBackgroundWithNotification:(NSNotification*)note {
    [self pauseApp];
}

#pragma mark - Launch

+ (WMFAppViewController*)initialAppViewControllerFromDefaultStoryBoard {
    return [[UIStoryboard storyboardWithName:NSStringFromClass([WMFAppViewController class]) bundle:nil] instantiateInitialViewController];
}

- (void)launchAppInWindow:(UIWindow*)window {
    WMFStyleManager* manager = [WMFStyleManager new];
    [manager applyStyleToWindow:window];
    [WMFStyleManager setSharedStyleManager:manager];

    [window setRootViewController:self];
    [window makeKeyAndVisible];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroundWithNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackgroundWithNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil];

    [self showSplashView];

    //HAX: fix for "Unbalanced calls to begin/end appearance transitions" warning
    //We could put it in viewdidappear, but then we would have to wrap it in a dispatch_once to make sure it only runs once
    //Add a delay for iOS 8 (for iOS 9+ we can dispatch and that will be enough)
    dispatchOnMainQueueAfterDelayInSeconds(0.35, ^{
        @weakify(self)
        [self runDataMigrationIfNeededWithCompletion:^{
            @strongify(self)
            [self.imageMigration setupAndStart];
            [self.savedArticlesFetcher fetchAndObserveSavedPageList];
            if ([[NSProcessInfo processInfo] wmf_isOperatingSystemMajorVersionAtLeast:9]) {
                self.spotlightManager = [[WMFSavedPageSpotlightManager alloc] initWithDataStore:self.session.dataStore];
            }
            [self presentOnboardingIfNeededWithCompletion:^(BOOL didShowOnboarding) {
                @strongify(self)
                [self loadMainUI];
                [self hideSplashViewAnimated:!didShowOnboarding];
                [self resumeApp];
                [[PiwikTracker wmf_configuredInstance] wmf_logView:[self rootViewControllerForTab:WMFAppTabTypeExplore]];
            }];
        }];
    });
}

#pragma mark - Start/Pause/Resume App

- (void)resumeApp {
    if (self.isPresentingOnboarding) {
        return;
    }

    if ([self shouldShowLastReadArticleOnLaunch]) {
        [self showLastReadArticleAnimated:YES];
    } else if ([self shouldShowExploreScreenOnLaunch]) {
        [self showExplore];
    }

    if (FBTweakValue(@"Alerts", @"General", @"Show error on launch", NO)) {
        [[WMFAlertManager sharedInstance] showErrorAlert:[NSError errorWithDomain:@"WMFTestDomain" code:0 userInfo:@{NSLocalizedDescriptionKey: @"There was an error"}] sticky:NO dismissPreviousAlerts:NO tapCallBack:NULL];
    }
    if (FBTweakValue(@"Alerts", @"General", @"Show warning on launch", NO)) {
        [[WMFAlertManager sharedInstance] showWarningAlert:@"You have been warned" sticky:NO dismissPreviousAlerts:NO tapCallBack:NULL];
    }
    if (FBTweakValue(@"Alerts", @"General", @"Show success on launch", NO)) {
        [[WMFAlertManager sharedInstance] showSuccessAlert:@"You are successful" sticky:NO dismissPreviousAlerts:NO tapCallBack:NULL];
    }
    if (FBTweakValue(@"Alerts", @"General", @"Show message on launch", NO)) {
        [[WMFAlertManager sharedInstance] showAlert:@"You have been notified" sticky:NO dismissPreviousAlerts:NO tapCallBack:NULL];
    }
}

- (void)pauseApp {
    [self downloadAssetsFilesIfNecessary];
    [self performHousekeeping];
}

#pragma mark - Shortcut

- (void)processShortcutItem:(UIApplicationShortcutItem*)item completion:(void (^)(BOOL))completion {
    if (!item) {
        return;
    }

    if ([item.type isEqualToString:WMFIconShortcutTypeSearch]) {
        [self showSearchAnimated:YES];
    } else if ([item.type isEqualToString:WMFIconShortcutTypeRandom]) {
        [self showRandomArticleAnimated:YES];
    } else if ([item.type isEqualToString:WMFIconShortcutTypeNearby]) {
        [self showNearbyListAnimated:YES];
    } else if ([item.type isEqualToString:WMFIconShortcutTypeContinueReading]) {
        [self showLastReadArticleAnimated:YES];
    }

    if (completion) {
        completion(YES);
    }
}

#pragma mark - NSUserActivity

- (BOOL)processUserActivity:(NSUserActivity*)activity {
    switch ([activity wmf_type]) {
        case WMFUserActivityTypeExplore:
            [self dismissViewControllerAnimated:NO completion:NULL];
            [self.rootTabBarController setSelectedIndex:WMFAppTabTypeExplore];
            [[self navigationControllerForTab:WMFAppTabTypeExplore] popToRootViewControllerAnimated:NO];
            break;
        case WMFUserActivityTypeSavedPages:
            [self dismissViewControllerAnimated:NO completion:NULL];
            [self.rootTabBarController setSelectedIndex:WMFAppTabTypeSaved];
            [[self navigationControllerForTab:WMFAppTabTypeSaved] popToRootViewControllerAnimated:NO];
            break;
        case WMFUserActivityTypeHistory:
            [self dismissViewControllerAnimated:NO completion:NULL];
            [self.rootTabBarController setSelectedIndex:WMFAppTabTypeRecent];
            [[self navigationControllerForTab:WMFAppTabTypeRecent] popToRootViewControllerAnimated:NO];
            break;
        case WMFUserActivityTypeSearch:
            [self dismissViewControllerAnimated:NO completion:NULL];
            [self.rootTabBarController setSelectedIndex:WMFAppTabTypeExplore];
            [[self navigationControllerForTab:WMFAppTabTypeExplore] popToRootViewControllerAnimated:NO];
            [[self rootViewControllerForTab:WMFAppTabTypeExplore] wmf_showSearchAnimated:NO];
            break;
        case WMFUserActivityTypeSearchResults:
            [self dismissViewControllerAnimated:NO completion:NULL];
            [self.rootTabBarController setSelectedIndex:WMFAppTabTypeExplore];
            [[self navigationControllerForTab:WMFAppTabTypeExplore] popToRootViewControllerAnimated:NO];
            [[self rootViewControllerForTab:WMFAppTabTypeExplore] wmf_showSearchAnimated:NO];
            [[UIViewController wmf_sharedSearchViewController] setSearchTerm:[activity wmf_searchTerm]];
            break;
        case WMFUserActivityTypeArticle: {
            MWKTitle* title = [[MWKTitle alloc] initWithURL:activity.webpageURL];
            if (!title) {
                return NO;
            }
            [self showArticleForTitle:title animated:NO];
        }
        break;
        case WMFUserActivityTypeSettings:
            [self dismissViewControllerAnimated:NO completion:NULL];
            [self.rootTabBarController setSelectedIndex:WMFAppTabTypeExplore];
            [[self navigationControllerForTab:WMFAppTabTypeExplore] popToRootViewControllerAnimated:NO];
            [self.exploreViewController showSettings];
            break;
        default:
            return NO;
            break;
    }

    return YES;
}

#pragma mark - Utilities

- (BOOL)shouldShowExploreScreenOnLaunch {
    NSDate* resignActiveDate = [[NSUserDefaults standardUserDefaults] wmf_appResignActiveDate];
    if (!resignActiveDate) {
        return NO;
    }

    if (fabs([resignActiveDate timeIntervalSinceNow]) >= WMFTimeBeforeRefreshingExploreScreen) {
        return YES;
    }
    return NO;
}

- (BOOL)shouldShowLastReadArticleOnLaunch {
    if (FBTweakValue(@"Last Open Article", @"General", @"Restore on Launch", YES)) {
        return YES;
    }

    NSDate* resignActiveDate = [[NSUserDefaults standardUserDefaults] wmf_appResignActiveDate];
    if (!resignActiveDate) {
        return NO;
    }

    if (fabs([resignActiveDate timeIntervalSinceNow]) < WMFTimeBeforeRefreshingExploreScreen) {
        if (![self exploreViewControllerIsDisplayingContent] && [self.rootTabBarController selectedIndex] == WMFAppTabTypeExplore) {
            return YES;
        }
    }

    return NO;
}

- (BOOL)exploreViewControllerIsDisplayingContent {
    return [self navigationControllerForTab:WMFAppTabTypeExplore].viewControllers.count > 1;
}

- (UINavigationController*)navigationControllerForTab:(WMFAppTabType)tab {
    return (UINavigationController*)[self.rootTabBarController viewControllers][tab];
}

- (UIViewController<WMFAnalyticsViewNameProviding>*)rootViewControllerForTab:(WMFAppTabType)tab {
    return [[[self navigationControllerForTab:tab] viewControllers] firstObject];
}

#pragma mark - Accessors

- (WMFLegacyImageDataMigration*)imageMigration {
    if (!_imageMigration) {
        _imageMigration = [[WMFLegacyImageDataMigration alloc]
                           initWithImageController:[WMFImageController sharedInstance]
                                   legacyDataStore:[MWKDataStore new]];
    }
    return _imageMigration;
}

- (SavedArticlesFetcher*)savedArticlesFetcher {
    if (!_savedArticlesFetcher) {
        _savedArticlesFetcher =
            [[SavedArticlesFetcher alloc] initWithSavedPageList:[[[SessionSingleton sharedInstance] userDataStore] savedPageList]];
    }
    return _savedArticlesFetcher;
}

- (WMFRandomArticleFetcher*)randomFetcher {
    if (_randomFetcher == nil) {
        _randomFetcher = [[WMFRandomArticleFetcher alloc] init];
    }
    return _randomFetcher;
}

- (SessionSingleton*)session {
    if (!_session) {
        _session = [SessionSingleton sharedInstance];
    }

    return _session;
}

- (MWKDataStore*)dataStore {
    return self.session.dataStore;
}

- (MWKUserDataStore*)userDataStore {
    return self.session.userDataStore;
}

- (WMFExploreViewController*)exploreViewController {
    return (WMFExploreViewController*)[self rootViewControllerForTab:WMFAppTabTypeExplore];
}

- (WMFArticleListTableViewController*)savedArticlesViewController {
    return (WMFArticleListTableViewController*)[self rootViewControllerForTab:WMFAppTabTypeSaved];
}

- (WMFArticleListTableViewController*)recentArticlesViewController {
    return (WMFArticleListTableViewController*)[self rootViewControllerForTab:WMFAppTabTypeRecent];
}

#pragma mark - UIViewController

- (BOOL)shouldAutorotate {
    return YES;
}

#pragma mark - Onboarding

static NSString* const WMFDidShowOnboarding = @"DidShowOnboarding5.0";

- (BOOL)shouldShowOnboarding {
    if (FBTweakValue(@"Welcome", @"General", @"Show on launch (requires force quit)", NO)
        || [[NSProcessInfo processInfo] environment][@"WMFShowWelcomeView"].boolValue) {
        return YES;
    }
    NSNumber* didShow = [[NSUserDefaults standardUserDefaults] objectForKey:WMFDidShowOnboarding];
    return !didShow.boolValue;
}

- (void)setDidShowOnboarding {
    [[NSUserDefaults standardUserDefaults] setObject:@YES forKey:WMFDidShowOnboarding];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)presentOnboardingIfNeededWithCompletion:(void (^)(BOOL didShowOnboarding))completion {
    if ([self shouldShowOnboarding]) {
        WMFWelcomeViewController* vc = [WMFWelcomeViewController welcomeViewControllerFromDefaultStoryBoard];
        vc.completionBlock = ^{
            [self setDidShowOnboarding];
            if (completion) {
                completion(YES);
            }
        };
        [self presentViewController:vc animated:NO completion:NULL];
    } else {
        if (completion) {
            completion(NO);
        }
    }
}

#pragma mark - Splash

- (void)showSplashView {
    self.splashView.hidden          = NO;
    self.splashView.layer.transform = CATransform3DIdentity;
    self.splashView.alpha           = 1.0;
}

- (void)hideSplashViewAnimated:(BOOL)animated {
    NSTimeInterval duration = animated ? 0.3 : 0.0;

    [UIView animateWithDuration:duration animations:^{
        self.splashView.layer.transform = CATransform3DMakeScale(10.0f, 10.0f, 1.0f);
        self.splashView.alpha = 0.0;
    } completion:^(BOOL finished) {
        self.splashView.hidden = YES;
        self.splashView.layer.transform = CATransform3DIdentity;
    }];
}

- (BOOL)isShowingSplashView {
    return self.splashView.hidden == NO;
}

#pragma mark - Explore VC

- (void)showExplore {
    [self.rootTabBarController setSelectedIndex:WMFAppTabTypeExplore];
    [[self navigationControllerForTab:WMFAppTabTypeExplore] popToRootViewControllerAnimated:NO];
}

#pragma mark - Last Read Article

- (void)showArticleForTitle:(MWKTitle*)title animated:(BOOL)animated {
    if (!title) {
        return;
    }
    if ([[self onscreenTitle] isEqualToTitle:title]) {
        return;
    }
    [self.rootTabBarController setSelectedIndex:WMFAppTabTypeExplore];
    [[self exploreViewController] wmf_pushArticleWithTitle:title dataStore:self.session.dataStore restoreScrollPosition:YES animated:animated];
}

- (void)showLastReadArticleAnimated:(BOOL)animated {
    MWKTitle* lastRead = [[NSUserDefaults standardUserDefaults] wmf_openArticleTitle];
    [self showArticleForTitle:lastRead animated:animated];
}

- (WMFArticleBrowserViewController*)currentlyDisplayedArticleBrowser {
    UINavigationController* navVC = [self navigationControllerForTab:self.rootTabBarController.selectedIndex];
    if (navVC.presentedViewController && [navVC.presentedViewController isKindOfClass:[WMFArticleBrowserViewController class]]) {
        WMFArticleBrowserViewController* vc = (id)navVC.presentedViewController;
        return vc;
    }
    return nil;
}

- (BOOL)articleBrowserIsBeingDisplayed {
    UINavigationController* navVC = [self navigationControllerForTab:self.rootTabBarController.selectedIndex];
    if (navVC.presentedViewController && [navVC.presentedViewController isKindOfClass:[WMFArticleBrowserViewController class]]) {
        return YES;
    }

    return NO;
}

- (MWKTitle*)onscreenTitle {
    UINavigationController* navVC = [self navigationControllerForTab:self.rootTabBarController.selectedIndex];
    if ([navVC.topViewController isKindOfClass:[WMFArticleViewController class]]) {
        return ((WMFArticleViewController*)navVC.topViewController).articleTitle;
    }

    if (navVC.presentedViewController && [navVC.presentedViewController isKindOfClass:[WMFArticleBrowserViewController class]]) {
        WMFArticleBrowserViewController* vc = (id)navVC.presentedViewController;
        return [vc titleOfCurrentArticle];
    }
    return nil;
}

#pragma mark - Show Search

- (void)showSearchAnimated:(BOOL)animated {
    [self.rootTabBarController setSelectedIndex:WMFAppTabTypeExplore];
    UINavigationController* exploreNavController = [self navigationControllerForTab:WMFAppTabTypeExplore];
    if (exploreNavController.presentedViewController) {
        [exploreNavController dismissViewControllerAnimated:NO completion:NULL];
    }
    [self.exploreViewController wmf_showSearchAnimated:animated];
}

#pragma mark - App Shortcuts

- (void)showRandomArticleAnimated:(BOOL)animated {
    [self.rootTabBarController setSelectedIndex:WMFAppTabTypeExplore];
    UINavigationController* exploreNavController = [self navigationControllerForTab:WMFAppTabTypeExplore];
    if (exploreNavController.presentedViewController) {
        [exploreNavController dismissViewControllerAnimated:NO completion:NULL];
    }
    MWKSite* site = [NSUserDefaults standardUserDefaults].wmf_appSite;
    [self.randomFetcher fetchRandomArticleWithSite:site].then(^(MWKSearchResult* result){
        MWKTitle* title = [site titleWithString:result.displayTitle];
        [[self exploreViewController] wmf_pushArticleWithTitle:title dataStore:self.session.dataStore animated:YES];
    }).catch(^(NSError* error){
        [[WMFAlertManager sharedInstance] showErrorAlert:error sticky:NO dismissPreviousAlerts:NO tapCallBack:NULL];
    });
}

- (void)showNearbyListAnimated:(BOOL)animated {
    [self.rootTabBarController setSelectedIndex:WMFAppTabTypeExplore];
    UINavigationController* exploreNavController = [self navigationControllerForTab:WMFAppTabTypeExplore];
    if (exploreNavController.presentedViewController) {
        [exploreNavController dismissViewControllerAnimated:NO completion:NULL];
    }
    [[self navigationControllerForTab:WMFAppTabTypeExplore] popToRootViewControllerAnimated:NO];
    MWKSite* site                   = [NSUserDefaults standardUserDefaults].wmf_appSite;
    WMFNearbyListViewController* vc = [[WMFNearbyListViewController alloc] initWithSearchSite:site dataStore:self.dataStore];
    [[self navigationControllerForTab:WMFAppTabTypeExplore] pushViewController:vc animated:animated];
}

#pragma mark - House Keeping

- (void)performHousekeeping {
    MWKDataHousekeeping* dataHouseKeeping = [[MWKDataHousekeeping alloc] init];
    [dataHouseKeeping performHouseKeeping];
}

#pragma mark - Download Assets

- (void)downloadAssetsFilesIfNecessary {
    // Sync config/ios.json at most once per day.
    [[QueuesSingleton sharedInstance].assetsFetchManager.operationQueue cancelAllOperations];

    (void)[[AssetsFileFetcher alloc] initAndFetchAssetsFileOfType:WMFAssetsFileTypeConfig
                                                      withManager:[QueuesSingleton sharedInstance].assetsFetchManager
                                                           maxAge:kWMFMaxAgeDefault];
}

#pragma mark - Migration

- (void)runDataMigrationIfNeededWithCompletion:(dispatch_block_t)completion {
    DataMigrationProgressViewController* migrationVC = [[DataMigrationProgressViewController alloc] init];
    [migrationVC removeOldDataBackupIfNeeded];

    if (![migrationVC needsMigration]) {
        if (completion) {
            completion();
        }
        return;
    }

    [self presentViewController:migrationVC animated:YES completion:^{
        [migrationVC runMigrationWithCompletion:^(BOOL migrationCompleted) {
            [migrationVC dismissViewControllerAnimated:YES completion:NULL];
            if (completion) {
                completion();
            }
        }];
    }];
}

#pragma mark - UITabBarControllerDelegate

- (void)tabBarController:(UITabBarController*)tabBarController didSelectViewController:(UIViewController*)viewController {
    [self wmf_hideKeyboard];
}

#pragma mark - UINavigationControllerDelegate

- (void)navigationController:(UINavigationController*)navigationController
      willShowViewController:(UIViewController*)viewController
                    animated:(BOOL)animated {
    [navigationController wmf_hideToolbarIfViewControllerHasNoToolbarItems:viewController];
}

@end


text:
import Readability = require('mozilla-readability');
import { JSDOM } from 'jsdom';

// Compiling requires `--noImplicitUseStrict`
// because issue https://github.com/mozilla/readability/issues/346
// requires global variable `Node` when using nodejs.

const fakeUri: Readability.Uri = {
    spec: "http://fakehost/test/page.html",
    host: "fakehost",
    prePath: "http://fakehost",
    scheme: "http",
    pathBase: "http://fakehost/test/"
};

function test_basic_usage() {
    const dom = new JSDOM(`<p>Hello</p><p><strong>Hi!</strong>`);
    // Required until https://github.com/mozilla/readability/issues/346
    // is fixed.
    Node = dom.window.Node;

    const reader = new Readability(fakeUri, dom.window.document);
    const article = reader.parse();
}

function test_readability_with_options() {
    const dom = new JSDOM(`<p>Hello</p><p><strong>Hi!</strong>`);
    // Required until https://github.com/mozilla/readability/issues/346
    // is fixed.
    Node = dom.window.Node;

    const options: Readability.Options = {
        debug: true,
        maxElemsToParse: 100,
    };
    const article = new Readability(fakeUri, dom.window.document, options).parse();
}

function test_is_probably_readerable() {
    const dom = new JSDOM(`<p>Hello</p><p><strong>Hi!</strong>`);
    // Required until https://github.com/mozilla/readability/issues/346
    // is fixed.
    Node = dom.window.Node;

    const isReadable = new Readability(fakeUri, dom.window.document).isProbablyReaderable();
}


text:
set -e

FWUP_CONFIG=$NERVES_DEFCONFIG_DIR/fwup.conf

# Run the common post-image processing for nerves
$BR2_EXTERNAL_NERVES_PATH/board/nerves-common/post-createfs.sh $TARGET_DIR $FWUP_CONFIG


text:
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <openssl/evp.h>
#include <gfarm/gfarm.h>
#include "gfs_proto.h"

char GFS_SERVICE_TAG[] = "gfarm-data";

/*
 * Not really public interface,
 * but common routine called from both client and server.
 */
int
gfs_digest_calculate_local(int fd, char *buffer, size_t buffer_size,
	const EVP_MD *md_type, EVP_MD_CTX *md_ctx,
	size_t *md_lenp, unsigned char *md_value,
	gfarm_off_t *filesizep)
{
	int size;
	gfarm_off_t off = 0;
	unsigned int len;

	if (lseek(fd, (off_t)0, 0) == -1)
		return (errno);

	EVP_DigestInit(md_ctx, md_type);
	while ((size = read(fd, buffer, buffer_size)) > 0) {
		EVP_DigestUpdate(md_ctx, buffer, size);
		off += size;
	}
	EVP_DigestFinal(md_ctx, md_value, &len);

	*md_lenp = len;
	*filesizep = off;
	return (size == -1 ? errno : 0);
}


text:
require 'cocoa/bindings/NSObject'
module Cocoa
  class NSOperation < Cocoa::NSObject
    attach_method :addDependency, :args=>1, :names=>[], :types=>["@"], :retval=>"v"
    attach_method :cancel, :args=>0, :names=>[], :types=>[], :retval=>"v"
    attach_method :completionBlock, :args=>0, :names=>[], :types=>[], :retval=>"@?"
    attach_method :dependencies, :args=>0, :names=>[], :types=>[], :retval=>"@"
    attach_method :init, :args=>0, :names=>[], :types=>[], :retval=>"@"
    attach_method :isCancelled, :args=>0, :names=>[], :types=>[], :retval=>"B"
    attach_method :isConcurrent, :args=>0, :names=>[], :types=>[], :retval=>"B"
    attach_method :isExecuting, :args=>0, :names=>[], :types=>[], :retval=>"B"
    attach_method :isFinished, :args=>0, :names=>[], :types=>[], :retval=>"B"
    attach_method :isReady, :args=>0, :names=>[], :types=>[], :retval=>"B"
    attach_method :main, :args=>0, :names=>[], :types=>[], :retval=>"v"
    attach_method :queuePriority, :args=>0, :names=>[], :types=>[], :retval=>"q"
    attach_method :removeDependency, :args=>1, :names=>[], :types=>["@"], :retval=>"v"
    attach_method :setCompletionBlock, :args=>1, :names=>[], :types=>["@?"], :retval=>"v"
    attach_method :setQueuePriority, :args=>1, :names=>[], :types=>["q"], :retval=>"v"
    attach_method :setThreadPriority, :args=>1, :names=>[], :types=>["d"], :retval=>"v"
    attach_method :start, :args=>0, :names=>[], :types=>[], :retval=>"v"
    attach_method :threadPriority, :args=>0, :names=>[], :types=>[], :retval=>"d"
    attach_method :waitUntilFinished, :args=>0, :names=>[], :types=>[], :retval=>"v"
  end
end


text:
using UnityEngine;
using System.Collections;
using LMWidgets;

public class ScrollBase : LeapPhysicsBase {
  public float InteractionScale = 1.0f;

  // How strong is the snapping spring.
  public float SnapSpringForce = 100.0f;

  // How much drag should be applied ( as a percentage of velocity/second )
  public float Drag = 5.0f;

  // The transform of the root game object of the content to be scrolled.
  public Transform ContentTransform;

  // Used to define and top and bottom of the scroll content
  public Transform ContentTopBound;
  public Transform ContentBottomBound;

  // Used to define the top and bottom of the scroll container
  public Transform ContainerTopBound;
  public Transform ContainerBottomBound;

  // The current velocity of the content.
  protected float m_velocity = 0.0f;

  // The dampening force for the edge spring.
  protected float m_dampingForce = 0.0f;

  // The location of the scrollable content
  // when interaction began.
  protected Vector3 m_contentPivot;

	protected virtual void Start () {
    // Set critical dampening force to avoid oscillation.
    m_dampingForce = Mathf.Sqrt(4.0f * SnapSpringForce);
	}

  protected override void ResetPivots() {
    base.ResetPivots();
    m_contentPivot = ContentTransform.localPosition;
  }

  protected override void ApplyPhysics() {
    applyOverrunSpringForces();
    applyDrag();
    applyVelocity();
  }

  protected void applyDrag() {
    m_velocity -= m_velocity * Mathf.Max(0, Drag * Time.deltaTime);
  }

  protected void applyVelocity() {
    Vector3 currentPosition = ContentTransform.localPosition;
    currentPosition.y += m_velocity * Time.deltaTime;
    ContentTransform.localPosition = currentPosition;
  }

  /// <summary>
  /// Applies a spring force to velocity to return content to scroller bounds.
  /// </summary>
  protected void applyOverrunSpringForces() {
    float overrunDistance = calculateOverrunMagnitude() * InteractionScale;

    if (overrunDistance != 0.0f) {
      float springForce = calculate1DSpringForce(overrunDistance);
      m_velocity += springForce * Time.deltaTime;
    }
  }

  // offsetVector is the vector by which the object is offset from the goal
  protected float calculate1DSpringForce(float offsetVector) {
    float springForce = offsetVector * SnapSpringForce;
    float dampingForce = m_dampingForce * (m_velocity);
    return springForce - dampingForce;
  }

  // calc the amount and direction (if any) the content has overrun the scroll container.
  protected float calculateOverrunMagnitude() {
    float overrunDistance = 0.0f;

    // Put all positions in object space.
    Vector3 localContentTop = transform.InverseTransformPoint(ContentTopBound.position);
    Vector3 localContentBottom = transform.InverseTransformPoint(ContentBottomBound.position);
    Vector3 localContainerTop = transform.InverseTransformPoint(ContainerTopBound.position);
    Vector3 localContainerBottom = transform.InverseTransformPoint(ContainerBottomBound.position);

    if (localContentTop.y < localContainerTop.y) {
      overrunDistance = localContainerTop.y - localContentTop.y;
    }
    else if (localContentBottom.y > localContainerBottom.y) {
      overrunDistance = localContainerBottom.y - localContentBottom.y;
    }

    return overrunDistance;
  }

  protected override void ApplyInteractions() {

    Vector3 targetInteractorPositionChange = transform.parent.InverseTransformPoint(m_target.transform.position) - m_targetPivot;
    targetInteractorPositionChange *= InteractionScale;
    targetInteractorPositionChange.x = 0.0f;
    targetInteractorPositionChange.z = 0.0f;
    Vector3 contentCurrentPosition = ContentTransform.localPosition;
    Vector3 newContentPosition = m_contentPivot + targetInteractorPositionChange;
    Vector3 velocity = (newContentPosition - contentCurrentPosition) / Time.deltaTime;
    m_velocity = velocity.y;

    ContentTransform.localPosition = newContentPosition;
  }

  protected override void ApplyConstraints() {
    return;
  }

}


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async } from '@angular/core/testing';
import { HexPipe } from './hex.pipe';

describe('HexPipe', () => {

  let pipe: HexPipe;

  beforeEach(() => {
    pipe = new HexPipe();
  });

  it('create an instance', () => {
    expect(pipe).toBeTruthy();
  });

  it('converts to a word by default', () => {
    expect(pipe.transform(255)).toBe('$00FF');
  });

  it('converts to number of digits passed', () => {
    expect(pipe.transform(255, 2)).toBe('$FF');
  });
});


text:
from flask import Flask, render_template, session, request, redirect
import random

app = Flask(__name__)
app.secret_key = 'my_secret_key'

@app.route('/')
def index():
    if not 'gold' in session:
        session['gold'] = 0
    if not 'activities' in session:
        session['activities'] = []
    return render_template('index.html')

@app.route('/process', methods = ['POST'])
def process():
    buildings = {
        'farm':random.randint(5,10),
        'casino':random.randint(-50,50),
        'cave':random.randint(0,30),
        'house':random.randint(0,5)
    }
    if request.form['building'] in buildings:
        """ OMG What???"""
        result = buildings[ request.form['building'] ]
        session['gold'] = session['gold']+result
        result_dictionary = {
                                'class': ('red','green')[result > 0],
                                'activity': "You went to the {} and {} {} gold!".format(request.form['building'], ('lost','gained')[result > 0], result)
                            }
        session['activities'].append(result_dictionary)
    return redirect('/')

if __name__ == '__main__':
  app.run(debug = True)

"""
Explain line 24 - 31.  Will it work?  How, where what? why!?
"""

"""
Use variable result to find the name of the building.
Sets session gold equal to a random number depending on building
Sets key of 'class' to a value of 'red' or 'green' depending if you lose or gain money
"""


text:
set -e

export KUBELESS_PKG='github.com/kubeless/kubeless'

# List of bundles to create when no argument is passed
DEFAULT_BUNDLES=(
        validate-test
	validate-gofmt
	validate-git-marks
	validate-lint
	validate-vet
	binary
)
bundle() {
    local bundle="$1"; shift
    echo "---> Making bundle: $(basename "$bundle") (in $DEST)"
    source "script/$bundle" "$@"
}

if [ $# -lt 1 ]; then
    bundles=(${DEFAULT_BUNDLES[@]})
else
    bundles=($@)
fi
for bundle in ${bundles[@]}; do
    export DEST=.
    ABS_DEST="$(cd "$DEST" && pwd -P)"
    bundle "$bundle"
    echo
done


text:
:mod:`anyconfig.backend.xml`
=============================

.. automodule:: anyconfig.backend.xml
    :members:
    :special-members:
    :private-members:
    :undoc-members:
    :show-inheritance:


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class asgn2Passengers.Passenger</title>
<meta name="date" content="2016-05-24">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
asgn2Passengers.Passenger

Packages that use Passenger

Package
Description

asgn2Aircraft

asgn2Passengers

asgn2Simulators

Uses of Passenger in asgn2Aircraft

Fields in asgn2Aircraft with type parameters of type Passenger

Modifier and Type
Field and Description

protected java.util.List<Passenger>
Aircraft.seats

Methods in asgn2Aircraft that return types with arguments of type Passenger

Modifier and Type
Method and Description

java.util.List<Passenger>
Aircraft.getPassengers()

Method to return an List object containing a copy of
 the list of passengers on this aircraft.

Methods in asgn2Aircraft with parameters of type Passenger

Modifier and Type
Method and Description

void
Aircraft.cancelBooking(Passenger p,
             int cancellationTime)

Method to remove passenger from the aircraft - passenger must have a confirmed
 seat prior to entry to this method.

void
Aircraft.confirmBooking(Passenger p,
              int confirmationTime)

Method to add a Passenger to the aircraft seating.

boolean
Aircraft.hasPassenger(Passenger p)

Simple boolean to check whether a passenger is included on the aircraft

boolean
Aircraft.seatsAvailable(Passenger p)

Given a Passenger, method determines whether there are seats available in that
 fare class.

Uses of Passenger in asgn2Passengers

Subclasses of Passenger in asgn2Passengers

Modifier and Type
Class and Description

class
Business

class
Economy

class
First

class
Premium

Methods in asgn2Passengers that return Passenger

Modifier and Type
Method and Description

Passenger
Premium.upgrade()

abstract Passenger
Passenger.upgrade()

Method to create new Passenger instance based on upgrade to a higher fare class.

Passenger
First.upgrade()

Passenger
Economy.upgrade()

Passenger
Business.upgrade()

Methods in asgn2Passengers with parameters of type Passenger

Modifier and Type
Method and Description

protected void
Passenger.copyPassengerState(Passenger p)

Helper method to copy state to facilitate upgrade()

Uses of Passenger in asgn2Simulators

Methods in asgn2Simulators that return Passenger

Modifier and Type
Method and Description

Passenger
Simulator.createPassenger(int bookingTime,
               int departureTime)

Method to create a New Passenger.

Methods in asgn2Simulators that return types with arguments of type Passenger

Modifier and Type
Method and Description

java.util.List<Passenger>
Flights.cancelBookings(java.util.Random rng,
              double cancelProb,
              int cancelTime)

Cancel bookings across the daily schedule based on cancellation probability

Methods in asgn2Simulators with parameters of type Passenger

Modifier and Type
Method and Description

void
Flights.addPassenger(Passenger p,
            int time)

Adds a Passenger to one of the aircraft in the flight list.

void
Simulator.queuePassenger(Passenger p,
              int queueTime,
              int departureTime)

Method to add a Passenger to the simulator queue.

void
Simulator.refuseBooking(Passenger p,
             int refusalTime)

Method to add a Passenger to the refused list.

boolean
Flights.seatsAvailable(Passenger p)

Given a Passenger, method determines whether there are seats available in that
 fare class across the daily schedule

static java.lang.String
Log.setPassengerMsg(Passenger p,
               java.lang.String source,
               java.lang.String target)

Helper to set Passenger transition messages

static java.lang.String
Log.setUpgradeMsg(Passenger p)

Helper to set Passenger upgrade messages.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
#include "tuple_update.h"
#include <stdio.h>

#include "third_party/queue.h"

#include "salad/rope.h"
#include "error.h"
#include "msgpuck/msgpuck.h"
#include "bit/int96.h"

/** UPDATE request implementation.
 * UPDATE request is represented by a sequence of operations, each
 * working with a single field. There also are operations which
 * add or remove fields. Only one operation on the same field
 * is allowed.
 *
 * Supported field change operations are: SET, ADD, SUBTRACT;
 * bitwise AND, XOR and OR; SPLICE.
 *
 * Supported tuple change operations are: SET, DELETE, INSERT,
 * PUSH and POP.
 * If the number of fields in a tuple is altered by an operation,
 * field index of all following operations is evaluated against the
 * new tuple.
 *
 * Despite the allowed complexity, a typical use case for UPDATE
 * is when the operation count is much less than field count in
 * a tuple.
 *
 * With the common case in mind, UPDATE tries to minimize
 * the amount of unnecessary temporary tuple copies.
 *
 * First, operations are parsed and initialized. Then, the
 * resulting tuple length is calculated. A new tuple is allocated.
 * Finally, operations are applied sequentially, each copying data
 * from the old tuple to the new tuple.
 *
 * With this approach, cost of UPDATE is proportional to O(tuple
 * length) + O(C * log C), where C is the number of operations in
 * the request, and data is copied from the old tuple to the new
 * one only once.
 *
 * As long as INSERT, DELETE, PUSH and POP change the relative
 * field order, an auxiliary data structure is necessary to look
 * up fields in the "old" tuple by field number. Such field
 * index is built on demand, using "rope" data structure.
 *
 * A rope is a binary tree designed to store long strings built
 * from pieces. Each tree node points to a substring of a large
 * string. In our case, each rope node points at a range of
 * fields, initially in the old tuple, and then, as fields are
 * added and deleted by UPDATE, in the "current" tuple.
 * Note, that the tuple itself is not materialized: when
 * operations which affect field count are initialized, the rope
 * is updated to reflect the new field order.
 * In particular, if a field is deleted by an operation,
 * it disappears from the rope and all subsequent operations
 * on this field number instead affect the field following the
 * deleted one.
 */

/** Update internal state */
struct tuple_update
{
	region_alloc_func alloc;
	void *alloc_ctx;
	struct rope *rope;
	struct update_op *ops;
	uint32_t op_count;
	int index_base; /* 0 for C and 1 for Lua */
};

/** Argument of SET operation. */
struct op_set_arg {
	uint32_t length;
	const char *value;
};

/**
 * MsgPack format code of an arithmetic argument or result.
 * MsgPack codes are not used to simplify type calculation.
 */
enum arith_type {
	AT_DOUBLE = 0, /* MP_DOUBLE */
	AT_FLOAT = 1, /* MP_FLOAT */
	AT_INT = 2 /* MP_INT/MP_UINT */
};

/**
 * Argument (left and right) and result of ADD, AND, XOR, OR,
 * SUBTRACT, MULTIPLY.
 *
 * To perform an arithmetic operation, update first loads
 * left and right arguments into corresponding value objects,
 * then performs arithmetics on types of arguments, thus
 * calculating the type of the result, and then
 * performs the requested operation according to the calculated
 * type rules.
 *
 * The rules are as follows:
 * - when one of the argument types is double, the result is
 *   double
 * - when one of the argument types is float, the result is
 *   float
 * - for integer arguments, the result type code depends on
 *   the range in which falls the result of the operation.
 *   If the result is in negative range, it's MP_INT, otherwise
 *   it's MP_UINT. If the result is out of bounds of (-2^63,
 *   2^64), and exception is raised for overflow.
 */
struct op_arith_arg {
	enum arith_type type;
	union {
		double dbl;
		float flt;
		struct int96_num int96;
	};
};

/** Argument of AND, XOR, OR operations. */
struct op_bit_arg {
	uint64_t val;
};

/** Argument of SPLICE. */
struct op_splice_arg {
	int32_t offset;	   /** splice position */
	int32_t cut_length;    /** cut this many bytes. */
	const char *paste; /** paste what? */
	uint32_t paste_length;  /** paste this many bytes. */

	/** Offset of the tail in the old field */
	int32_t tail_offset;
	/** Size of the tail. */
	int32_t tail_length;
};

union update_op_arg {
	struct op_set_arg set;
	struct op_arith_arg arith;
	struct op_bit_arg bit;
	struct op_splice_arg splice;
};

struct update_field;
struct update_op;

typedef void (*do_op_func)(struct tuple_update *update, struct update_op *op,
			   const char **expr);
typedef void (*store_op_func)(union update_op_arg *arg, const char *in, char *out);

/** A set of functions and properties to initialize and do an op. */
struct update_op_meta {
	do_op_func do_op;
	store_op_func store;
	/* Argument count */
	uint32_t args;
};

/** A single UPDATE operation. */
struct update_op {
	const struct update_op_meta *meta;
	union update_op_arg arg;
	/* Subject field no. */
	uint32_t field_no;
	uint32_t new_field_len;
	uint8_t opcode;
};

/**
 * We can have more than one operation on the same field.
 * A descriptor of one changed field.
 */
struct update_field {
	/** UPDATE operation against the first field in the range. */
	struct update_op *op;
	/** Points at start of field *data* in the old tuple. */
	const char *old;
	/** End of the old field. */
	const char *tail;
	/**
	 * Length of the "tail" in the old tuple from end
	 * of old data to the beginning of the field in the
	 * next update_field structure.
	 */
	uint32_t tail_len;
};

static void
update_field_init(struct update_field *field,
		  const char *old, uint32_t old_len, uint32_t tail_len)
{
	field->op = NULL;
	field->old = old;
	field->tail = old + old_len;
	field->tail_len = tail_len;
}

/** Read a field index or any other integer field. */
static inline int64_t
mp_read_int(struct tuple_update *update, struct update_op *op,
	    const char **expr)
{
	int64_t field_no;
	if (mp_typeof(**expr) == MP_UINT)
		field_no = mp_decode_uint(expr);
	else if (mp_typeof(**expr) == MP_INT)
		field_no = mp_decode_int(expr);
	else
		tnt_raise(ClientError, ER_ARG_TYPE, (char ) op->opcode,
			  update->index_base + op->field_no, "UINT");
	return field_no;
}

static inline uint64_t
mp_read_uint(struct tuple_update *update, struct update_op *op,
	     const char **expr)
{
	int64_t field_no;
	if (mp_typeof(**expr) == MP_UINT)
		field_no = mp_decode_uint(expr);
	else
		tnt_raise(ClientError, ER_ARG_TYPE, (char ) op->opcode,
			  update->index_base + op->field_no, "UINT");
	return field_no;
}

/**
 * Load an argument of an arithmetic operation either from tuple
 * or from the UPDATE command.
 */
static inline struct op_arith_arg
mp_read_arith_arg(struct tuple_update *update, struct update_op *op,
		  const char **expr)
{
	struct op_arith_arg result;
	if (mp_typeof(**expr) == MP_UINT) {
		result.type = AT_INT;
		int96_set_unsigned(&result.int96, mp_decode_uint(expr));
	} else if (mp_typeof(**expr) == MP_INT) {
		result.type = AT_INT;
		int96_set_signed(&result.int96, mp_decode_int(expr));
	} else if (mp_typeof(**expr) == MP_DOUBLE) {
		result.type = AT_DOUBLE;
		result.dbl = mp_decode_double(expr);
	} else if (mp_typeof(**expr) == MP_FLOAT) {
		result.type = AT_FLOAT;
		result.flt = mp_decode_float(expr);
	} else {
		tnt_raise(ClientError, ER_ARG_TYPE, (char ) op->opcode,
			  update->index_base + op->field_no, "NUMBER");
	}
	return result;
}

static inline double
cast_arith_arg_to_double(struct op_arith_arg arg)
{
	if (arg.type == AT_DOUBLE) {
		return arg.dbl;
	} else if (arg.type == AT_FLOAT) {
		return arg.flt;
	} else {
		assert(arg.type == AT_INT);
		if (int96_is_uint64(&arg.int96)) {
			return int96_extract_uint64(&arg.int96);
		} else {
			assert(int96_is_neg_int64(&arg.int96));
			return int96_extract_neg_int64(&arg.int96);
		}
	}
}

/** Return the MsgPack size of an arithmetic operation result. */
static inline uint32_t
mp_sizeof_op_arith_arg(struct op_arith_arg arg)
{
	if (arg.type == AT_INT) {
		if (int96_is_uint64(&arg.int96)) {
			uint64_t val = int96_extract_uint64(&arg.int96);
			return mp_sizeof_uint(val);
		} else {
			int64_t val = int96_extract_neg_int64(&arg.int96);
			return mp_sizeof_int(val);
		}
	} else if (arg.type == AT_DOUBLE) {
		return mp_sizeof_double(arg.dbl);
	} else {
		assert(arg.type == AT_FLOAT);
		return mp_sizeof_float(arg.flt);
	}
}

static inline const char *
mp_read_str(struct tuple_update *update, struct update_op *op,
	    const char **expr, uint32_t *len)
{
	if (mp_typeof(**expr) != MP_STR) {
		tnt_raise(ClientError, ER_ARG_TYPE, (char) op->opcode,
			  update->index_base + op->field_no, "STR");
	}
	return mp_decode_str(expr, len); /* value */
}

static inline void
op_check_field_no(struct tuple_update *update, uint32_t field_no,
		  uint32_t field_max)
{
	if (field_no > field_max)
		tnt_raise(ClientError, ER_NO_SUCH_FIELD, update->index_base +
			  field_no);
}

static inline void
op_adjust_field_no(struct tuple_update *update, struct update_op *op,
		   uint32_t field_max)
{
	if (op->field_no == UINT32_MAX)
		op->field_no = field_max;
	else
		op_check_field_no(update, op->field_no, field_max);
}

static inline void
op_set_read(struct update_op *op, const char **expr)
{
	op->arg.set.value = *expr;
	mp_next(expr);
	op->arg.set.length = *expr - op->arg.set.value;
}

/* {{{ do_op */

static void
do_op_insert(struct tuple_update *update, struct update_op *op,
	     const char **expr)
{
	op_adjust_field_no(update, op, rope_size(update->rope));
	op_set_read(op, expr);
	struct update_field *field = (struct update_field *)
		update->alloc(update->alloc_ctx, sizeof(*field));
	update_field_init(field, op->arg.set.value, op->arg.set.length, 0);
	rope_insert(update->rope, op->field_no, field, 1);
}

static void
do_op_set(struct tuple_update *update, struct update_op *op,
	  const char **expr)
{
	if (op->field_no < rope_size(update->rope)) {
		struct update_field *field = (struct update_field *)
				rope_extract(update->rope, op->field_no);
		/* Ignore the previous op, if any. */
		field->op = op;
		op_set_read(op, expr);
		op->new_field_len = op->arg.set.length;
	} else {
		do_op_insert(update, op, expr);
	}
}

static void
do_op_delete(struct tuple_update *update, struct update_op *op,
	     const char **expr)
{
	op_adjust_field_no(update, op, rope_size(update->rope) - 1);
	uint32_t delete_count = mp_read_int(update, op, expr);

	if ((uint64_t) op->field_no + delete_count > rope_size(update->rope))
		delete_count = rope_size(update->rope) - op->field_no;

	if (delete_count == 0) {
		tnt_raise(ClientError, ER_UPDATE_FIELD, update->index_base +
			  op->field_no, "cannot delete 0 fields");
	}

	for (uint32_t u = 0; u < delete_count; u++)
		rope_erase(update->rope, op->field_no);
}

static inline struct op_arith_arg
make_arith_operation(struct op_arith_arg arg1, struct op_arith_arg arg2,
		     char opcode, uint32_t err_fieldno)
{
	struct op_arith_arg result;

	arith_type lowest_type = arg1.type;
	if (arg1.type > arg2.type)
		lowest_type = arg2.type;

	if (lowest_type == AT_INT) {
		result.type = AT_INT;
		switch(opcode) {
		case '+':
			int96_add(&arg1.int96, &arg2.int96);
			break;
		case '-':
			int96_invert(&arg2.int96);
			int96_add(&arg1.int96, &arg2.int96);
			break;
		default:
			assert(false); /* checked by update_read_ops */
			break;
		}
		if (!int96_is_uint64(&arg1.int96) &&
		    !int96_is_neg_int64(&arg1.int96)) {
			tnt_raise(ClientError,
				  ER_UPDATE_INTEGER_OVERFLOW,
				  opcode, err_fieldno);
		}
		return arg1;
	} else {
		/* At least one of operands is double or float */
		double a = cast_arith_arg_to_double(arg1);
		double b = cast_arith_arg_to_double(arg2);
		double c;
		switch(opcode) {
		case '+': c = a + b; break;
		case '-': c = a - b; break;
		default:
			tnt_raise(ClientError, ER_ARG_TYPE, (char ) opcode,
				err_fieldno, "positive integer");
			break;
		}
		if (lowest_type == AT_DOUBLE) {
			/* result is DOUBLE */
			result.type = AT_DOUBLE;
			result.dbl = c;
		} else {
			/* result is FLOAT */
			assert(lowest_type == AT_FLOAT);
			result.type = AT_FLOAT;
			result.flt = (float)c;
		}
	}
	return result;
}

static void
prepare_op_arith(struct tuple_update *update, struct update_op *op,
		 const char **expr, struct op_arith_arg *left)
{
	op_check_field_no(update, op->field_no, rope_size(update->rope) - 1);

	struct update_field *field = (struct update_field *)
			rope_extract(update->rope, op->field_no);
	if (field->op) {
		tnt_raise(ClientError, ER_UPDATE_FIELD, update->index_base +
			  op->field_no, "double update of the same field");
	}
	field->op = op;
	const char *old = field->old;
	*left = mp_read_arith_arg(update, op, &old);
	op->arg.arith = mp_read_arith_arg(update, op, expr);
}

static void
do_op_arith(struct tuple_update *update, struct update_op *op,
	    const char **expr)
{
	struct op_arith_arg left;
	prepare_op_arith(update, op, expr, &left);
	op->arg.arith = make_arith_operation(left, op->arg.arith, op->opcode,
					     update->index_base + op->field_no);
	op->new_field_len = mp_sizeof_op_arith_arg(op->arg.arith);
}

static void
do_op_bit(struct tuple_update *update, struct update_op *op,
	  const char **expr)
{
	op_check_field_no(update, op->field_no, rope_size(update->rope) - 1);
	struct update_field *field = (struct update_field *)
			rope_extract(update->rope, op->field_no);

	struct op_bit_arg *arg = &op->arg.bit;
	arg->val = mp_read_uint(update, op, expr);
	if (field->op) {
		tnt_raise(ClientError, ER_UPDATE_FIELD,
			update->index_base + op->field_no,
			"double update of the same field");
	}
	field->op = op;
	const char *old = field->old;
	uint64_t val = mp_read_uint(update, op, &old);
	switch (op->opcode) {
	case '&':
		arg->val &= val;
		break;
	case '^':
		arg->val ^= val;
		break;
	case '|':
		arg->val |= val;
		break;
	default:
		assert(false); /* checked by update_read_ops */
	}
	op->new_field_len = mp_sizeof_uint(arg->val);
}

static void
do_op_splice(struct tuple_update *update, struct update_op *op,
	     const char **expr)
{
	op_check_field_no(update, op->field_no, rope_size(update->rope) - 1);
	struct update_field *field = (struct update_field *)
			rope_extract(update->rope, op->field_no);
	if (field->op) {
		tnt_raise(ClientError, ER_UPDATE_FIELD,
			  update->index_base + op->field_no,
			  "double update of the same field");
	}

	struct op_splice_arg *arg = &op->arg.splice;

	arg->offset = mp_read_int(update, op, expr);
	arg->cut_length = mp_read_int(update, op, expr); /* cut length */

	arg->paste = mp_read_str(update, op, expr, &arg->paste_length); /* value */

	const char *in = field->old;
	uint32_t str_len;
	in = mp_read_str(update, op, &in, &str_len);

	if (arg->offset < 0) {
		if (-arg->offset > str_len + 1) {
			tnt_raise(ClientError, ER_SPLICE, update->index_base +
				  op->field_no, "offset is out of bound");
		}
		arg->offset = arg->offset + str_len + 1;
	} else if (arg->offset > str_len) {
		arg->offset = str_len;
	}

	assert(arg->offset >= 0 && arg->offset <= str_len);

	if (arg->cut_length < 0) {
		if (-arg->cut_length > (str_len - arg->offset))
			arg->cut_length = 0;
		else
			arg->cut_length += str_len - arg->offset;
	} else if (arg->cut_length > str_len - arg->offset) {
		arg->cut_length = str_len - arg->offset;
	}

	assert(arg->offset <= str_len);

	/* Fill tail part */
	arg->tail_offset = arg->offset + arg->cut_length;
	arg->tail_length = str_len - arg->tail_offset;

	/* Record the new field length (maximal). */
	op->new_field_len = mp_sizeof_str(arg->offset + arg->paste_length +
					  arg->tail_length);
	field->op = op;
}

/* }}} */

/* {{{ store_op */

static void
store_op_set(struct op_set_arg *arg, const char *in __attribute__((unused)),
		 char *out)
{
	memcpy(out, arg->value, arg->length);
}

static void
store_op_arith(struct op_arith_arg *arg,
	       const char *in __attribute__((unused)), char *out)
{
	if (arg->type == AT_INT) {
		if (int96_is_uint64(&arg->int96)) {
			mp_encode_uint(out, int96_extract_uint64(&arg->int96));
		} else {
			assert(int96_is_neg_int64(&arg->int96));
			mp_encode_int(out, int96_extract_neg_int64(&arg->int96));
		}
	} else if (arg->type == AT_DOUBLE) {
		mp_encode_double(out, arg->dbl);
	} else {
		assert(arg->type == AT_FLOAT);
		mp_encode_float(out, arg->flt);
	}
}

static void
store_op_bit(struct op_bit_arg *arg, const char *in __attribute__((unused)), char *out)
{
	mp_encode_uint(out, arg->val);
}

static void
store_op_splice(struct op_splice_arg *arg, const char *in, char *out)
{
	uint32_t new_str_len = arg->offset + arg->paste_length
		+ arg->tail_length;

	(void) mp_decode_strl(&in);

	out = mp_encode_strl(out, new_str_len);
	memcpy(out, in, arg->offset);               /* copy field head. */
	out = out + arg->offset;
	memcpy(out, arg->paste, arg->paste_length); /* copy the paste */
	out = out + arg->paste_length;
	memcpy(out, in + arg->tail_offset, arg->tail_length); /* copy tail */
}

static void
store_op_insert(struct op_set_arg *arg,
		    const char *in __attribute__((unused)),
		    char *out)
{
	memcpy(out, arg->value, arg->length);
}

static const struct update_op_meta op_set =
	{ do_op_set, (store_op_func) store_op_set, 3 };
static const struct update_op_meta op_insert =
	{ do_op_insert, (store_op_func) store_op_insert, 3 };
static const struct update_op_meta op_arith =
	{ do_op_arith, (store_op_func) store_op_arith, 3 };
static const struct update_op_meta op_bit =
	{ do_op_bit, (store_op_func) store_op_bit, 3 };
static const struct update_op_meta op_splice =
	{ do_op_splice, (store_op_func) store_op_splice, 5 };
static const struct update_op_meta op_delete =
	{ do_op_delete, (store_op_func) NULL, 3 };

/* }}} */

/** Split a range of fields in two, allocating update_field
 * context for the new range.
 */
static void *
update_field_split(void *split_ctx, void *data, size_t size __attribute__((unused)),
		   size_t offset)
{
	struct tuple_update *update = (struct tuple_update *) split_ctx;

	struct update_field *prev = (struct update_field *) data;

	struct update_field *next = (struct update_field *)
			update->alloc(update->alloc_ctx, sizeof(*next));
	assert(offset > 0 && prev->tail_len > 0);

	const char *field = prev->tail;
	const char *end = field + prev->tail_len;

	for (uint32_t i = 1; i < offset; i++) {
		mp_next(&field);
	}

	prev->tail_len = field - prev->tail;
	const char *f = field;
	mp_next(&f);
	uint32_t field_len = f - field;

	update_field_init(next, field, field_len, end - field - field_len);
	return next;
}

/** Free rope node - do nothing, since we use a pool allocator. */
static void
region_alloc_free_stub(void *ctx, void *mem)
{
	(void) ctx;
	(void) mem;
}

/**
 * We found a tuple to do the update on. Prepare a rope
 * to perform operations on.
 */
void
update_create_rope(struct tuple_update *update,
		   const char *tuple_data, const char *tuple_data_end)
{
	uint32_t field_count = mp_decode_array(&tuple_data);

	update->rope = rope_new(update_field_split, update, update->alloc,
				region_alloc_free_stub, update->alloc_ctx);

	/* Initialize the rope with the old tuple. */

	struct update_field *first = (struct update_field *)
			update->alloc(update->alloc_ctx, sizeof(*first));
	const char *field = tuple_data;
	const char *end = tuple_data_end;

	/* Add first field to rope */
	mp_next(&tuple_data);
	uint32_t field_len = tuple_data - field;
	update_field_init(first, field, field_len,
			  end - field - field_len);

	rope_append(update->rope, first, field_count);
}

static uint32_t
update_calc_tuple_length(struct tuple_update *update)
{
	uint32_t res = mp_sizeof_array(rope_size(update->rope));
	struct rope_iter it;
	struct rope_node *node;

	rope_iter_create(&it, update->rope);
	for (node = rope_iter_start(&it); node; node = rope_iter_next(&it)) {
		struct update_field *field =
				(struct update_field *) rope_leaf_data(node);
		uint32_t field_len = (field->op ? field->op->new_field_len :
				      field->tail - field->old);
		res += field_len + field->tail_len;
	}

	return res;
}

static uint32_t
update_write_tuple(struct tuple_update *update, char *buffer, char *buffer_end)
{
	char *new_data = buffer;
	new_data = mp_encode_array(new_data, rope_size(update->rope));

	(void) buffer_end;

	uint32_t total_field_count = 0;

	struct rope_iter it;
	struct rope_node *node;

	rope_iter_create(&it, update->rope);
	for (node = rope_iter_start(&it); node; node = rope_iter_next(&it)) {
		struct update_field *field = (struct update_field *)
				rope_leaf_data(node);
		uint32_t field_count = rope_leaf_size(node);
		const char *old_field = field->old;
		struct update_op *op = field->op;
		if (op) {
			op->meta->store(&op->arg, old_field, new_data);
			new_data += op->new_field_len;
		} else {
			uint32_t field_len = field->tail - field->old;
			memcpy(new_data, old_field, field_len);
			new_data += field_len;
		}
		/* Copy tail_len from the old tuple. */
		assert(field->tail_len == 0 || field_count > 1);
		if (field_count > 1) {
			memcpy(new_data, field->tail, field->tail_len);
			new_data += field->tail_len;
		}
		total_field_count += field_count;
	}

	assert(rope_size(update->rope) == total_field_count);
	assert(new_data <= buffer_end);
	return new_data - buffer; /* real_tuple_size */
}

static void
update_read_ops(struct tuple_update *update, const char *expr,
		const char *expr_end)
{
	/* number of operations */
	update->op_count = mp_decode_array(&expr);

	if (update->op_count > BOX_UPDATE_OP_CNT_MAX)
		tnt_raise(IllegalParams, "too many operations for update");
	if (update->op_count == 0)
		tnt_raise(IllegalParams, "no operations for update");

	/* Read update operations.  */
	update->ops = (struct update_op *) update->alloc(update->alloc_ctx,
				update->op_count * sizeof(struct update_op));
	struct update_op *op = update->ops;
	struct update_op *ops_end = op + update->op_count;
	for (; op < ops_end; op++) {
		/* Read operation */
		uint32_t args, len;
		args = mp_decode_array(&expr);
		if (args < 1)
			tnt_raise(ClientError, ER_INVALID_MSGPACK, "expected an update operation (array)");
		if (mp_typeof(*expr) != MP_STR)
			tnt_raise(ClientError, ER_INVALID_MSGPACK, "expected an update operation name (string)");

		op->opcode = *mp_decode_str(&expr, &len);

		switch (op->opcode) {
		case '=':
			op->meta = &op_set;
			break;
		case '+':
		case '-':
			op->meta = &op_arith;
			break;
		case '&':
		case '|':
		case '^':
			op->meta = &op_bit;
			break;
		case ':':
			op->meta = &op_splice;
			break;
		case '#':
			op->meta = &op_delete;
			break;
		case '!':
			op->meta = &op_insert;
			break;
		default:
			tnt_raise(ClientError, ER_UNKNOWN_UPDATE_OP);
		}
		if (args != op->meta->args)
			tnt_raise(ClientError, ER_UNKNOWN_UPDATE_OP);
		op->field_no = mp_read_int(update, op, &expr);
		op->meta->do_op(update, op, &expr);
	}

	/* Check the remainder length, the request must be fully read. */
	if (expr != expr_end)
		tnt_raise(IllegalParams, "can't unpack update operations");
}

const char *
tuple_update_execute(region_alloc_func alloc, void *alloc_ctx,
		     const char *expr,const char *expr_end,
		     const char *old_data, const char *old_data_end,
		     uint32_t *p_tuple_len, int index_base)
{
	struct tuple_update *update = (struct tuple_update *)
			alloc(alloc_ctx, sizeof(*update));
	assert(update != NULL);
	memset(update, 0, sizeof(*update));
	update->alloc = alloc;
	update->alloc_ctx = alloc_ctx;
	/*
	 * Base field offset, e.g. 0 for C and 1 for Lua. Used only for
	 * error messages. All fields numbers must be zero-based!
	 */
	update->index_base = index_base;

	update_create_rope(update, old_data, old_data_end);
	update_read_ops(update, expr, expr_end);
	uint32_t tuple_len = update_calc_tuple_length(update);

	char *buffer = (char *) alloc(alloc_ctx, tuple_len);

	*p_tuple_len = update_write_tuple(update, buffer, buffer + tuple_len);

	return buffer;
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<example>
  <tags></tags>
  <include>
    <file zip="true" url="../Shared/EditorTemplates/Customer.cshtml" />
    <file zip="true" url="../Shared/EditorTemplates/Department.cshtml" />
    <file zip="true" url="../../Models/Editor_TemplateModel.cs" />
  </include>
</example>


text:
Pattern: Missing multi-word component name

Issue: -

## Description

This rule require component names to be always multi-word, except for root `App`
components, and built-in components provided by Vue, such as `<transition>` or
`<component>`. This prevents conflicts with existing and future HTML elements,
since all HTML elements are a single word.

<eslint-code-block filename="src/TodoItem.js" language="javascript" :rules="{'vue/multi-word-component-names': ['error']}">

```js
/* ✓ GOOD */
Vue.component('todo-item', {
  // ...
})

/* ✗ BAD */
Vue.component('Todo', {
  // ...
})
```

</eslint-code-block>

<eslint-code-block filename="src/TodoItem.js" :rules="{'vue/multi-word-component-names': ['error']}">

```vue
<script>
/* ✓ GOOD */
export default {
  name: 'TodoItem',
  // ...
}
</script>
```

</eslint-code-block>

<eslint-code-block filename="src/Todo.vue" :rules="{'vue/multi-word-component-names': ['error']}">

```vue
<script>
/* ✗ BAD */
export default {
  name: 'Todo',
  // ...
}
</script>
```

</eslint-code-block>

<eslint-code-block filename="src/Todo.vue" :rules="{'vue/multi-word-component-names': ['error']}">

```vue
<!-- filename: Todo.vue -->
<script>
/* ✗ BAD */
export default {
  // ...
}
</script>
```

</eslint-code-block>

## Options

```json
{
  "vue/multi-word-component-names": ["error", {
    "ignores": []
  }]
}
```

- `ignores` (`string[]`) ... The component names to ignore. Sets the component name to allow.

### `ignores: ["Todo"]`

<eslint-code-block :rules="{'vue/multi-word-component-names': ['error', {ignores: ['Todo']}]}">

```vue
<script>
export default {
  /* ✓ GOOD */
  name: 'Todo'
}
</script>
```

</eslint-code-block>

<eslint-code-block :rules="{'vue/multi-word-component-names': ['error', {ignores: ['Todo']}]}">

```vue
<script>
export default {
  /* ✗ BAD */
  name: 'Item'
}
</script>
```

</eslint-code-block>

## Further Reading

* [eslint-plugin-vue - multi-word-component-names](https://eslint.vuejs.org/rules/multi-word-component-names.html)
* [Style guide - Multi-word component names](https://v3.vuejs.org/style-guide/#multi-word-component-names-essential)


text:
using IDI.Central.Core;
using IDI.Central.Domain;
using IDI.Central.Domain.Localization;
using IDI.Core.Common;
using IDI.Core.Common.Extensions;
using IDI.Core.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace IDI.Central
{
    public class Startup
    {
        public IConfigurationRoot Configuration { get; }

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Runtime.Initialize(services);

            // Add framework services.
            services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
                .AddMvcOptions(options => options.Filters.Add<ApplicationExceptionAttribute>());

            services.AddSqlServer<CentralContext>(Configuration.GetConnectionString("DefaultConnection"));

            // Inject an implementation of ISwaggerProvider with defaulted settings applied
            services.AddSwaggerGen();

            #region AllowCORS
            var urls = Configuration[Constants.Policy.AllowCORSDomain].Split(',');
            services.AddCors(options => options.AddPolicy(Constants.Policy.AllowCORSDomain, builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
            services.Configure<MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory(Constants.Policy.AllowCORSDomain)); });
            #endregion

            services.Configure<ApplicationOptions>(Configuration.GetSection("API"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            //loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            //app.UseCookieAuthentication(AuthOptions.CookieOptions());

            app.UseTokenAuthentication<ApplicationAuthenticationProvider>();

            #region Swashbuckle
            // Enable middleware to serve generated Swagger as a JSON endpoint
            app.UseSwagger();

            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            app.UseSwaggerUi();
            #endregion

            app.UseStaticFiles();
            //app.UseMvc();
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            });
            app.UseCors(Constants.Policy.AllowCORSDomain);
            app.UseLanguagePackage<LanguagePackage>();
            app.UseAuthorization<ApplicationAuthorization>();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:id="@+id/mainLayout"
    android:background="@android:color/white">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:background="@drawable/img2">
    </ImageView>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollcontainer"
        android:layout_centerInParent="true">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <EditText
            android:id = "@+id/edit_id"
            android:layout_width = "279.3dp"
            android:layout_height = "wrap_content"
            android:inputType="textEmailAddress"
            android:layout_centerHorizontal="true"
            android:singleLine="true"
            android:textCursorDrawable="@null"
            android:drawableLeft="@drawable/icn_mail_pp"
            android:drawablePadding="@dimen/activity_horizontal_margin"
            android:hint = "Email을 입력해주세요"
            android:textColor="#282455"
            android:textColorHint="#bbbad0"
            android:textSize="12sp"
            android:selectAllOnFocus="true"/>
        <EditText
            android:id = "@+id/edit_pass"
            android:layout_centerInParent="true"
            android:layout_marginTop="42.8dp"
            android:layout_width = "279.3dp"
            android:inputType="textPassword"
            android:textCursorDrawable="@null"
            android:layout_height = "wrap_content"
            android:singleLine="true"
            android:maxLength="12"
            android:drawablePadding="@dimen/activity_horizontal_margin"
            android:drawableLeft="@drawable/icn_pw_pp"
            android:hint = "Password를 입력해주세요"
            android:textColor="#282455"
            android:textColorHint="#bbbad0"
            android:textSize="12sp"
            android:selectAllOnFocus="true"/>
    <EditText
        android:id = "@+id/edit_repass"
        android:layout_below="@+id/edit_pass"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="42.8dp"
        android:layout_width = "279.3dp"
        android:inputType="textPassword"
        android:layout_height = "wrap_content"
        android:singleLine="true"
        android:textCursorDrawable="@null"
        android:maxLength="12"
        android:imeOptions="actionDone"
        android:drawablePadding="@dimen/activity_horizontal_margin"
        android:drawableLeft="@drawable/icn_pw_pp"
        android:hint = "Password를 다시 한 번 더 입력해주세요"
        android:textColor="#282455"
        android:textColorHint="#bbbad0"
        android:textSize="12sp"
        android:selectAllOnFocus="true"/>
        </RelativeLayout>
    </ScrollView>
      <RelativeLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:background="#837af1"
          android:layout_alignParentBottom="true">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_alignParentLeft="true"
            android:onClick="Back"
            android:text="이전"
            android:background="#837af1"
            android:textColor="@android:color/white"
            android:drawableLeft="@drawable/btn_back_active">
        </Button>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:onClick="Next"
            android:text="다음"
            android:background="#837af1"
            android:textColor="@android:color/white"
            android:drawableRight="@drawable/btn_next_active">
        </Button>
  </RelativeLayout>
  </RelativeLayout>


text:
require "thor"

# common
require "me/store"
require "me/registry"
require "me/executor"
require "me/errors"
require "me/error_presenter"

# mappers
require "me/mappers/identity_store2"
require "me/mappers/git_config_store2"
require "me/mappers/ssh_config_store2"

# commands
require "me/cli/whoami_command"
require "me/cli/switch_command"
require "me/cli/activate_command"
require "me/cli/git_config_command"
require "me/cli/ssh_config_command"

# views
require "me/cli/git_not_configured_view"
require "me/cli/ssh_not_configured_view"

module Me
  module Cli
    ERROR_VIEW_FACTORIES = {
      "Me::Errors::GitNotConfigured" => GitNotConfiguredView,
      "Me::Errors::SshNotConfigured" => SshNotConfiguredView,
    }

    Registry.register_kernel(Kernel)
    Registry.register_executor_factory(Executor)
    Registry.register_error_view_factories(ERROR_VIEW_FACTORIES)
    Registry.register_identity_mapper_factory(Me::Mappers::IdentityStore2)
    Registry.register_git_config_mapper_factory(Me::Mappers::GitConfigStore2)
    Registry.register_ssh_config_mapper_factory(Me::Mappers::SshConfigStore2)

    class BaseApp < Thor
      private

      def render(&blk)
        _render(ErrorPresenter.new.call(&blk))
      end

      def _render(views)
        return _render([views]) unless views.is_a?(Array)
        views.map { |v| puts v.to_s }
      end
    end

    class Config < BaseApp
      desc "git NAME [GIT_NAME GIT_EMAIL]", "Configure corresponding git config options. Omit optional params to show current configuration"
      def git(identity, name=nil, email=nil)
        render { GitConfigCommand[identity, name, email].call }
      end

      desc "ssh NAME [SSH_KEYS]", "Configure ssh-agent to use provided ssh keys. Omit optional params to show current configuration"
      def ssh(identity, *keys)
        render { SshConfigCommand[identity, keys].call }
      end
    end

    class App < BaseApp
      desc "whoami", "Show current identity"
      def whoami
        render { WhoamiCommand.new.call }
      end

      desc "switch NAME", "Switch to specified identity"
      def switch(identity)
        render { SwitchCommand[identity].call }
      end

      desc "activate", "Activates configuration for current identity"
      def activate
        render { ActivateCommand.new.call }
      end

      default_task :activate

      desc "config CONFIG_NAME", "Configure identities"
      subcommand "config", Config
    end
  end
end


text:
<?php

namespace Sonata\AdminBundle\Builder;

use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Admin\FieldDescriptionCollection;
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;

/**
 * Interface ListBuilderInterface.
 *
 * @author  Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
interface ListBuilderInterface extends BuilderInterface
{
    /**
     * @param array $options
     *
     * @return FieldDescriptionCollection
     */
    public function getBaseList(array $options = array());

    /**
     * Modify a field description to display it in the list view.
     *
     * @param null|mixed                $type
     * @param FieldDescriptionInterface $fieldDescription
     * @param AdminInterface            $admin
     */
    public function buildField($type, FieldDescriptionInterface $fieldDescription, AdminInterface $admin);

    /**
     * Modify a field description and add it to the displayed columns.
     *
     * @param FieldDescriptionCollection $list
     * @param null|mixed                 $type
     * @param FieldDescriptionInterface  $fieldDescription
     * @param AdminInterface             $admin
     */
    public function addField(FieldDescriptionCollection $list, $type, FieldDescriptionInterface $fieldDescription, AdminInterface $admin);
}


text:
// File generated by OpenXava: Wed Sep 11 11:56:53 CEST 2013
// Archivo generado por OpenXava: Wed Sep 11 11:56:53 CEST 2013

// WARNING: NO EDIT
// OJO: NO EDITAR
// Component: Invoice		Aggregate/Agregado: InvoiceDetail

package org.openxava.test.model;

import java.util.*;
import java.math.*;
import java.rmi.RemoteException;
import org.openxava.component.MetaComponent;
import org.openxava.model.meta.MetaModel;
import org.openxava.util.*;

/**
 *
 * @author MCarmen Gimeno
 */
public class InvoiceDetail implements java.io.Serializable, org.openxava.test.model.IInvoiceDetail {

	// Constructor
	public InvoiceDetail() {
		initMembers();
	}

	private void initMembers() {
		setOid(null);
		setServiceType(0);
		setQuantity(0);
		setUnitPrice(null);
		setDeliveryDate(null);
		setRemarks(null);
	}

	// Properties/Propiedades
	/**
	 *
	 *
	 */
	public boolean isFree() {
		try {
			org.openxava.test.calculators.InvoiceDetailIsFreeCalculator freeCalculator= (org.openxava.test.calculators.InvoiceDetailIsFreeCalculator)
				getMetaModel().getMetaProperty("free").getMetaCalculator().createCalculator();
				freeCalculator.setModel(this);
			return ((Boolean) freeCalculator.calculate()).booleanValue();
		}
		catch (NullPointerException ex) {
			// Usually for multilevel property access with null references
			return false;
		}
		catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.calculate_value_error", "Free", "InvoiceDetail", ex.getLocalizedMessage()));
		}
	}
	public void setFree(boolean newFree) {
		// for it is in value object
		// para que aparezca en los value objects
	}
	/**
	 *
	 *
	 */
	public java.math.BigDecimal getAmount() {
		try {
			org.openxava.test.calculators.DetailAmountCalculator amountCalculator= (org.openxava.test.calculators.DetailAmountCalculator)
				getMetaModel().getMetaProperty("amount").getMetaCalculator().createCalculator();

			amountCalculator.setUnitPrice(getUnitPrice());

			amountCalculator.setQuantity(getQuantity());
			return (java.math.BigDecimal) amountCalculator.calculate();
		}
		catch (NullPointerException ex) {
			// Usually for multilevel property access with null references
			return null;
		}
		catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.calculate_value_error", "Amount", "InvoiceDetail", ex.getLocalizedMessage()));
		}
	}
	public void setAmount(java.math.BigDecimal newAmount) {
		// for it is in value object
		// para que aparezca en los value objects
	}
	private static org.openxava.converters.IConverter unitPriceConverter;
	private org.openxava.converters.IConverter getUnitPriceConverter() {
		if (unitPriceConverter == null) {
			try {
				unitPriceConverter = (org.openxava.converters.IConverter)
					getMetaModel().getMapping().getConverter("unitPrice");
			}
			catch (Exception ex) {
				ex.printStackTrace();
				throw new RuntimeException(XavaResources.getString("generator.create_converter_error", "unitPrice"));
			}

		}
		return unitPriceConverter;
	}
	private java.math.BigDecimal unitPrice;
	private java.math.BigDecimal get_UnitPrice() {
		return unitPrice;
	}
	private void set_UnitPrice(java.math.BigDecimal newUnitPrice) {
		this.unitPrice = newUnitPrice;
	}

	/**
	 *
	 *
	 */
	public java.math.BigDecimal getUnitPrice() {
		try {
			return (java.math.BigDecimal) getUnitPriceConverter().toJava(get_UnitPrice());
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_error", "UnitPrice", "InvoiceDetail", "java.math.BigDecimal"));
		}
	}

	/**
	 *
	 */
	public void setUnitPrice(java.math.BigDecimal newUnitPrice) {
		try {
			set_UnitPrice((java.math.BigDecimal) getUnitPriceConverter().toDB(newUnitPrice));
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_error", "UnitPrice", "InvoiceDetail", "java.math.BigDecimal"));
		}
	}
	private String oid;
	public String getOid() {
		return oid;
	}
	public void setOid(String newOid) {
		this.oid = newOid;
	}
	private static org.openxava.converters.IConverter remarksConverter;
	private org.openxava.converters.IConverter getRemarksConverter() {
		if (remarksConverter == null) {
			try {
				remarksConverter = (org.openxava.converters.IConverter)
					getMetaModel().getMapping().getConverter("remarks");
			}
			catch (Exception ex) {
				ex.printStackTrace();
				throw new RuntimeException(XavaResources.getString("generator.create_converter_error", "remarks"));
			}

		}
		return remarksConverter;
	}
	private java.lang.String remarks;
	private java.lang.String get_Remarks() {
		return remarks;
	}
	private void set_Remarks(java.lang.String newRemarks) {
		this.remarks = newRemarks;
	}

	/**
	 *
	 *
	 */
	public java.lang.String getRemarks() {
		try {
			return (java.lang.String) getRemarksConverter().toJava(get_Remarks());
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_error", "Remarks", "InvoiceDetail", "java.lang.String"));
		}
	}

	/**
	 *
	 */
	public void setRemarks(java.lang.String newRemarks) {
		try {
			set_Remarks((java.lang.String) getRemarksConverter().toDB(newRemarks));
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_error", "Remarks", "InvoiceDetail", "java.lang.String"));
		}
	}
	private static org.openxava.converters.Date3Converter deliveryDateConverter;
	private org.openxava.converters.Date3Converter getDeliveryDateConverter() {
		if (deliveryDateConverter == null) {
			try {
				deliveryDateConverter = (org.openxava.converters.Date3Converter)
					getMetaModel().getMapping().getMultipleConverter("deliveryDate");
			}
			catch (Exception ex) {
				ex.printStackTrace();
				throw new RuntimeException(XavaResources.getString("generator.create_converter_error", "deliveryDate"));
			}

		}
		return deliveryDateConverter;
	}
	private int deliveryDate_day;
	private int getDeliveryDate_day() {
		return deliveryDate_day;
	}
	private void setDeliveryDate_day(int newValue) {
		this.deliveryDate_day = newValue;
	}
	private int deliveryDate_month;
	private int getDeliveryDate_month() {
		return deliveryDate_month;
	}
	private void setDeliveryDate_month(int newValue) {
		this.deliveryDate_month = newValue;
	}
	private int deliveryDate_year;
	private int getDeliveryDate_year() {
		return deliveryDate_year;
	}
	private void setDeliveryDate_year(int newValue) {
		this.deliveryDate_year = newValue;
	}
	/**
	 *
	 *
	 */
	public java.util.Date getDeliveryDate() {
		try {
			getDeliveryDateConverter().setDay(getDeliveryDate_day());
			getDeliveryDateConverter().setMonth(getDeliveryDate_month());
			getDeliveryDateConverter().setYear(getDeliveryDate_year());
			return (java.util.Date) getDeliveryDateConverter().toJava();
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_error", "DeliveryDate", "InvoiceDetail", "java.util.Date"));
		}
	}

	/**
	 *
	 */
	public void setDeliveryDate(java.util.Date newDeliveryDate) {
		try {
			getDeliveryDateConverter().toDB(newDeliveryDate);
			setDeliveryDate_day(getDeliveryDateConverter().getDay());
			setDeliveryDate_month(getDeliveryDateConverter().getMonth());
			setDeliveryDate_year(getDeliveryDateConverter().getYear());
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_db_error", "DeliveryDate", "InvoiceDetail"));
		}
	}
	private static org.openxava.converters.IConverter quantityConverter;
	private org.openxava.converters.IConverter getQuantityConverter() {
		if (quantityConverter == null) {
			try {
				quantityConverter = (org.openxava.converters.IConverter)
					getMetaModel().getMapping().getConverter("quantity");
			}
			catch (Exception ex) {
				ex.printStackTrace();
				throw new RuntimeException(XavaResources.getString("generator.create_converter_error", "quantity"));
			}

		}
		return quantityConverter;
	}
	private java.lang.Integer quantity;
	private java.lang.Integer get_Quantity() {
		return quantity;
	}
	private void set_Quantity(java.lang.Integer newQuantity) {
		this.quantity = newQuantity;
	}

	/**
	 *
	 *
	 */
	public int getQuantity() {
		try {
			return ((Integer) getQuantityConverter().toJava(get_Quantity())).intValue();
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_error", "Quantity", "InvoiceDetail", "int"));
		}
	}

	/**
	 *
	 */
	public void setQuantity(int newQuantity) {
		try {
			set_Quantity((java.lang.Integer) getQuantityConverter().toDB(new Integer(newQuantity)));
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_error", "Quantity", "InvoiceDetail", "int"));
		}
	}
	private static org.openxava.converters.IConverter serviceTypeConverter;
	private org.openxava.converters.IConverter getServiceTypeConverter() {
		if (serviceTypeConverter == null) {
			try {
				serviceTypeConverter = (org.openxava.converters.IConverter)
					getMetaModel().getMapping().getConverter("serviceType");
			}
			catch (Exception ex) {
				ex.printStackTrace();
				throw new RuntimeException(XavaResources.getString("generator.create_converter_error", "serviceType"));
			}

		}
		return serviceTypeConverter;
	}
	private java.lang.Integer serviceType;
	private java.lang.Integer get_ServiceType() {
		return serviceType;
	}
	private void set_ServiceType(java.lang.Integer newServiceType) {
		this.serviceType = newServiceType;
	}

	/**
	 *
	 *
	 */
	public int getServiceType() {
		try {
			return ((Integer) getServiceTypeConverter().toJava(get_ServiceType())).intValue();
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_error", "ServiceType", "InvoiceDetail", "int"));
		}
	}

	/**
	 *
	 */
	public void setServiceType(int newServiceType) {
		try {
			set_ServiceType((java.lang.Integer) getServiceTypeConverter().toDB(new Integer(newServiceType)));
		}
		catch (org.openxava.converters.ConversionException ex) {
			ex.printStackTrace();
			throw new RuntimeException(XavaResources.getString("generator.conversion_error", "ServiceType", "InvoiceDetail", "int"));
		}
	}

	// References/Referencias

	private org.openxava.test.model.IProduct product;
	public org.openxava.test.model.IProduct getProduct() {
		if (product != null) {
			// Because not-found='ignore' annul lazy initialization, we simulate it
			try {
				product.toString();
			}
			catch (Exception ex) {
				return null;
			}
		}
		return product;
	}
	public void setProduct(org.openxava.test.model.IProduct newProduct) {
		if (newProduct != null && !(newProduct instanceof org.openxava.test.model.Product)) {
			throw new IllegalArgumentException(XavaResources.getString("ejb_to_pojo_illegal"));
		}
		this.product = newProduct;
	}

	private org.openxava.test.model.ISeller soldBy;
	public org.openxava.test.model.ISeller getSoldBy() {
		if (soldBy != null) {
			// Because not-found='ignore' annul lazy initialization, we simulate it
			try {
				soldBy.toString();
			}
			catch (Exception ex) {
				return null;
			}
		}
		return soldBy;
	}
	public void setSoldBy(org.openxava.test.model.ISeller newSeller) {
		if (newSeller != null && !(newSeller instanceof org.openxava.test.model.Seller)) {
			throw new IllegalArgumentException(XavaResources.getString("ejb_to_pojo_illegal"));
		}
		this.soldBy = newSeller;
	}

	private org.openxava.test.model.IInvoice invoice;
	public org.openxava.test.model.IInvoice getInvoice() {
		if (invoice != null) {
			// Because not-found='ignore' annul lazy initialization, we simulate it
			try {
				invoice.toString();
			}
			catch (Exception ex) {
				return null;
			}
		}
		return invoice;
	}
	public void setInvoice(org.openxava.test.model.IInvoice newInvoice) {
		if (newInvoice != null && !(newInvoice instanceof org.openxava.test.model.Invoice)) {
			throw new IllegalArgumentException(XavaResources.getString("ejb_to_pojo_illegal"));
		}
		this.invoice = newInvoice;
	}

	// Colecciones/Collections

	// Methods/Metodos

	// User defined finders/Buscadores definidos por el usuario

	private static MetaModel metaModel;
	public MetaModel getMetaModel() throws XavaException {
		if (metaModel == null) {
			metaModel = MetaComponent.get("Invoice").getMetaAggregate("InvoiceDetail");
		}
		return metaModel;
	}

	public String toString() {
		try {
			return getMetaModel().toString(this);
		}
		catch (XavaException ex) {
			System.err.println(XavaResources.getString("toString_warning", "InvoiceDetail"));
			return super.toString();
		}
	}

	public boolean equals(Object other) {
		if (other == null) return false;
		return toString().equals(other.toString());
	}

	public int hashCode() {
		return toString().hashCode();
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Müller & Arx, Beitr. Kryptfl. Schweiz 11(no. 2): 158 (1962)

#### Original name
Dialacenium cissi Syd.

### Remarks
null