text:
NSString * const TMLBundleVersionFilename = @"snapshot.json";
NSString * const TMLBundleApplicationFilename = @"application.json";
NSString * const TMLBundleSourcesFilename = @"sources.json";
NSString * const TMLBundleTranslationsFilename = @"translations.json";
NSString * const TMLBundleTranslationKeysFilename = @"translation_keys.json";
NSString * const TMLBundleLanguageFilename = @"language.json";
NSString * const TMLBundleSourcesRelativePath = @"sources";

NSString * const TMLBundleVersionKey = @"version";
NSString * const TMLBundleURLKey = @"url";

NSString * const TMLBundleErrorDomain = @"TMLBundleErrorDomain";
NSString * const TMLBundleErrorResourcePathKey = @"resourcePath";
NSString * const TMLBundleErrorsKey = @"errors";

@interface TMLBundle()
@property (readwrite, nonatomic) NSString *version;
@property (readwrite, nonatomic) NSString *path;
@property (readwrite, nonatomic) NSArray *languages;
@property (readwrite, nonatomic) NSMutableDictionary *translations;
@property (readwrite, nonatomic) NSArray *availableLocales;
@property (readwrite, nonatomic) NSMutableDictionary *availableLanguages;
@property (readwrite, nonatomic) NSArray *locales;
@property (readwrite, nonatomic) TMLApplication *application;
@property (readwrite, nonatomic) NSArray *sources;
@property (readwrite, nonatomic) NSDictionary *translationKeys;
@property (readwrite, nonatomic) NSURL *sourceURL;
@end

@implementation TMLBundle

+ (instancetype)mainBundle {
    return [[TMLBundleManager defaultManager] latestBundle];
}

+ (instancetype)apiBundle {
    return [[TMLBundleManager defaultManager] apiBundle];
}

+ (instancetype)bundleWithVersion:(NSString *)version {
    TMLBundleManager *manager = [TMLBundleManager defaultManager];
    TMLBundle *bundle = [manager registeredBundleWithVersion:version];
    if (bundle != nil) {
        return bundle;
    }
    return [manager installedBundleWithVersion:version];
}

- (instancetype)initWithContentsOfDirectory:(NSString *)path {
    if (self = [super init]) {
        self.path = path;
        _translations = [NSMutableDictionary dictionary];
        _availableLanguages = [NSMutableDictionary dictionary];
        TMLBundleManager *manager = [TMLBundleManager defaultManager];
        [manager registerBundle:self];
    }
    return self;
}

- (BOOL)isEqual:(id)object {
    if (self == object) {
        return YES;
    }
    else if ([object isKindOfClass:[TMLBundle class]] == NO) {
        return NO;
    }
    return [self isEqualToBundle:object];
}

- (BOOL)isEqualToBundle:(TMLBundle *)bundle {
    return [self.version isEqualToString:bundle.version] && [self.path isEqualToString:bundle.path];
}

- (NSUInteger)hash {
    return [[NSString stringWithFormat:@"%@%@", self.version, self.path] hash];
}

- (BOOL)isMutable {
    return NO;
}

- (void)resetData {
    self.languages = nil;
    self.sources = nil;
    self.application = nil;
    self.version = nil;
    self.sourceURL = nil;
    self.availableLocales = nil;
    self.translationKeys = nil;
    self.translations = nil;
}

- (void)reloadVersionInfo {
    NSString *path = [self.path stringByAppendingPathComponent:TMLBundleVersionFilename];
    NSData *versionData = [NSData dataWithContentsOfFile:path];
    NSDictionary *versionInfo = [versionData tmlJSONObject];
    if (versionInfo == nil) {
        TMLWarn(@"Cannot find bundle version at path: %@", path);
        return;
    }
    self.version = versionInfo[TMLBundleVersionKey];
    self.sourceURL = [NSURL URLWithString:versionInfo[TMLBundleURLKey]];
}

- (void)reloadApplicationData {
    NSString *path = [self.path stringByAppendingPathComponent:TMLBundleApplicationFilename];
    NSData *applicationData = [NSData dataWithContentsOfFile:path];
    NSDictionary *applicationInfo = [applicationData tmlJSONObject];
    if (applicationInfo == nil) {
        TMLWarn(@"Cannot find application info at path: %@", path);
        return;
    }
    self.application = [TMLAPISerializer materializeObject:applicationInfo
                                                 withClass:[TMLApplication class]];
}

- (void)reloadSourcesData {
    NSString *path = [self.path stringByAppendingPathComponent:TMLBundleSourcesFilename];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSArray *sources = [data tmlJSONObject];
    if (sources == nil) {
        TMLWarn(@"Cannot find sources defintion at path: %@", path);
        self.sources = @[];
    }
    else {
        self.sources = sources;
    }
}

- (void)reloadTranslationKeysData {
    NSString *path = [self.path stringByAppendingPathComponent:TMLBundleTranslationKeysFilename];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSArray *keysArray = [data tmlJSONObject][TMLAPIResponseResultsKey];
    if (keysArray == nil) {
        TMLWarn(@"Cannot find translation keys definition at path: %@", path);
        self.translationKeys = @{};
        return;
    }
    keysArray = [TMLAPISerializer materializeObject:keysArray withClass:[TMLTranslationKey class]];
    NSMutableDictionary *keys = [NSMutableDictionary dictionary];
    for (TMLTranslationKey *translationKey in keysArray) {
        keys[translationKey.key] = translationKey;
    }
    self.translationKeys = keys;
}

- (void)reloadAvailableLocales {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:self.path error:&error];
    NSMutableArray *locales = [NSMutableArray array];
    if (contents == nil) {
        TMLError(@"Error listing available bundle locales: %@", error);
    }
    else {
        BOOL isDir = NO;
        for (NSString *path in contents) {
            if ([fileManager fileExistsAtPath:[self.path stringByAppendingPathComponent:path] isDirectory:&isDir] == YES
                && isDir == YES) {
                [locales addObject:[path lastPathComponent]];
            }
        }
    }
    self.availableLocales = locales;
}

#pragma mark - Accessors

- (NSString *)version {
    if (_version == nil) {
        [self reloadVersionInfo];
    }
    return _version;
}

- (NSURL *)sourceURL {
    if (_sourceURL == nil) {
        [self reloadVersionInfo];
    }
    return _sourceURL;
}

- (TMLApplication *)application {
    if (_application == nil) {
        [self reloadApplicationData];
    }
    return _application;
}

- (NSArray *)sources {
    if (_sources == nil) {
        [self reloadSourcesData];
    }
    return _sources;
}

- (NSDictionary *)translationKeys {
    if (_translationKeys == nil) {
        [self reloadTranslationKeysData];
    }
    return _translationKeys;
}

- (NSArray *)availableLocales {
    if (_availableLocales == nil) {
        [self reloadAvailableLocales];
    }
    return _availableLocales;
}

- (NSArray *)locales {
    NSArray *langs = self.languages;
    return [langs valueForKeyPath:@"locale"];
}

- (NSArray *)languages {
    TMLApplication *app = self.application;
    return app.languages;
}

#pragma mark - Languages

- (TMLLanguage *)languageForLocale:(NSString *)locale {
    TMLLanguage *lang = _availableLanguages[locale];
    if (lang == nil) {
        [self loadLocalLanguageForLocale:locale];
    }
    lang = _availableLanguages[locale];
    return lang;
}

- (void)loadLocalLanguageForLocale:(NSString *)locale {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *languageFilePath = [[self.path stringByAppendingPathComponent:locale] stringByAppendingPathComponent:TMLBundleLanguageFilename];
    if ([fileManager fileExistsAtPath:languageFilePath] == NO) {
        TMLDebug(@"Cannot find %@ for locale '%@'", TMLBundleLanguageFilename, locale);
        return;
    }
    NSData *data = [NSData dataWithContentsOfFile:languageFilePath];
    if (data == nil) {
        TMLError(@"Failed to load %@ for locale '%@'", TMLBundleLanguageFilename, locale);
        return;
    }
    TMLLanguage *lang = [TMLAPISerializer materializeData:data withClass:[TMLLanguage class]];
    if (lang == nil) {
        TMLError(@"Failed to materialize %@ for locale '%@'", TMLBundleLanguageFilename, locale);
    }
    else {
        _availableLanguages[locale] = lang;
    }
}

#pragma mark - Translations

- (NSString *)translationsPathForLocale:(NSString *)locale {
    return [[self.path stringByAppendingPathComponent:locale] stringByAppendingPathComponent:TMLBundleTranslationsFilename];
}

- (BOOL)hasLocaleTranslationsForLocale:(NSString *)locale {
    if (_translations[locale] != nil) {
        return YES;
    }

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *basePath = [self.path stringByAppendingPathComponent:locale];

    NSString *languageFilePath = [basePath stringByAppendingPathComponent:TMLBundleLanguageFilename];
    NSString *translationsFilePath = [basePath stringByAppendingPathComponent:TMLBundleTranslationsFilename];
    return ([fileManager fileExistsAtPath:languageFilePath] == YES
            && [fileManager fileExistsAtPath:translationsFilePath] == YES);
}

- (NSDictionary *)translationsForLocale:(NSString *)locale {
    NSDictionary *translations = _translations[locale];
    if (translations == nil) {
        [self loadLocalTranslationsForLocale:locale];
        translations = _translations[locale];
    }
    return translations;
}

- (void)loadLocalTranslationsForLocale:(NSString *)aLocale {
    NSString *locale = [aLocale lowercaseString];
    NSArray *availableLocales = self.availableLocales;
    NSString *translationsPath;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([availableLocales containsObject:locale] == YES) {
        translationsPath = [self translationsPathForLocale:locale];
        if ([fileManager fileExistsAtPath:translationsPath] == NO) {
            translationsPath = nil;
        }
    }
    if (translationsPath != nil) {
        NSMutableDictionary *translations = [NSMutableDictionary dictionary];
        NSData *data = [NSData dataWithContentsOfFile:translationsPath];
        NSDictionary *info = [data tmlJSONObject];
        if (info[TMLAPIResponseResultsKey] != nil) {
            info = info[TMLAPIResponseResultsKey];
        }

        for (NSString *key in info) {
            NSArray *translationsList = nil;
            if ([info[key] isKindOfClass:[NSArray class]] == YES) {
                translationsList = info[key];
            }
            else if ([info[key] isKindOfClass:[NSDictionary class]] == YES) {
                translationsList = info[key][TMLAPIResponseResultsTranslationsKey];
            }
            if (translationsList.count > 0) {
                NSArray *newTranslations = [TMLAPISerializer materializeObject:translationsList
                                                                     withClass:[TMLTranslation class]];
                translations[key] = newTranslations;
            }
            // associate translations with translation key and locale
            for (TMLTranslation *translation in translations[key]) {
                translation.locale = aLocale;
                translation.translationKey = key;
            }
        }

        if (_translations == nil) {
            _translations = [NSMutableDictionary dictionary];
        }
        _translations[locale] = [translations copy];
    }
}

- (void)loadTranslationsForLocale:(NSString *)aLocale
                       completion:(void(^)(NSError *error))completion
{
    NSString *locale = [aLocale lowercaseString];
    NSDictionary *loadedTranslations = [self translationsForLocale:locale];
    if (loadedTranslations != nil) {
        if (completion != nil) {
            completion(nil);
        }
        return;
    }

    NSString *version = self.version;
    NSMutableArray *paths = [NSMutableArray array];
    NSArray *sources = [self sources];
    [paths addObject:[locale stringByAppendingPathComponent:TMLBundleLanguageFilename]];
    [paths addObject:[locale stringByAppendingPathComponent:TMLBundleTranslationsFilename]];
    for (NSString *source in sources) {
        [paths addObject:[[locale stringByAppendingPathComponent:TMLBundleSourcesRelativePath] stringByAppendingPathComponent:[source stringByAppendingPathExtension:@"json"]]];
    }

    [[TMLBundleManager defaultManager] fetchPublishedResources:paths
                                                 bundleVersion:version
                                                 baseDirectory:nil
                                               completionBlock:^(BOOL success, NSArray *paths, NSArray *errors) {
                                                       if (success == YES && paths.count > 0) {
                                                           [self installResources:paths completion:completion];
                                                       }
                                                       else if (completion != nil) {
                                                           NSDictionary *errorInfo = @{
                                                                                TMLBundleErrorsKey: errors
                                                                                };
                                                           NSError *ourError = [NSError errorWithDomain:TMLBundleErrorDomain
                                                                                code:TMLBundleMissingResources
                                                                                userInfo:errorInfo];
                                                           completion(ourError);
                                                       }
                                               }];
}

#pragma mark - Translation Keys

- (NSArray *)translationKeysMatchingString:(NSString *)string
                                    locale:(NSString *)locale
{
    if (string == nil) {
        return nil;
    }

    NSMutableArray *foundKeys = [NSMutableArray array];
    NSDictionary *translationKeys = self.translationKeys;
    for (NSString *key in translationKeys) {
        TMLTranslationKey *translationKey = translationKeys[key];
        if ([string isEqualToString:translationKey.label] == YES
            && [locale isEqualToString:translationKey.locale] == YES) {
            [foundKeys addObject:translationKey.key];
        }
    }

    if (foundKeys.count == 0) {
        NSDictionary *translations = [self translationsForLocale:locale];
        for (NSString *key in translations) {
            for (TMLTranslation *translation in translations[key]) {
                if ([translation.label isEqualToString:string] == NO) {
                    continue;
                }
                [foundKeys addObject:key];
            }
        }
    }
    return (foundKeys.count > 0) ? [foundKeys copy] : nil;
}

#pragma mark - Synchronization

- (void)loadCompleteBundle:(void(^)(NSError *error))completion {
    NSURL *url = self.sourceURL;
    TMLBundleManager *manager = [TMLBundleManager defaultManager];
    [manager installBundleFromURL:url completionBlock:^(NSString *path, NSError *error) {
        if (path != nil) {
            TMLInfo(@"Bundle successfully synchronized: %@", path);
        }
        else {
            TMLError(@"Bundle failed to synchronize: %@", error);
        }
        if (completion != nil) {
            completion(error);
        }
    }];
}

- (void)loadMetaData:(void(^)(NSError *error))completion {
    NSString *version = self.version;
    NSArray *paths = @[
                       TMLBundleApplicationFilename,
                       TMLBundleSourcesFilename,
                       TMLBundleVersionFilename
                       ];

    [[TMLBundleManager defaultManager] fetchPublishedResources:paths
                                                 bundleVersion:version
                                                 baseDirectory:nil
                                               completionBlock:^(BOOL success, NSArray *paths, NSArray *errors) {
                                                   [self installResources:paths completion:^(NSError *error) {
                                                       if (completion != nil) {
                                                           completion(error);
                                                       }
                                                   }];
                                               }];
}

#pragma mark - Resources

- (void)installResources:(NSArray *)resourcePaths
              completion:(void(^)(NSError *))completion
{
    if (resourcePaths.count == 0) {
        if (completion != nil) {
            completion(nil);
        }
        return;
    }

    __block NSInteger count = 0;
    NSString *version = self.version;
    TMLBundleManager *bundleManager = [TMLBundleManager defaultManager];
    __block NSMutableArray *allErrors = [NSMutableArray array];

    for (NSString *path in resourcePaths) {
        NSArray *pathComponents = [path pathComponents];
        NSInteger index = [pathComponents indexOfObject:version];
        NSString *relativePath = nil;
        if (index < pathComponents.count - 1) {
            relativePath = [NSString pathWithComponents:[pathComponents subarrayWithRange:NSMakeRange(index+1, pathComponents.count - index - 1)]];
        }
        if (relativePath == nil) {
            NSError *installError = [NSError errorWithDomain:TMLBundleErrorDomain
                                                        code:TMLBundleInvalidResourcePath
                                                    userInfo:@{
                                                               TMLBundleErrorResourcePathKey: path
                                                               }];
            [allErrors addObject:installError];
            continue;
        }
        [bundleManager installResourceFromPath:path
                        withRelativeBundlePath:relativePath
                             intoBundleVersion:version
                               completionBlock:^(NSString *path, NSError *error) {
                                   count++;
                                   if (error != nil) {
                                       [allErrors addObject:error];
                                   }
                                   if (count == resourcePaths.count) {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           [self resetData];
                                           if ([[TML sharedInstance] currentBundle] == self) {
                                               [[TMLBundleManager defaultManager] notifyBundleMutation:TMLLocalizationDataChangedNotification
                                                                                bundle:self
                                                                                errors:allErrors];
                                           }
                                           if (completion != nil) {
                                               completion((allErrors.count > 0) ? [allErrors firstObject] : nil);
                                           }
                                       });
                                   }
                               }];
    }
}

#pragma mark -
- (BOOL)isValid {
    NSString *ourPath = [self path];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *fileNames = @[TMLBundleApplicationFilename, TMLBundleSourcesFilename];
    for (NSString *fileName in fileNames) {
        NSString *path = [ourPath stringByAppendingPathComponent:fileName];
        if ([fileManager fileExistsAtPath:path] == NO) {
            return NO;
        }
    }
    return YES;
}

#pragma mark -
- (NSString *)description {
    return [NSString stringWithFormat:@"<%@:%@: %p>", [self class], self.version, self];
}

@end


text:
module Alchemy
  # This helpers are useful to render elements from pages.
  #
  # The most important helper for frontend developers is the {#render_elements} helper.
  #
  module ElementsHelper
    include Alchemy::EssencesHelper
    include Alchemy::UrlHelper
    include Alchemy::ElementsBlockHelper

    # Renders all elements from current page
    #
    # == Examples:
    #
    # === Render only certain elements:
    #
    #
    #     <%= render_elements only: ['header', 'claim'] %>
    #
    #

    #     <%= render_elements except: ['header', 'claim'] %>
    #

    #
    # === Render elements from global page:
    #
    #
    #     <%= render_elements from_page: 'footer' %>
    #
    #
    # === Render elements from cell:
    #
    #
    #     <%= render_elements from_cell: 'sidebar' %>
    #
    #
    # === Fallback to elements from global page:
    #
    # You can use the fallback option as an override for elements that are stored on another page.
    # So you can take elements from a global page and only if the user adds an element on current page the
    # local one gets rendered.
    #
    # 1. You have to pass the the name of the element the fallback is for as <tt>for</tt> key.
    # 2. You have to pass a <tt>page_layout</tt> name or {Alchemy::Page} from where the fallback elements is taken from as <tt>from</tt> key.
    # 3. You can pass the name of element to fallback with as <tt>with</tt> key. This is optional (the element name from the <tt>for</tt> key is taken as default).
    #
    #   <%= render_elements(fallback: {
    #     for: 'contact_teaser',
    #     from: 'sidebar',
    #     with: 'contact_teaser'
    #   }) %>
    #
    # @param [Hash] options
    #   Additional options.
    #
    # @option options [Number] :count
    #   The amount of elements to be rendered (begins with first element found)
    # @option options [Array or String] :except ([])
    #   A list of element names not to be rendered.
    # @option options [Hash] :fallback
    #   Define elements that are rendered from another page.
    # @option options [Alchemy::Cell or String] :from_cell
    #   The cell the elements are rendered from. You can pass a {Alchemy::Cell} name String or a {Alchemy::Cell} object.
    # @option options [Alchemy::Page or String] :from_page (@page)
    #   The page the elements are rendered from. You can pass a page_layout String or a {Alchemy::Page} object.
    # @option options [Array or String] :only ([])
    #   A list of element names only to be rendered.
    # @option options [Boolean] :random
    #   Randomize the output of elements
    # @option options [Boolean] :reverse
    #   Reverse the rendering order
    # @option options [String] :sort_by
    #   The name of a {Alchemy::Content} to sort the elements by
    # @option options [String] :separator
    #   A string that will be used to join the element partials. Default nil
    #
    def render_elements(options = {})
      options = {
        from_page: @page,
        render_format: 'html'
      }.update(options)

      pages = pages_holding_elements(options.delete(:from_page))

      if pages.blank?
        warning('No page to get elements from was found')
        return
      end

      elements = collect_elements_from_pages(pages, options)

      if options[:sort_by].present?
        elements = sort_elements_by_content(elements, options.delete(:sort_by))
      end

      render_element_view_partials(elements, options)
    end

    # This helper renders a {Alchemy::Element} partial.
    #
    # A element has always two partials:
    #
    # 1. A view partial (This is the view presented to the website visitor)
    # 2. A editor partial (This is the form presented to the website editor while in page edit mode)
    #
    # The partials are located in <tt>app/views/alchemy/elements</tt>.
    #
    # == View partial naming
    #
    # The partials have to be named after the name of the element as defined in the <tt>elements.yml</tt> file and has to be suffixed with the partial part.
    #
    # === Example
    #
    # Given a headline element
    #
    #   # elements.yml
    #   - name: headline
    #     contents:
    #     - name: text
    #       type: EssenceText
    #
    # Then your element view partials has to be named like:
    #
    #   app/views/alchemy/elements/_headline_editor.html.erb
    #   app/views/alchemy/elements/_headline_view.html.erb
    #
    # === Element partials generator
    #
    # You can use this handy generator to let Alchemy generate the partials for you:
    #
    #   $ rails generate alchemy:elements --skip
    #
    # == Usage
    #
    #   <%= render_element(Alchemy::Element.published.named(:headline).first) %>
    #
    # @param [Alchemy::Element] element
    #   The element you want to render the view for
    # @param [Symbol] part
    #   The type of element partial (<tt>:editor</tt> or <tt>:view</tt>) you want to render
    # @param [Hash] options
    #   Additional options
    # @param [Number] counter
    #   a counter
    #
    # @note If the view partial is not found <tt>alchemy/elements/_view_not_found.html.erb</tt>
    #   or <tt>alchemy/elements/_editor_not_found.html.erb</tt> gets rendered.
    #
    def render_element(element, part = :view, options = {}, counter = 1)
      if element.nil?
        warning('Element is nil')
        render "alchemy/elements/#{part}_not_found", {name: 'nil'}
        return
      end

      element.store_page(@page) if part.to_sym == :view

      render "alchemy/elements/#{element.name}_#{part}", {
        element: element,
        counter: counter,
        options: options
      }.merge(options.delete(:locals) || {})

    rescue ActionView::MissingTemplate => e
      warning(%(
        Element #{part} partial not found for #{element.name}.\n
        #{e}
      ))
      render "alchemy/elements/#{part}_not_found", {
        name: element.name,
        error: "Element #{part} partial not found.
Use rails generate alchemy:elements to generate it."
      }
    end

    # Returns a string for the id attribute of a html element for the given element
    def element_dom_id(element)
      return "" if element.nil?
      "#{element.name}_#{element.id}".html_safe
    end

    # Renders the HTML tag attributes required for preview mode.
    def element_preview_code(element)
      tag_options(element_preview_code_attributes(element))
    end

    # Returns a hash containing the HTML tag attributes required for preview mode.
    def element_preview_code_attributes(element)
      return {} unless element.present? && @preview_mode && element.page == @page
      { :'data-alchemy-element' => element.id }
    end

    # Returns the element's tags information as a string. Parameters and options
    # are equivalent to {#element_tags_attributes}.
    #
    # @see #element_tags_attributes
    #
    # @return [String]
    #   HTML tag attributes containing the element's tag information.
    #
    def element_tags(element, options = {})
      tag_options(element_tags_attributes(element, options))
    end

    # Returns the element's tags information as an attribute hash.
    #
    # @param [Alchemy::Element] element The {Alchemy::Element} you want to render the tags from.
    #
    # @option options [Proc] :formatter
    #   ('lambda { |tags| tags.join(' ') }')
    #   Lambda converting array of tags to a string.
    #
    # @return [Hash]
    #   HTML tag attributes containing the element's tag information.
    #
    def element_tags_attributes(element, options = {})
      options = {
        formatter: lambda { |tags| tags.join(' ') }
      }.merge(options)

      return {} if !element.taggable? || element.tag_list.blank?
      { :'data-element-tags' => options[:formatter].call(element.tag_list) }
    end

    # Sort given elements by content.
    #
    # @param [Array] elements - The elements you want to sort
    # @param [String] content_name - The name of the content you want to sort by
    #
    # @return [Array]
    #
    def sort_elements_by_content(elements, content_name)
      elements.sort_by do |element|
        content = element.content_by_name(content_name)
        content ? content.ingredient.to_s : ''
      end
    end

    private

    def pages_holding_elements(page)
      case page
      when String
        Language.current.pages.where(
          page_layout: page,
          restricted: false
        ).to_a
      when Page
        page
      end
    end

    def collect_elements_from_pages(page, options)
      if page.is_a? Array
        elements = page.collect { |p| p.find_elements(options) }.flatten
      else
        elements = page.find_elements(options)
      end
      if fallback_required?(elements, options)
        elements += fallback_elements(options)
      end
      elements
    end

    def fallback_required?(elements, options)
      options[:fallback] && elements.detect { |e| e.name == options[:fallback][:for] }.nil?
    end

    def fallback_elements(options)
      fallback_options = options.delete(:fallback)
      case fallback_options[:from]
      when String
        page = Language.current.pages.find_by(
          page_layout: fallback_options[:from],
          restricted: false
        )
      when Page
        page = fallback_options[:from]
      end
      return [] if page.blank?
      page.elements.named(fallback_options[:with].blank? ? fallback_options[:for] : fallback_options[:with])
    end

    def render_element_view_partials(elements, options = {})
      buff = []
      elements.each_with_index do |element, i|
        buff << render_element(element, :view, options, i + 1)
      end
      buff.join(options[:separator]).html_safe
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE ScopedTypeVariables #-}
module FOmega.SubSig where

import Prelude hiding (mapM)
import Control.Lens
import Control.Monad (MonadPlus, zipWithM)

import Data.Traversable (Traversable(..))

import qualified Data.Map as M

import Unbound.Generics.LocallyNameless (LFresh(..))
import qualified Unbound.Generics.LocallyNameless as U

import Insomnia.Common.FreshName

import FOmega.Syntax
import FOmega.SemanticSig
import FOmega.MatchSigs (matchSubst, matchSubsts)

-- | A coercion is a closed term of function type.
-- As it turns out, many coercions are just the identity function, so
-- do a bit of simplifications as we go.
-- (We could do even better if we represented composite coercions as values of this datatype.
--  For example if we saw  (DistCoer (IdCoer ty)) we could replace it by IdCoer (TDist ty)
--  instead of the more cumbersome  "λ x : Dist ty . let s ~ coerce@(id ty) x in return s"
--  But we get a lot of mileage just out of the id/non-id distinction and substitution of
--  coercion arguments for coercion results.)
data Coercion =
  IdCoer Type
  | LamCoer (U.Bind (Var, U.Embed Type) Term)

coercionTerm :: Coercion -> Term
coercionTerm (IdCoer ty) = idCoerTerm ty
coercionTerm (LamCoer bnd) = Lam bnd

-- λ x : τ . x
idCoerTerm :: Type -> Term
idCoerTerm t =
  let x = U.s2n "x"
  in Lam $ U.bind (x, U.embed t) $ V x

applyCoercion :: Coercion -> Term -> Term
applyCoercion (IdCoer _ty) m = m
applyCoercion (LamCoer bnd) m =
  U.runLFreshM $
  U.avoid (toListOf U.fvAny m) $
  U.lunbind bnd $ \ ((v, _ty), body) ->
  return (U.subst v m body)

-- given f : τ → σ , g : ρ → τ construct λ x : ρ . f (g x)) : ρ → σ
composeCoer :: Coercion -> Coercion -> Type -> Coercion
composeCoer f g t =
  let x = U.s2n "x"
  in LamCoer $ U.bind (x, U.embed t) $ f `applyCoercion` (g `applyCoercion` (V x))

coercion :: LFresh m => Type -> (Term -> m Term) -> m Coercion
coercion t f = do
  x <- U.lfresh $ U.s2n "x"
  e <- U.avoid [U.AnyName x] $ f (V x)
  return $ LamCoer $ U.bind (x, U.embed t) e

-- Λ α : κ → ⋆. λ x : α τ . x
reflFun :: LFresh m => Type -> Kind -> m Term
reflFun t k = do
  a <- U.lfresh $ U.s2n "α"
  let knd = k `KArr` KType
      typ = TV a `TApp` t
  return $ PLam $ U.bind (a, U.embed knd) $ coercionTerm $ IdCoer typ

valSemTerm :: Term -> Term
valSemTerm e = Record [(FVal, e)]

typeSemTerm :: LFresh m => Type -> Kind -> m Term
typeSemTerm t k = do
  m <- reflFun t k
  return $ Record [(FType, m)]

sigSemTerm :: LFresh m => AbstractSig -> m Term
sigSemTerm a = do
  t <- embedAbstractSig a
  return $ Record [(FSig, coercionTerm $ IdCoer t)]

termSubtyping :: LFresh m => Type -> Type -> m Coercion
termSubtyping lhs _rhs = do
  -- TODO:
  --  eq <- tyEquiv lhs rhs KType
  -- guard eq
  return $ IdCoer lhs

sigSubtyping :: (MonadPlus m, LFresh m) => SemanticSig -> SemanticSig -> m Coercion
sigSubtyping lhs rhs = do
  lhsTy <- embedSemanticSig lhs
  case (lhs, rhs) of
   (ValSem tl, ValSem tr) -> do
     f <- termSubtyping tl tr
     coercion lhsTy $ \x -> return $ valSemTerm (applyCoercion f (x `Proj` FVal))
   (TypeSem _tl _kl, TypeSem _tr _kr) -> do
     -- TODO:
     -- eq <- tyEquiv tl tr kl
     -- guard eq
     return $ IdCoer lhsTy
   (SigSem sl, SigSem sr) -> do
     _f1 <- abstractSigSubtyping sl sr
     _f2 <- abstractSigSubtyping sr sl
     coercion lhsTy $ \_x -> sigSemTerm sr
   (DataSem {}, DataSem {}) -> return (IdCoer lhsTy)
   (DataSem {} , TypeSem tr kr) ->
     coercion lhsTy $ \_dk -> typeSemTerm tr kr
   (ModSem modl, ModSem modr) -> do
     -- check that keys of modr are a subset of the keys of modl,
     -- so the intersection of the keys is in fact the rhs
     let ml = M.fromList modl
         mr = M.fromList modr
         m = M.intersectionWith (\x y -> (x, y)) ml mr
     m' <- mapM (uncurry sigSubtyping) m
     coercion lhsTy $ \x -> do
       let rs = M.mapWithKey (\fld coer -> applyCoercion coer (x `Proj` fld)) m'
       return $ Record $ M.toList rs
   (FunctorSem bndl, FunctorSem bndr) ->
     functorSubtyping bndl bndr
   (ModelSem absL, ModelSem absR) ->
     modelSubtyping absL absR
   (_, _) -> fail ("internal error: sigSubtyping of unequal signatures " ++ show lhs ++ " vs " ++ show rhs)

abstractSigSubtyping :: (MonadPlus m, LFresh m) => AbstractSig -> AbstractSig -> m Coercion
abstractSigSubtyping lhs@(AbstractSig bndl) rhs@(AbstractSig rhsBndl) = do
  lhsTy <- embedAbstractSig lhs
  U.lunbind bndl $ \(tvks, sigl) -> do
    -- extend environment
    (sigr, taus) <- matchSubst sigl rhs
    coer <- sigSubtyping sigl sigr
    coercion lhsTy $ \x -> do
      y <- U.lfresh (U.s2n "y")
      U.lunbind rhsBndl $ \(rhsVs, rhsSig) -> do
        rhsTy <- embedSemanticSig rhsSig
        let ep = (rhsVs, rhsTy)
        U.avoid [U.AnyName y]
          $ unpacks (map fst tvks) y x
          $ packs taus (applyCoercion coer $ V y) ep

-- |   ⊢ ∀αs . Σs → Ξ ≤ ∀αs'. Σs' → Ξ' ⇝ f'
--
--   αs' ⊢ Σs' ≤ ∃αs . Σs ↑ τs ⇝ χs
--
--   αs' ⊢ Ξ[τs/αs] ≤ Ξ' ⇝ χbody
--
-- where f' = λf:(∀αs.Σs→Ξ).
--             Λ αs . λ y1:Σ1' . … λ yN:Σn' .
--               χbody (f [τs] (χ1 y1) ⋯ (χN yN))
functorSubtyping :: forall m . (MonadPlus m, LFresh m)
                    => (U.Bind [(TyVar, U.Embed Kind)] SemanticFunctor)
                    -> (U.Bind [(TyVar, U.Embed Kind)] SemanticFunctor)
                    -> m Coercion
functorSubtyping bndl bndr =
  U.lunbind bndr $ \(tvksr, (SemanticFunctor rhsArgs rhsBodySig)) -> do
    -- (extend environment)

    lhsTy <- embedSemanticFunctor bndl
    rhsArgTys <- mapM embedSemanticSig rhsArgs

    -- (χ1, ..., χn), τs, χbody
    (coerArgs, taus, coerBody) <- U.lunbind bndl $ \(tvksl, (SemanticFunctor lhsArgs lhsBodySig)) -> do
      let alphas = map fst tvksl
      (lhsArgs', taus) <- matchSubsts rhsArgs (alphas, lhsArgs)
      coerArgs <- zipWithM sigSubtyping rhsArgs lhsArgs'

      let substitution = zip alphas taus
          lhsBodySig' = U.substs substitution lhsBodySig
      coerBody <- abstractSigSubtyping lhsBodySig' rhsBodySig
      return (coerArgs, taus, coerBody)

    let argNames = map (\n -> "yArg" ++ show n) [1 .. length rhsArgTys]

    coercion lhsTy $ \inFunc ->
      withFreshNames (argNames :: [String]) $ \argYs ->
      let
        -- χ = χbody (f [τs] (χ1 y1) ... (χn yn))
        chi =
          applyCoercion coerBody ((inFunc `pApps` taus) `apps` (zipWith applyCoercion coerArgs $ map V argYs))
        -- Λ α's . λ ys : Σ's . χ
        resultFn = pLams' tvksr $ lams (zip argYs rhsArgTys) chi
       in return resultFn

-- |  ⊢ model Ξ ≤ model Ξ' ⇝ f'
--
--    ⊢ Ξ ≤ Ξ' ⇝ f
--
-- where f' = λx:Dist Ξ. let x ~ x in return (f x)  :: Dist Ξ → Dist Ξ'
modelSubtyping :: (MonadPlus m, LFresh m) => AbstractSig -> AbstractSig -> m Coercion
modelSubtyping lhsAbs rhsAbs = do
  lhsTy_ <- embedAbstractSig lhsAbs
  let lhsTy = TDist lhsTy_
  pureCoer <- abstractSigSubtyping lhsAbs rhsAbs
  coercion lhsTy $ \d ->
    withFreshName "s" $ \s ->
    let body  = Return (applyCoercion pureCoer $ V s)
        letSamp = LetSample $ U.bind (s, U.embed d) body
    in return letSamp


text:
package com.helospark.lightdi.it;

import org.junit.Test;

import com.helospark.lightdi.LightDi;
import com.helospark.lightdi.LightDiContext;
import com.helospark.lightdi.exception.BeanCreationException;
import com.helospark.lightdi.exception.ContextInitializationFailedException;
import com.helospark.lightdi.it.requireddependencyfail.BeanWithNonExistentRequiredConstructorDependency;
import com.helospark.lightdi.it.requireddependencyfail.BeanWithNonExistentRequiredFieldDependency;
import com.helospark.lightdi.it.requireddependencyfail.BeanWithNonExistentRequiredSetterDependency;
import com.helospark.lightdi.it.requireddependencyfail.BeanWithNonExistentValueInField;

public class MissingRequiredDependencyContextLoadFailIT {

    @Test(expected = ContextInitializationFailedException.class)
    public void testLoadContextWithMissingRequiredFieldDependencyShouldFail() {
        // GIVEN

        // WHEN
        LightDi lightDi = new LightDi();
        LightDi.initContextByClass(BeanWithNonExistentRequiredFieldDependency.class);

        // THEN throws
    }

    @Test(expected = ContextInitializationFailedException.class)
    public void testLoadContextWithMissingRequiredSetterDependencyShouldFail() {
        // GIVEN

        // WHEN
        LightDi lightDi = new LightDi();
        LightDi.initContextByClass(BeanWithNonExistentRequiredSetterDependency.class);

        // THEN throws
    }

    @Test(expected = ContextInitializationFailedException.class)
    public void testLoadContextWithMissingRequiredConstructorDependencyShouldFail() {
        // GIVEN

        // WHEN
        LightDi lightDi = new LightDi();
        LightDi.initContextByClass(BeanWithNonExistentRequiredConstructorDependency.class);

        // THEN throws
    }

    @Test(expected = BeanCreationException.class)
    public void testBeanInitializationShouldFailWithMissingValueAnnotation() {
        // GIVEN
        LightDi lightDi = new LightDi();
        LightDiContext context = LightDi.initContextByClass(BeanWithNonExistentValueInField.class);

        // WHEN
        context.getBean(BeanWithNonExistentValueInField.class);

        // THEN throws
    }

}


text:
package net.grinder.engine.communication;

import net.grinder.communication.Message;

public class ConnectionAgentCommunicationMessage implements Message {
	private final int usingPort;
	private final String ip;
	private final int port;

	public ConnectionAgentCommunicationMessage(int usingPort, String ip, int port) {
		this.usingPort = usingPort;
		this.ip = ip;
		this.port = port;
	}

	public int getUsingPort() {
		return usingPort;
	}

	public String getIp() {
		return ip;
	}

	public int getPort() {
		return port;
	}
}


text:
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.net;

/**
 * Constants used by Chrome in SPNEGO authentication requests to the Android Account Manager.
 */
public class HttpNegotiateConstants {
    // Option bundle keys
    //
    // The token provided by in the HTTP 401 response (Base64 encoded string)
    public static final String KEY_INCOMING_AUTH_TOKEN = "incomingAuthToken";
    // The SPNEGO Context from the previous transaction (Bundle) - also used in the response bundle
    public static final String KEY_SPNEGO_CONTEXT = "spnegoContext";
    // True if delegation is allowed
    public static final String KEY_CAN_DELEGATE = "canDelegate";

    // Response bundle keys
    //
    // The returned status from the authenticator.
    public static final String KEY_SPNEGO_RESULT = "spnegoResult";

    // Name of SPNEGO feature
    public static final String SPNEGO_FEATURE = "SPNEGO";
    // Prefix of token type. Full token type is "SPNEGO:HOSTBASED:<spn>"
    public static final String SPNEGO_TOKEN_TYPE_BASE = "SPNEGO:HOSTBASED:";

    // Returned status codes
    // All OK. Returned token is valid.
    public static final int OK = 0;
    // An unexpected error. This may be caused by a programming mistake or an invalid assumption.
    public static final int ERR_UNEXPECTED = 1;
    // Request aborted due to user action.
    public static final int ERR_ABORTED = 2;
    // An unexpected, but documented, SSPI or GSSAPI status code was returned.
    public static final int ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS = 3;
    // The server's response was invalid.
    public static final int ERR_INVALID_RESPONSE = 4;
    // Credentials could not be established during HTTP Authentication.
    public static final int ERR_INVALID_AUTH_CREDENTIALS = 5;
    // An HTTP Authentication scheme was tried which is not supported on this machine.
    public static final int ERR_UNSUPPORTED_AUTH_SCHEME = 6;
    // (GSSAPI) No Kerberos credentials were available during HTTP Authentication.
    public static final int ERR_MISSING_AUTH_CREDENTIALS = 7;
    // An undocumented SSPI or GSSAPI status code was returned.
    public static final int ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS = 8;
    // The identity used for authentication is invalid.
    public static final int ERR_MALFORMED_IDENTITY = 9;
}


text:
package main

// This deviates form the example on gobyexample.com
// because a fast machine will make it seem like the
// jobs channel is working synchronously when it is
// not acting that way. Adding the sleep helps illustrate
// the point of how the channels communicate and how they
// work when closing.

import (
	"fmt"
	"time"
)

func main() {
	jobs := make(chan int, 5)
	done := make(chan bool, 1)

	go func() {
		for {
			j, more := <-jobs
			if more {
				fmt.Println("received job", j)
			} else {
				fmt.Println("received all jobs")
				done <- true
				return
			}
		}
	}()

	go func() {
		for j := 1; j <= 3; j++ {
			jobs <- j
			fmt.Println("sent job")
			if j%2 == 0 {
				time.Sleep(time.Second * 1)
			}
		}
		close(jobs)
		// It's like the financial crisis
		fmt.Println("sent all jobs")
	}()

	<-done
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1">
<context>
    <name>CoverPage</name>
    <message>
        <source>My Cover</source>
        <translation>Mein Cover</translation>
    </message>
</context>
<context>
    <name>FirstPage</name>
    <message>
        <source>Show Page 2</source>
        <translation type="vanished">Zur Seite 2</translation>
    </message>
    <message>
        <source>UI Template</source>
        <translation type="vanished">UI-Vorlage</translation>
    </message>
    <message>
        <source>Hello Sailors</source>
        <translation type="vanished">Hallo Matrosen</translation>
    </message>
</context>
<context>
    <name>SecondPage</name>
    <message>
        <source>Nested Page</source>
        <translation type="vanished">Unterseite</translation>
    </message>
    <message>
        <source>Item</source>
        <translation type="vanished">Element</translation>
    </message>
</context>
</TS>


text:
<?php

namespace SwooleFlierMouseBase\abstracts;

use SwooleFlierMouseBase\command\Command;
use SwooleFlierMouseBase\Conf;
use SwooleFlierMouseBase\Core;
use SwooleFlierMouseBase\interfaces\Serv as ServI;
use SwooleFlierMouseBase\serv\Server;
use SwooleFlierMouseBase\SwooleFlierMouseBaseException;

abstract class Serv implements ServI
{
	public static $serv         = NULL;
	public        $server_type  = NULL;
	public        $protocol     = NULL;
	public        $host         = NULL;
	public        $server_name  = NULL;
	public        $conf         = NULL;
	public        $serv_conf    = NULL;
	public        $port         = NULL;
	public        $ssl          = FALSE;
	public        $ssl_cert_pem = NULL;
	public        $ssl_cert_key = NULL;
	public        $session      = FALSE;
	public        $server_id    = FALSE;
	public        $sock_type    = SWOOLE_SOCK_TCP;
	public        $mode         = SWOOLE_PROCESS;

	static public $ssl_protocols
		= [
			'https',
			'wss'
		];

	static public $default_options
		= [
			'heartbeat_check_interval' => 60,
			'heartbeat_idle_time'      => 600,
			//		'daemonize' => 1,
			//			'package_max_length'       => 1024 * 1024 * 1024 * 1024 * 1024,
			//			'open_http_protocol'       => TRUE
		];

	public function __construct (array $conf, $server_id)
	{
		$this->conf = $conf;

		$this->host        = $conf['host'];
		$this->server_id   = $server_id;
		$this->protocol    = $conf['protocol'];
		$this->session     = $conf['session']??FALSE;
		$this->server_name = isset($conf['server_name']) ? explode(' ', $conf['server_name'])[0] : $this->host;
		$this->port        = $conf['port'];
		$this->serv_conf   = $conf['serv_conf']??[];
		$this->ssl         = $conf['ssl']??(in_array($this->protocol, self::$ssl_protocols) ? TRUE : FALSE);
		$this->mode        = $conf['mode']??SWOOLE_PROCESS;
		if ($this->ssl) {
			if (!isset($conf['ssl_cert_pem']) || !isset($conf['ssl_cert_key'])) {
				throw new SwooleFlierMouseBaseException('You open the SSL not set secret key and certificate');
			}
			else {
				$this->ssl_cert_pem = $conf['ssl_cert_pem'];
				$this->ssl_cert_key = $conf['ssl_cert_key'];
				$this->sock_type    = $conf['sock_type'] ?: (SWOOLE_SOCK_TCP | SWOOLE_SSL);
			}
		}

		if (in_array($this->protocol, ['http', 'https'])) {
			$this->serv_conf['open_http_protocol'] = TRUE;
		}

		$this->serv_conf = array_merge(self::$default_options, $this->serv_conf);

		if (NULL == self::$serv) {
			self::$serv = new \swoole_server($this->host, $this->port, $this->mode, $this->sock_type);
			self::$serv->on('Packet', [$this, 'onPacket']);
			self::$serv->on('Start', [$this, 'onStart']);
			self::$serv->on('WorkerStart', [$this, 'onWorkerStart']);
			self::$serv->on('WorkerStop', [$this, 'onWorkerStop']);
			self::$serv->on('Receive', [$this, 'onReceive']);
			self::$serv->on('Shutdown', [$this, 'onShutdown']);
			self::$serv->on('connect', [$this, 'onConnect']);
			self::$serv->on('close', [$this, 'onClose']);

			if (Conf::isDaemonize()) {
				$this->serv_conf['daemonize'] = TRUE;
			}

			if ($this->serv_conf) self::$serv->set(array_merge($this->serv_conf, Conf::get('servers_config') ?: []));
		}
		else {
			$new_listen = self::$serv->addListener($this->host, $this->port, $this->sock_type);
			$new_listen->on('Packet', [$this, 'onPacket']);
			$new_listen->on('Receive', [$this, 'onReceive']);
			$new_listen->on('connect', [$this, 'onConnect']);
			$new_listen->on('close', [$this, 'onClose']);
			if ($this->serv_conf) $new_listen->set($this->serv_conf);
		}
	}

	public function onStart ($server)
	{
		$messages = [];
		foreach (Server::$instances as $instance) {
			$messages[] = sprintf(" \e[41;37m RUNING \e[0m   HOST:%s://%s:%s[%s] ",
				$instance->protocol,
				$instance->server_name,
				$instance->port,
				$instance->host
			);
		}

		Command::line($messages);

		file_put_contents(Command::$pid_file, $server->master_pid);
		file_put_contents(Command::$pid_file, ',' . $server->manager_pid, FILE_APPEND);
		Command::setProcessTitle('master');
	}

	public function onShutdown ($server)
	{
//		Command::line('onShutdown');
	}

	public function onWorkerStart ($server, $worker_id)
	{
		file_put_contents(Command::$pid_file, ',' . $server->worker_pid, FILE_APPEND);

		if ($server->taskworker) {
			Command::setProcessTitle('tasker');
		}
		else {
			echo 'onWorkerStart' . PHP_EOL;

			#before
			if (isset(Core::$bind_exec_before[ $this->server_id ])) {
				$call_function         = Core::$bind_exec_before[ $this->server_id ];
				$server->before_result = $call_function();
			}

			Command::setProcessTitle('worker');
		}
	}

	public function onWorkerStop ()
	{
//		Command::line('onWorkerStop');
	}

	public function onTimer ()
	{
	}

	public function onConnect ($server, $fd, $from_id)
	{
//		Command::line('onConnect' . json_encode($server->connection_info($fd)));
	}

	public function onReceive ($server, $fd, $reactor_id, $data)
	{
//		$starttime = explode(' ',microtime());
		switch ($this->protocol) {
			case 'http';
				$this->httpServ($server, $fd, $reactor_id, $data);
				break;
			case 'https';
				$this->httpServ($server, $fd, $reactor_id, $data);
				break;
		}

//		$endtime = explode(' ',microtime());
//		$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);
//		$thistime = round($thistime,3);
//		echo "本网页执行耗时:".$thistime." 秒。".time().PHP_EOL;
	}

	public function onPacket ()
	{
	}

	public function onClose ()
	{
//		Command::line('onClose');
	}

	public function onBufferFull ()
	{
	}

	public function onBufferEmpty ()
	{
	}

	public function onTask ()
	{
	}

	public function onFinish ()
	{
	}

	public function onPipeMessage ()
	{
	}

	public function onWorkerError ()
	{
	}

	public function onManagerStart ()
	{
	}

	public function onManagerStop ()
	{
	}
}


text:
package org.usfirst.frc.team2583.robot.commands;

import org.usfirst.frc.team2583.robot.OI;
import org.usfirst.frc.team2583.robot.subsystems.DriveBase;

import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class JoystickDrive extends Command {

	private final OI oi;
	private final DriveBase base;

    public JoystickDrive() {
    	base = DriveBase.getInstance();
        requires(base);
        setInterruptible(true);
        oi = OI.getInstance();
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	base.tankDrive(oi.XController1.getLeftY(), oi.XController1.getRightY());
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/vision/v1/image_annotator.proto

namespace Google\Cloud\Vision\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Rectangle determined by min and max `LatLng` pairs.
 *
 * Generated from protobuf message google.cloud.vision.v1.LatLongRect
 */
class LatLongRect extends \Google\Protobuf\Internal\Message
{
    /**
     * Min lat/long pair.
     *
     * Generated from protobuf field .google.type.LatLng min_lat_lng = 1;
     */
    private $min_lat_lng = null;
    /**
     * Max lat/long pair.
     *
     * Generated from protobuf field .google.type.LatLng max_lat_lng = 2;
     */
    private $max_lat_lng = null;

    public function __construct() {
        \GPBMetadata\Google\Cloud\Vision\V1\ImageAnnotator::initOnce();
        parent::__construct();
    }

    /**
     * Min lat/long pair.
     *
     * Generated from protobuf field .google.type.LatLng min_lat_lng = 1;
     * @return \Google\Type\LatLng
     */
    public function getMinLatLng()
    {
        return $this->min_lat_lng;
    }

    /**
     * Min lat/long pair.
     *
     * Generated from protobuf field .google.type.LatLng min_lat_lng = 1;
     * @param \Google\Type\LatLng $var
     * @return $this
     */
    public function setMinLatLng($var)
    {
        GPBUtil::checkMessage($var, \Google\Type\LatLng::class);
        $this->min_lat_lng = $var;

        return $this;
    }

    /**
     * Max lat/long pair.
     *
     * Generated from protobuf field .google.type.LatLng max_lat_lng = 2;
     * @return \Google\Type\LatLng
     */
    public function getMaxLatLng()
    {
        return $this->max_lat_lng;
    }

    /**
     * Max lat/long pair.
     *
     * Generated from protobuf field .google.type.LatLng max_lat_lng = 2;
     * @param \Google\Type\LatLng $var
     * @return $this
     */
    public function setMaxLatLng($var)
    {
        GPBUtil::checkMessage($var, \Google\Type\LatLng::class);
        $this->max_lat_lng = $var;

        return $this;
    }

}


text:
  Vittefleur est
       un village
       géographiquement positionné dans le département de Seine-Maritime en Haute-Normandie. Elle comptait 623 habitants en 2008.

À coté de Vittefleur sont positionnées géographiquement les communes de
Canouville localisée à 2 km, 280 habitants,
Cany-Barville située à 2 km, 3 150 habitants,
Bertheauville située à 3 km, 116 habitants,
Clasville localisée à 3 km, 251 habitants,
Butot-Vénesville située à 3 km, 282 habitants,
Auberville-la-Manuel à 3 km, 117 habitants,
 entre autres. De plus, Vittefleur est située à seulement 19 km de Fécamp.

La commune offre de nombreux  équipements sportifs, elle propose entre autres un terrain de tennis, un terrain de sport, un équipement de roller/skate et une base nautique.

À Vittefleur, la valeur moyenne à l'achat d'un appartement se situe à 3 028 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 556 € du m². À la location la valeur moyenne se situe à 9,66 € du m² par mois.

Le nombre de logements, à Vittefleur, était réparti en 2011 en trois appartements et 352 maisons soit
 un marché relativement équilibré.

Si vous envisagez de emmenager à Vittefleur, vous pourrez facilement trouver une maison à acheter.


text:
<?php namespace Ganymed\Exceptions;

class TypeHintException extends \Exception{

}


text:
Removes all records from the grid.

    clear([noRefresh])

        noRefresh
        boolean, indicates if to refresh the grid after reset

Returns undefined.

Description

Removes all records from the .records array, resets .total and
.buffered properties and refreshes the grid. If you have grid defined in the
following way:
<textarea class="javascript">
$('#grid').w2grid({
    name    : 'grid',
    columns: [
        { field: 'recid', caption: 'ID', size: '50px' },
        { field: 'lname', caption: 'Last Name', size: '30%' },
        { field: 'fname', caption: 'First Name', size: '30%' },
        { field: 'email', caption: 'Email', size: '40%' },
        { field: 'sdate', caption: 'Start Date', size: '120px' },
        { field: 'sdate', caption: 'End Date', size: '120px' }
    ],
    records: [
        { recid: 1, fname: 'John', lname: 'doe', email: 'vitali@gmail.com', sdate: '1/3/2012' },
        { recid: 2, fname: 'Stuart', lname: 'Motzart', email: 'jdoe@gmail.com', sdate: '2/4/2012' },
        { recid: 3, fname: 'Jin', lname: 'Franson', email: '--', sdate: '4/23/2012' },
        { recid: 4, fname: 'Susan', lname: 'Ottie', email: 'jdoe@gmail.com', sdate: '5/3/2012' },
        { recid: 5, fname: 'Kelly', lname: 'Silver', email: 'jdoe@gmail.com', sdate: '4/3/2012' },
        { recid: 6, fname: 'Francis', lname: 'Gatos', email: 'vitali@gmail.com', sdate: '2/5/2012' }
    ]
});
</textarea>

You can remove all records:
<textarea class="javascript">
w2ui['grid'].clear();
</textarea>

See also .reset() and .searchReset()


text:
import renderdoc as rd
import rdtest

class VK_Spec_Constants(rdtest.TestCase):
    demos_test_name = 'VK_Spec_Constants'

    def check_capture(self):
        # find the first action
        action = self.find_action("Draw")

        # We should have 4 actions, with spec constant values 0, 1, 2, 3
        for num_colors in range(4):
            self.check(action is not None)

            self.controller.SetFrameEvent(action.eventId, False)

            pipe: rd.PipeState = self.controller.GetPipelineState()

            shader: rd.ShaderReflection = pipe.GetShaderReflection(rd.ShaderStage.Pixel)

            # uniform buffer and spec constants
            self.check(len(shader.constantBlocks) == 2)
            self.check(shader.constantBlocks[0].bufferBacked)
            self.check(not shader.constantBlocks[1].bufferBacked)
            self.check(len(shader.constantBlocks[1].variables) == 1)

            # should be an array of num_colors+1 elements
            array_len = shader.constantBlocks[0].variables[0].type.descriptor.elements
            if not rdtest.value_compare(array_len, num_colors+1):
                raise rdtest.TestFailureException("CBuffer variable is array of {}, not {}".format(array_len, num_colors+1))

            if num_colors > 0:
                cbuf: rd.BoundCBuffer = pipe.GetConstantBuffer(rd.ShaderStage.Pixel, 0, 0)

                cb_vars = self.controller.GetCBufferVariableContents(pipe.GetGraphicsPipelineObject(),
                                                                     pipe.GetShader(rd.ShaderStage.Pixel),
                                                                     pipe.GetShaderEntryPoint(rd.ShaderStage.Pixel), 0,
                                                                     cbuf.resourceId, cbuf.byteOffset, cbuf.byteSize)

                self.check(len(cb_vars) == 1)

                if not rdtest.value_compare(len(cb_vars[0].members), num_colors+1):
                    raise rdtest.TestFailureException("CBuffer variable is array of {}, not {}".format(len(cb_vars[0].members), num_colors+1))

                for col in range(num_colors):
                    expected = [0.0, 0.0, 0.0, 0.0]
                    expected[col] = 1.0

                    val = [i for i in cb_vars[0].members[col].value.f32v[0:4]]

                    if not rdtest.value_compare(val, expected):
                        raise rdtest.TestFailureException("Cbuffer[{}] value {} doesn't match expectation {}".format(col, val, expected))

                rdtest.log.success("Draw with {} colors uniform buffer is as expected".format(num_colors))

            cbuf: rd.BoundCBuffer = pipe.GetConstantBuffer(rd.ShaderStage.Pixel, 1, 0)

            cb_vars = self.controller.GetCBufferVariableContents(pipe.GetGraphicsPipelineObject(),
                                                                 pipe.GetShader(rd.ShaderStage.Pixel),
                                                                 pipe.GetShaderEntryPoint(rd.ShaderStage.Pixel), 1,
                                                                 cbuf.resourceId, cbuf.byteOffset, cbuf.byteSize)

            self.check(len(cb_vars) == 1)

            if not rdtest.value_compare(cb_vars[0].value.s32v[0], num_colors):
                raise rdtest.TestFailureException("Spec constant is {}, not {}".format(cb_vars[0].value.s32v[0], num_colors))

            rdtest.log.success("Draw with {} colors specialisation constant is as expected".format(num_colors))

            view = pipe.GetViewport(0)

            # the first num_colors components should be 0.6, the rest should be 0.1 (alpha is always 1.0)
            expected = [0.0, 0.0, 0.0, 1.0]
            for col in range(num_colors):
                expected[col] += 1.0

            # Sample the centre of the viewport
            self.check_pixel_value(pipe.GetOutputTargets()[0].resourceId, int(view.x) + int(view.width / 2), int(view.height / 2), expected)

            rdtest.log.success("Draw with {} colors picked value is as expected".format(num_colors))

            action = action.next


text:
require 'spec'
require File.dirname(__FILE__)+'/dirs'
Spec::Runner.configure do |config|

end


text:
package com.hazelcast.client.proxy.txn.xa;

import com.hazelcast.client.connection.nio.ClientConnection;
import com.hazelcast.client.impl.HazelcastClientInstanceImpl;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.XATransactionCommitCodec;
import com.hazelcast.client.impl.protocol.codec.XATransactionCreateCodec;
import com.hazelcast.client.impl.protocol.codec.XATransactionPrepareCodec;
import com.hazelcast.client.impl.protocol.codec.XATransactionRollbackCodec;
import com.hazelcast.client.spi.impl.ClientInvocation;
import com.hazelcast.logging.ILogger;
import com.hazelcast.transaction.TransactionException;
import com.hazelcast.transaction.TransactionNotActiveException;
import com.hazelcast.transaction.impl.Transaction;
import com.hazelcast.transaction.impl.xa.SerializableXID;
import com.hazelcast.util.Clock;
import com.hazelcast.util.ExceptionUtil;

import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import static com.hazelcast.transaction.impl.Transaction.State.ACTIVE;
import static com.hazelcast.transaction.impl.Transaction.State.COMMITTED;
import static com.hazelcast.transaction.impl.Transaction.State.COMMITTING;
import static com.hazelcast.transaction.impl.Transaction.State.COMMIT_FAILED;
import static com.hazelcast.transaction.impl.Transaction.State.NO_TXN;
import static com.hazelcast.transaction.impl.Transaction.State.PREPARED;
import static com.hazelcast.transaction.impl.Transaction.State.ROLLED_BACK;
import static com.hazelcast.transaction.impl.Transaction.State.ROLLING_BACK;

/**
 * This class does not need to be thread-safe, it is only used via XAResource
 * All visibility guarantees handled by XAResource
 */
public class XATransactionProxy {

    private final HazelcastClientInstanceImpl client;
    private final ClientConnection connection;
    private final SerializableXID xid;
    private final int timeout;
    private final ILogger logger;

    private Transaction.State state = NO_TXN;
    private volatile String txnId;
    private long startTime;

    public XATransactionProxy(HazelcastClientInstanceImpl client, ClientConnection connection, Xid xid, int timeout) {
        this.client = client;
        this.connection = connection;
        this.timeout = timeout;
        this.xid = new SerializableXID(xid.getFormatId(), xid.getGlobalTransactionId(), xid.getBranchQualifier());
        logger = client.getLoggingService().getLogger(XATransactionProxy.class);
    }

    void begin() {
        try {
            startTime = Clock.currentTimeMillis();
            ClientMessage request = XATransactionCreateCodec.encodeRequest(xid, timeout);
            ClientMessage response = invoke(request);
            txnId = XATransactionCreateCodec.decodeResponse(response).response;
            state = ACTIVE;
        } catch (Exception e) {
            throw ExceptionUtil.rethrow(e);
        }
    }

    void prepare() {
        checkTimeout();
        try {
            if (state != ACTIVE) {
                throw new TransactionNotActiveException("Transaction is not active");
            }
            ClientMessage request = XATransactionPrepareCodec.encodeRequest(txnId);
            invoke(request);
            state = PREPARED;
        } catch (Exception e) {
            state = ROLLING_BACK;
            throw ExceptionUtil.rethrow(e);
        }
    }

    void commit(boolean onePhase) {
        checkTimeout();
        try {
            if (onePhase && state != ACTIVE) {
                throw new TransactionException("Transaction is not active");
            }
            if (!onePhase && state != PREPARED) {
                throw new TransactionException("Transaction is not prepared");
            }
            state = COMMITTING;
            ClientMessage request = XATransactionCommitCodec.encodeRequest(txnId, onePhase);
            invoke(request);
            state = COMMITTED;
        } catch (Exception e) {
            state = COMMIT_FAILED;
            throw ExceptionUtil.rethrow(e);
        }
    }

    void rollback() {
        state = ROLLING_BACK;
        try {
            ClientMessage request = XATransactionRollbackCodec.encodeRequest(txnId);
            invoke(request);
        } catch (Exception exception) {
            logger.warning("Exception while rolling back the transaction", exception);
        }
        state = ROLLED_BACK;
    }

    public String getTxnId() {
        return txnId;
    }

    public Transaction.State getState() {
        return state;
    }

    private void checkTimeout() {
        long timeoutMillis = TimeUnit.SECONDS.toMillis(timeout);
        if (startTime + timeoutMillis < Clock.currentTimeMillis()) {
            ExceptionUtil.sneakyThrow(new XAException(XAException.XA_RBTIMEOUT));
        }
    }

    private ClientMessage invoke(ClientMessage request) {
        try {
            final ClientInvocation clientInvocation = new ClientInvocation(client, request, connection);
            final Future<ClientMessage> future = clientInvocation.invoke();
            return future.get();
        } catch (Exception e) {
            throw ExceptionUtil.rethrow(e);
        }
    }
}


text:
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Forms;

namespace CslaContrib.Windows
{

    /// <summary>
    /// Add link to StatusStrip with Status and Animation.
    /// <example>
    /// 1) Add a StatusStrip to the form and add 2 ToolStripStatusLabels.
    /// 2) Add the StatusStripExtender to the form.
    /// 3) Set statusStripExtender properties on StatusStrip
    ///        StatusLabel  to toolStripStatusLabel1
    ///    and AnimationLabel to toolStripStatusLabel2
    /// 4) Set status text with
    ///         statusStripExtender1.SetStatus
    ///         statusStripExtender1.SetStatusStatic
    ///         statusStripExtender1.SetStatusWaiting
    ///         statusStripExtender1.SetStatusWithDuration
    /// </example>
    ///
    /// </summary>
    [ProvideProperty("StatusLabel", typeof(Control))]
    [ProvideProperty("AnimationLabel", typeof(Control))]
    public class StatusStripExtender : Component, IExtenderProvider
    {
        private ToolStripStatusLabel _status;
        private ToolStripStatusLabel _animation;
        private string _statusDefault = "Ready";
        private readonly Timer _timer;
        private Timer _progressIndicatorTimer;
        private int _statusDefaultDuration = 5000;
        private readonly StringCollection _toolTipList;
        private int _maximumToolTipLines = 5;
        private object _syncRoot = new object();

        #region --- Interface IExtenderProvider ----

        public bool CanExtend(object extendee)
        {
            return extendee is StatusStrip;
        }

        #endregion

        #region --- Extender properties ---

        [Category("StatusStripExtender")]
        public ToolStripStatusLabel GetStatusLabel(Control control)
        {
            return StatusControl;
        }

        [Category("StatusStripExtender")]
        public void SetStatusLabel(Control control, ToolStripStatusLabel statusLabel)
        {
            StatusControl = statusLabel;
        }

        [Category("StatusStripExtender")]
        public ToolStripStatusLabel GetAnimationLabel(Control control)
        {
            return AnimationControl;
        }

        [Category("StatusStripExtender")]
        public void SetAnimationLabel(Control control, ToolStripStatusLabel animationLabel)
        {
            AnimationControl = animationLabel;
        }

        #endregion
        #region // --- Constructor ---

        /// <summary>
        /// Initializes a new instance of the <see cref="StatusStripExtender"/> class.
        /// </summary>
        public StatusStripExtender()
        {
            _timer = new Timer { Enabled = false, Interval = _statusDefaultDuration };
            _timer.Tick += _timer_Tick;

            _toolTipList = new StringCollection();
        }

        #endregion

        #region // --- Public properties  ---

        /// <summary>
        /// Gets or sets the ToolStripStatusLabel for Status.
        /// </summary>
        /// <value>The status control.</value>
        [Category("ToolStrip"), Description("Gets or sets the ToolStripStatusLabel for Status.")]
        public ToolStripStatusLabel StatusControl
        {
            set
            {
                if (value == null && _status != null)
                {
                    ReleaseStatus();
                }
                else
                {
                    if (_animation == value && value != null)
                    {
                        throw new ArgumentException("StatusControl and AnimationControl can't be the same control.");
                    }
                    _status = value;
                    InitStatus();
                }
            }
            get
            {
                return _status;
            }
        }

        /// <summary>
        /// Gets or sets the default Status.
        /// </summary>
        /// <value>The status default text.</value>
        [Category("StatusControl"), Description("Gets or sets the default Status.")]
        [Localizable(true)]
        [DefaultValue("Klar")]
        public string StatusDefault
        {
            set
            {
                _statusDefault = value;
                SetStatusToDefault();
            }
            get
            {
                return _statusDefault;
            }
        }

        /// <summary>
        /// Gets or sets the maximum Tool Tip Lines to show (1-10, default 5).
        /// </summary>
        /// <value>The maximum number of Tool Tip Lines.</value>
        [Category("StatusControl"), Description("Maximum lines to show in the ToolTip text. Valid value is 1 to 10.")]
        [DefaultValue(5)]
        public int MaximumToolTipLines
        {
            set
            {
                _maximumToolTipLines = value;
                if (_maximumToolTipLines < 1)
                {
                    _maximumToolTipLines = 1;
                }
                if (_maximumToolTipLines > 10)
                {
                    _maximumToolTipLines = 10;
                }
            }
            get
            {
                return _maximumToolTipLines;
            }
        }

        private void SetStatusToolTip(string text)
        {
            if (!DesignMode)
            {
                _toolTipList.Insert(0, "(" + DateTime.Now.ToLongTimeString() + ") " + text);
                if (_toolTipList.Count > _maximumToolTipLines)
                {
                    _toolTipList.RemoveAt(_maximumToolTipLines);
                }

                string[] toolTipArray = new string[_maximumToolTipLines];
                _toolTipList.CopyTo(toolTipArray, 0);
                _status.ToolTipText = string.Join("\n", toolTipArray).TrimEnd();
            }
        }

        /// <summary>
        /// Gets or sets the delay.
        /// </summary>
        /// <value>The delay.</value>
        [Category("StatusControl"), Description("Delay in milliseconds to show the Status")]
        [DefaultValue(5000)]
        public int Delay
        {
            set
            {
                _statusDefaultDuration = value;
                _timer.Interval = _statusDefaultDuration;
            }
            get
            {
                return _statusDefaultDuration;
            }
        }

        public void SetStatusToDefault()
        {
            UpdateStatusStrip(_statusDefault, false, false, -1);
        }

        #endregion

        #region --- Public funtions  --

        #region // --- Public Animation ---

        /// <summary>
        /// Gets or sets the Animation control.
        /// </summary>
        /// <value>The animation control.</value>
        [Category("ToolStrip"), Description("Gets or sets the Animation control.")]
        public ToolStripStatusLabel AnimationControl
        {
            set
            {
                if (value == null && _animation != null)
                {
                    ReleaseAnimation();
                }
                else
                {
                    if (_status == value && value != null)
                    {
                        throw new ArgumentException("AnimationControl and StatusControl can't be the same control.");
                    }
                    _animation = value;
                    InitAnimation();
                }
            }
            get
            {
                return _animation;
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether the Animation control is visible].
        /// </summary>
        /// <value><c>true</c> if the Animation control is visible; otherwise, <c>false</c>.</value>
        [Browsable(false)]
        [ReadOnly(true)]
        [DefaultValue(true)]
        public bool AnimationVisible
        {
            set
            {
                if (_animation != null)
                {
                    _animation.Visible = value;
                }
            }
            get
            {
                if (_animation != null)
                {
                    return _animation.Visible;
                }
                else
                {
                    return true;
                }
            }
        }

        #endregion

        /// <summary>
        /// Sets the statu to defaultstatus and stop progress indicator from running.
        /// </summary>
        public void SetStatus()
        {
            SetStatus(_statusDefault);
        }

        /// <summary>
        /// Set status message and stops the progress indicator from running
        /// </summary>
        /// <param name="text">The text.</param>
        public void SetStatus(string text)
        {
            SetStatus(text, _statusDefaultDuration);
        }

        /// <summary>
        /// Set status message and stops the progress indicator from running
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="durationMilliseconds">The duration milliseconds.</param>
        public void SetStatus(string text, int durationMilliseconds)
        {
            UpdateStatusStrip(text, false, false, durationMilliseconds);
        }

        /// <summary>
        /// Sets the Status and keep it until new text.
        /// </summary>
        public void SetStatusStatic()
        {
            SetStatusStatic(_statusDefault);
        }

        /// <summary>
        /// Sets the Status and keep it until new text.
        /// </summary>
        /// <param name="text">The text.</param>
        public void SetStatusStatic(string text)
        {
            UpdateStatusStrip(text, false, false, -1);
        }

        /// <summary>
        /// Sets the duration of the status with.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="duration">The duration.</param>
        public void SetStatusWithDuration(string text, int duration)
        {
            UpdateStatusStrip(text, false, false, duration);
        }

        /// <summary>
        /// Updates the status bar with the specified message. The message is reset after a few seconds.
        /// Progress indicator is NOT shown
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="formatParams">Formatting parameters</param>
        public void SetStatusText(string message, params object[] formatParams)
        {
            var formattedMessage = string.Format(message, formatParams);
            UpdateStatusStrip(formattedMessage, false, false, _statusDefaultDuration);
        }

        /// <summary>
        /// Updates the status bar with the specified message. The message is not reset until "SetStatus()" is called
        /// Progress indicator IS shown
        /// Large IS shown
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="formatParams">The format params.</param>
        public void SetStatusWaiting(string message, params object[] formatParams)
        {
            SetStatusWaiting(message, true, formatParams);
        }

        /// <summary>
        /// Updates the status bar with the specified message. The message is not reset until "SetStatus()" is called
        /// Progress indicator IS shown
        /// Large progress indicator is displayed depending on "displayLargeProgressIndicator"
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="displayLargeProgressindicator">if set to <c>true</c> [display large progressindicator].</param>
        /// <param name="formatParams">Formatting parameters</param>
        public void SetStatusWaiting(string message, bool displayLargeProgressindicator, params object[] formatParams)
        {
            var formattedMessage = string.Format(message, formatParams);
            UpdateStatusStrip(formattedMessage, true, displayLargeProgressindicator, -1);
        }

        /// <summary>
        /// Updates the status strip.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="showProgressIndicator">if set to <c>true</c> [show progress indicator].</param>
        /// <param name="showLargeProgressIndicator">if set to <c>true</c> [show large progress indicator].</param>
        /// <param name="durationMilliseconds"></param>
        public void UpdateStatusStrip(string message, bool showProgressIndicator, bool showLargeProgressIndicator, int durationMilliseconds)
        {
            //if (this..InvokeRequired)
            //{
            //  ParentForm.Invoke(new StatusStripDelegate(UpdateStatusStrip), message, showProgressIndicator, showLargeProgressIndicator);
            //}
            lock (_syncRoot)
            {
                if (_progressIndicatorTimer != null)
                    _progressIndicatorTimer.Stop();
                SplashPanel.Close();

                if (showProgressIndicator)
                {
                    SetStatusTextStaticPrivate(message);

                    if (showLargeProgressIndicator)
                    {
                        //If still waiting after 2 seconds, show a larger progressindicator
                        _progressIndicatorTimer = new Timer { Interval = 2000 };
                        _progressIndicatorTimer.Tick += TimerShowBusyIndicator;
                        _progressIndicatorTimer.Start();
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(message))
                        SetStatusToDefaultPrivate();
                    else
                        SetStatusTextPrivate(message, durationMilliseconds);
                }
                AnimationVisible = showProgressIndicator;
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Sets the Status.
        /// </summary>
        /// <param name="text">The text.</param>
        private void SetStatusTextPrivate(string text)
        {
            SetStatusWithDurationPrivate(text, _statusDefaultDuration);
        }

        /// <summary>
        /// Sets the Status.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="durationMilliseconds">The duration milliseconds.</param>
        private void SetStatusTextPrivate(string text, int durationMilliseconds)
        {
            SetStatusWithDurationPrivate(text, durationMilliseconds);
        }

        /// <summary>
        /// Sets the Status and keep it until new text.
        /// </summary>
        /// <param name="text">The text.</param>
        private void SetStatusTextStaticPrivate(string text)
        {
            SetStatusWithDurationPrivate(text, -1);
        }

        /// <summary>
        /// Sets the Status with delay.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="durationMilliseconds">The duration in milliseconds.</param>
        private void SetStatusWithDurationPrivate(string text, int durationMilliseconds)
        {
            _status.Text = text;
            SetStatusToolTip(text);
            if (durationMilliseconds < 0)
            {
                _timer.Enabled = false;
                _timer.Interval = _statusDefaultDuration;
            }
            else
            {
                if (_timer.Enabled)
                {
                    _timer.Enabled = false;
                    _timer.Interval = durationMilliseconds;
                    _timer.Enabled = true;
                }
                else
                {
                    _timer.Enabled = true;
                }
            }
        }

        /// <summary>
        /// Sets the status to Default.
        /// </summary>
        private void SetStatusToDefaultPrivate()
        {
            if (_status != null)
            {
                if (_status.Text != _statusDefault || _toolTipList.Count == 0)
                {
                    _status.Text = _statusDefault;
                    SetStatusToolTip(_statusDefault);
                }
            }
        }

        /// <summary>
        /// Hides the temporary wait indicator.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void HideTemporaryWaitIndicator(object sender, EventArgs e)
        {
            lock (_syncRoot)
            {
                var timer = sender as Timer;
                if (timer != null) timer.Stop();
                SplashPanel.Close();
                SetStatusToDefault();
                AnimationVisible = false;
            }
        }

        /// <summary>
        /// Handles the Tick event of the _progressIndicatorTimer
        /// Displays a large progressindicator
        /// </summary>
        /// <param name="sender">The timer that triggered the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void TimerShowBusyIndicator(object sender, EventArgs e)
        {
            lock (_syncRoot)
            {
                var timer = sender as Timer;
                if (timer != null) timer.Stop();
                SplashPanel.Show((AnimationControl).Owner.FindForm(), StatusControl.Text);
            }
        }

        #endregion

        #region // --- Private Status ---

        private void InitStatus()
        {
            if (_status != null)
            {
                SetStatusToDefault();
                _status.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
                _status.Spring = true;
                if (DesignMode)
                {
                    _status.Owner.ShowItemToolTips = true;
                }
            }
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            _timer.Enabled = false;
            SetStatusToDefault();
            _timer.Interval = _statusDefaultDuration;
        }

        private void ReleaseStatus()
        {
            if (_status != null)
            {
                _status.Text = "# Not in use #";
                _status.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
                _status.Spring = false;
                _status = null;
            }
        }

        #endregion

        #region // --- Private Animation ---

        private void InitAnimation()
        {
            if (_animation != null)
            {
                _animation.DisplayStyle = ToolStripItemDisplayStyle.Image;
                _animation.ImageScaling = ToolStripItemImageScaling.None;
                _animation.Image = Properties.Resources.status_anim;
                if (!DesignMode)
                {
                    _animation.Visible = false;
                }
            }
        }

        private void ReleaseAnimation()
        {
            if (_animation != null)
            {
                _animation.Image = null;
                _animation.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                _animation.ImageScaling = ToolStripItemImageScaling.SizeToFit;
                _animation.Text = "# Not in use #";
                if (!DesignMode)
                {
                    _animation.Visible = true;
                }
                _animation = null;
            }
        }
        #endregion

    } // public class StatusStripExtender
}


text:
#include "path.h"

namespace Lxt
{
	std::string Path_GetExtension( const Path& a_path )
	{
		std::string				extension;
		std::string::size_type	i = a_path.find_last_of('.');

		if ( i != std::string::npos )
		{
			extension = a_path.substr( i, a_path.size() );
		}

		return extension;
	};

	std::string Path_GetFilename( const Path& a_path )
	{
		// get file name, starting from one after last slash
		// of beginning of string if no slash.
		size_t sp = a_path.find_last_of('/');
		sp = ( sp == Path::npos ) ? 0 : sp+1;

		// get path name
		Path fileName = a_path.substr( sp, a_path.size() );

		return fileName;
	}
}


text:
package space

import (
	"fmt"

	"code.cloudfoundry.org/cli/cf"
	"code.cloudfoundry.org/cli/cf/api/organizations"
	"code.cloudfoundry.org/cli/cf/api/spaces"
	"code.cloudfoundry.org/cli/cf/commandregistry"
	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
	"code.cloudfoundry.org/cli/cf/flags"
	. "code.cloudfoundry.org/cli/cf/i18n"
	"code.cloudfoundry.org/cli/cf/models"
	"code.cloudfoundry.org/cli/cf/requirements"
	"code.cloudfoundry.org/cli/cf/terminal"
)

type DeleteSpace struct {
	ui        terminal.UI
	config    coreconfig.ReadWriter
	spaceRepo spaces.SpaceRepository
	spaceReq  requirements.SpaceRequirement
	orgRepo   organizations.OrganizationRepository
}

func init() {
	commandregistry.Register(&DeleteSpace{})
}

func (cmd *DeleteSpace) MetaData() commandregistry.CommandMetadata {
	fs := make(map[string]flags.FlagSet)
	fs["f"] = &flags.BoolFlag{ShortName: "f", Usage: T("Force deletion without confirmation")}
	fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Delete space within specified org")}

	return commandregistry.CommandMetadata{
		Name:        "delete-space",
		Description: T("Delete a space"),
		Usage: []string{
			T("CF_NAME delete-space SPACE [-o ORG] [-f]"),
		},
		Flags: fs,
	}
}

func (cmd *DeleteSpace) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("delete-space"))
		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1)
	}

	cmd.spaceReq = requirementsFactory.NewSpaceRequirement(fc.Args()[0])

	reqs := []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}

	if fc.String("o") == "" {
		reqs = append(reqs, requirementsFactory.NewTargetedOrgRequirement())
		reqs = append(reqs, cmd.spaceReq)
	}

	return reqs, nil
}

func (cmd *DeleteSpace) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command {
	cmd.ui = deps.UI
	cmd.config = deps.Config
	cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository()
	cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository()
	return cmd
}
func (cmd *DeleteSpace) Execute(c flags.FlagContext) error {
	var space models.Space

	spaceName := c.Args()[0]
	orgName := c.String("o")

	if orgName == "" {
		space = cmd.spaceReq.GetSpace()

		orgName = cmd.config.OrganizationFields().Name
	} else {
		org, err := cmd.orgRepo.FindByName(orgName)
		if err != nil {
			return err
		}

		space, err = cmd.spaceRepo.FindByNameInOrg(spaceName, org.GUID)
		if err != nil {
			return err
		}
	}

	if !c.Bool("f") {
		if !cmd.ui.ConfirmDelete(T("space"), spaceName) {
			return nil
		}
	}

	cmd.ui.Say(T("Deleting space {{.TargetSpace}} in org {{.TargetOrg}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"TargetSpace": terminal.EntityNameColor(spaceName),
			"TargetOrg":   terminal.EntityNameColor(orgName),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	err := cmd.spaceRepo.Delete(space.GUID)
	if err != nil {
		return err
	}

	cmd.ui.Ok()

	if cmd.config.SpaceFields().GUID == space.GUID {
		cmd.config.SetSpaceFields(models.SpaceFields{})
		cmd.ui.Say(T("TIP: No space targeted, use '{{.CfTargetCommand}}' to target a space.",
			map[string]interface{}{"CfTargetCommand": cf.Name + " target -s"}))
	}

	return nil
}