text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * Responsible for showing following banners in the file list.
 *  - WelcomeBanner
 *  - AuthFailBanner
 * @param {DirectoryModel} directoryModel The model.
 * @param {VolumeManager} volumeManager The manager.
 * @param {DOMDocument} document HTML document.
 * @param {boolean} showOffers True if we should show offer banners.
 * @constructor
 */
function FileListBannerController(
    directoryModel, volumeManager, document, showOffers) {
  this.directoryModel_ = directoryModel;
  this.volumeManager_ = volumeManager;
  this.document_ = document;
  this.showOffers_ = showOffers;
  this.driveEnabled_ = false;

  this.initializeWelcomeBanner_();
  this.privateOnDirectoryChangedBound_ =
      this.privateOnDirectoryChanged_.bind(this);

  var handler = this.checkSpaceAndMaybeShowWelcomeBanner_.bind(this);
  this.directoryModel_.addEventListener('scan-completed', handler);
  this.directoryModel_.addEventListener('rescan-completed', handler);
  this.directoryModel_.addEventListener('directory-changed',
      this.onDirectoryChanged_.bind(this));

  this.unmountedPanel_ = this.document_.querySelector('#unmounted-panel');
  this.volumeManager_.addEventListener('drive-status-changed',
        this.updateDriveUnmountedPanel_.bind(this));
  this.volumeManager_.addEventListener('drive-connection-changed',
        this.onDriveConnectionChanged_.bind(this));

  util.storage.onChanged.addListener(this.onStorageChange_.bind(this));
  this.welcomeHeaderCounter_ = WELCOME_HEADER_COUNTER_LIMIT;
  this.warningDismissedCounter_ = 0;
  util.storage.sync.get([WELCOME_HEADER_COUNTER_KEY, WARNING_DISMISSED_KEY],
                          function(values) {
    this.welcomeHeaderCounter_ =
        parseInt(values[WELCOME_HEADER_COUNTER_KEY]) || 0;
    this.warningDismissedCounter_ =
        parseInt(values[WARNING_DISMISSED_KEY]) || 0;
  }.bind(this));

  this.authFailedBanner_ =
      this.document_.querySelector('#drive-auth-failed-warning');
  var authFailedText = this.authFailedBanner_.querySelector('.drive-text');
  authFailedText.innerHTML = util.htmlUnescape(str('DRIVE_NOT_REACHED'));
  authFailedText.querySelector('a').addEventListener('click', function(e) {
    chrome.fileBrowserPrivate.logoutUser();
    e.preventDefault();
  });
  this.maybeShowAuthFailBanner_();
}

/**
 * FileListBannerController extends cr.EventTarget.
 */
FileListBannerController.prototype.__proto__ = cr.EventTarget.prototype;

/**
 * Key in localStorage to keep numer of times the Drive Welcome
 * banner has shown.
 */
var WELCOME_HEADER_COUNTER_KEY = 'driveWelcomeHeaderCounter';

// If the warning was dismissed before, this key stores the quota value
// (as of the moment of dismissal).
// If the warning was never dismissed or was reset this key stores 0.
var WARNING_DISMISSED_KEY = 'driveSpaceWarningDismissed';

/**
 * Maximum times Drive Welcome banner could have shown.
 */
var WELCOME_HEADER_COUNTER_LIMIT = 25;

/**
 * Location of the FAQ about Google Drive.
 */
var GOOGLE_DRIVE_FAQ_URL =
      'https://support.google.com/chromeos/?p=filemanager_drive';

/**
 * Location of the page to buy more storage for Google Drive.
 */
var GOOGLE_DRIVE_BUY_STORAGE =
    'https://www.google.com/settings/storage';

var GOOGLE_DRIVE_REDEEM =
    'http://www.google.com/intl/en/chrome/devices/goodies.html';

/**
 * Location of the FAQ about the downloads directory.
 */
var DOWNLOADS_FAQ_URL =
    'http://support.google.com/chromeos/bin/answer.py?answer=1061547';

/**
 * Location of the help page about connecting to Google Drive.
 */
var GOOGLE_DRIVE_ERROR_HELP_URL =
    'https://support.google.com/chromeos/?p=filemanager_driveerror';

/**
 * Initializes the banner to promote DRIVE.
 * This method must be called before any of showing banner functions, and
 * also before registering them as callbacks.
 * @private
 */
FileListBannerController.prototype.initializeWelcomeBanner_ = function() {
  this.useNewWelcomeBanner_ = (!util.boardIs('x86-mario') &&
                               !util.boardIs('x86-zgb') &&
                               !util.boardIs('x86-alex'));
};

/**
 * @param {number} value How many times the Drive Welcome header banner
 * has shown.
 * @private
 */
FileListBannerController.prototype.setWelcomeHeaderCounter_ = function(value) {
  var values = {};
  values[WELCOME_HEADER_COUNTER_KEY] = value;
  util.storage.local.set(values);
};

/**
 * @param {number} value How many times the low space warning has dismissed.
 * @private
 */
FileListBannerController.prototype.setWarningDismissedCounter_ =
    function(value) {
  var values = {};
  values[WARNING_DISMISSED_KEY] = value;
  util.storage.local.set(values);
};

/**
 * util.storage.onChanged event handler.
 * @param {Object.<string, Object>} changes Changes values.
 * @param {string} areaName "local" or "sync".
 * @private
 */
FileListBannerController.prototype.onStorageChange_ = function(changes,
                                                               areaName) {
  if (areaName == 'local' && WELCOME_HEADER_COUNTER_KEY in changes) {
    this.welcomeHeaderCounter_ = changes[WELCOME_HEADER_COUNTER_KEY].newValue;
  }
  if (areaName == 'local' && WARNING_DISMISSED_KEY in changes) {
    this.warningDismissedCounter_ = changes[WARNING_DISMISSED_KEY].newValue;
  }
};

/**
 * Invoked when the drive connection status is change in the volume manager.
 * @private
 */
FileListBannerController.prototype.onDriveConnectionChanged_ = function() {
  this.maybeShowAuthFailBanner_();
};

/**
 * @param {string} type 'none'|'page'|'header'.
 * @param {string} messageId Reource ID of the message.
 * @private
 */
FileListBannerController.prototype.prepareAndShowWelcomeBanner_ =
    function(type, messageId) {
  this.showWelcomeBanner_(type);

  var container = this.document_.querySelector('.drive-welcome.' + type);
  if (container.firstElementChild)
    return;  // Do not re-create.

  if (!this.document_.querySelector('link[drive-welcome-style]')) {
    var style = this.document_.createElement('link');
    style.rel = 'stylesheet';
    style.href = 'css/drive_welcome.css';
    style.setAttribute('drive-welcome-style', '');
    this.document_.head.appendChild(style);
  }

  var wrapper = util.createChild(container, 'drive-welcome-wrapper');
  util.createChild(wrapper, 'drive-welcome-icon');

  var close = util.createChild(wrapper, 'cr-dialog-close');
  close.addEventListener('click', this.closeWelcomeBanner_.bind(this));

  var message = util.createChild(wrapper, 'drive-welcome-message');

  var title = util.createChild(message, 'drive-welcome-title');

  var text = util.createChild(message, 'drive-welcome-text');
  text.innerHTML = str(messageId);

  var links = util.createChild(message, 'drive-welcome-links');

  var more;
  if (this.useNewWelcomeBanner_) {
    var welcomeTitle = str('DRIVE_WELCOME_TITLE_ALTERNATIVE');
    if (util.boardIs('link'))
      welcomeTitle = str('DRIVE_WELCOME_TITLE_ALTERNATIVE_1TB');
    title.textContent = welcomeTitle;
    more = util.createChild(links,
        'drive-welcome-button drive-welcome-start', 'a');
    more.textContent = str('DRIVE_WELCOME_CHECK_ELIGIBILITY');
    more.href = GOOGLE_DRIVE_REDEEM;
  } else {
    title.textContent = str('DRIVE_WELCOME_TITLE');
    more = util.createChild(links, 'plain-link', 'a');
    more.textContent = str('DRIVE_LEARN_MORE');
    more.href = GOOGLE_DRIVE_FAQ_URL;
  }
  more.target = '_blank';

  var dismiss;
  if (this.useNewWelcomeBanner_)
    dismiss = util.createChild(links, 'drive-welcome-button');
  else
    dismiss = util.createChild(links, 'plain-link');

  dismiss.classList.add('drive-welcome-dismiss');
  dismiss.textContent = str('DRIVE_WELCOME_DISMISS');
  dismiss.addEventListener('click', this.closeWelcomeBanner_.bind(this));

  this.previousDirWasOnDrive_ = false;
};

/**
 * Show or hide the "Low Google Drive space" warning.
 * @param {boolean} show True if the box need to be shown.
 * @param {Object} sizeStats Size statistics. Should be defined when showing the
 *     warning.
 * @private
 */
FileListBannerController.prototype.showLowDriveSpaceWarning_ =
      function(show, sizeStats) {
  var box = this.document_.querySelector('#volume-space-warning');

  // Avoid showing two banners.
  // TODO(kaznacheev): Unify the low space warning and the promo header.
  if (show)
    this.cleanupWelcomeBanner_();

  if (box.hidden == !show)
    return;

  if (this.warningDismissedCounter_) {
    if (this.warningDismissedCounter_ ==
            sizeStats.totalSizeKB && // Quota had not changed
        sizeStats.remainingSizeKB / sizeStats.totalSizeKB < 0.15) {
      // Since the last dismissal decision the quota has not changed AND
      // the user did not free up significant space. Obey the dismissal.
      show = false;
    } else {
      // Forget the dismissal. Warning will be shown again.
      this.setWarningDismissedCounter_(0);
    }
  }

  box.textContent = '';
  if (show) {
    var icon = this.document_.createElement('div');
    icon.className = 'drive-icon';
    box.appendChild(icon);

    var text = this.document_.createElement('div');
    text.className = 'drive-text';
    text.textContent = strf('DRIVE_SPACE_AVAILABLE_LONG',
        util.bytesToString(sizeStats.remainingSizeKB * 1024));
    box.appendChild(text);

    var link = this.document_.createElement('a');
    link.className = 'plain-link';
    link.textContent = str('DRIVE_BUY_MORE_SPACE_LINK');
    link.href = GOOGLE_DRIVE_BUY_STORAGE;
    link.target = '_blank';
    box.appendChild(link);

    var close = this.document_.createElement('div');
    close.className = 'cr-dialog-close';
    box.appendChild(close);
    close.addEventListener('click', function(total) {
      window.localStorage[WARNING_DISMISSED_KEY] = total;
      box.hidden = true;
      this.requestRelayout_(100);
    }.bind(this, sizeStats.totalSizeKB));
  }

  if (box.hidden != !show) {
    box.hidden = !show;
    this.requestRelayout_(100);
  }
};
/**
 * Closes the Drive Welcome banner.
 * @private
 */
FileListBannerController.prototype.closeWelcomeBanner_ = function() {
  this.cleanupWelcomeBanner_();
  // Stop showing the welcome banner.
  this.setWelcomeHeaderCounter_(WELCOME_HEADER_COUNTER_LIMIT);
};

/**
 * Shows or hides the welcome banner for drive.
 * @private
 */
FileListBannerController.prototype.checkSpaceAndMaybeShowWelcomeBanner_ =
    function() {
  if (!this.isOnDrive()) {
    // We are not on the drive file system. Do not show (close) the welcome
    // banner.
    this.cleanupWelcomeBanner_();
    this.previousDirWasOnDrive_ = false;
    return;
  }

  if (this.welcomeHeaderCounter_ >= WELCOME_HEADER_COUNTER_LIMIT ||
      !this.directoryModel_.isDriveMounted()) {
    // The banner is already shown enough times or the drive FS is not mounted.
    // So, do nothing here.
    return;
  }

  if (!this.showOffers_) {
    // Because it is not necessary to show the offer, set
    // |useNewWelcomeBanner_| false here. Note that it probably should be able
    // to do this in the constructor, but there remains non-trivial path,
    // which may be causes |useNewWelcomeBanner_| == true's behavior even
    // if |showOffers_| is false.
    // TODO(hidehiko): Make sure if it is expected or not, and simplify
    // |showOffers_| if possible.
    this.useNewWelcomeBanner_ = false;
  }

  var self = this;
  if (self.useNewWelcomeBanner_) {
    // getSizeStats for Drive file system accesses to the server, so we should
    // minimize the invocation.
    chrome.fileBrowserPrivate.getSizeStats(
        util.makeFilesystemUrl(self.directoryModel_.getCurrentRootPath()),
        function(result) {
          var offerSpaceKb = util.boardIs('link') ?
              1024 * 1024 * 1024 :  // 1TB.
              100 * 1024 * 1024;  // 100GB.
          if (result && result.totalSizeKB >= offerSpaceKb) {
            self.useNewWelcomeBanner_ = false;
          }
          self.maybeShowWelcomeBanner_();
        });
  } else {
    self.maybeShowWelcomeBanner_();
  }
};

/**
 * Decides which banner should be shown, and show it. This method is designed
 * to be called only from checkSpaceAndMaybeShowWelcomeBanner_.
 * @private
 */
FileListBannerController.prototype.maybeShowWelcomeBanner_ = function() {
  if (this.directoryModel_.getFileList().length == 0 &&
      this.welcomeHeaderCounter_ == 0) {
    // Only show the full page banner if the header banner was never shown.
    // Do not increment the counter.
    // The timeout below is required because sometimes another
    // 'rescan-completed' event arrives shortly with non-empty file list.
    setTimeout(function() {
      if (this.isOnDrive() && this.welcomeHeaderCounter_ == 0) {
        this.prepareAndShowWelcomeBanner_('page', 'DRIVE_WELCOME_TEXT_LONG');
      }
    }.bind(this), 2000);
  } else {
    // We do not want to increment the counter when the user navigates
    // between different directories on Drive, but we increment the counter
    // once anyway to prevent the full page banner from showing.
    if (!this.previousDirWasOnDrive_ || this.welcomeHeaderCounter_ == 0) {
      this.setWelcomeHeaderCounter_(this.welcomeHeaderCounter_ + 1);
      this.prepareAndShowWelcomeBanner_('header', 'DRIVE_WELCOME_TEXT_SHORT');
    }
  }
  this.previousDirWasOnDrive_ = true;
};

/**
 * @return {boolean} True if current directory is on Drive.
 */
FileListBannerController.prototype.isOnDrive = function() {
  return this.directoryModel_.getCurrentRootType() === RootType.DRIVE;
};

/**
 * Shows the Drive Welcome banner.
 * @param {string} type 'page'|'head'|'none'.
 * @private
 */
FileListBannerController.prototype.showWelcomeBanner_ = function(type) {
  var container = this.document_.querySelector('.dialog-container');
  if (container.getAttribute('drive-welcome') != type) {
    container.setAttribute('drive-welcome', type);
    this.requestRelayout_(200);  // Resize only after the animation is done.
  }
};

/**
 * Update the UI when the current directory changes.
 *
 * @param {cr.Event} event The directory-changed event.
 * @private
 */
FileListBannerController.prototype.onDirectoryChanged_ = function(event) {
  var root = PathUtil.getTopDirectory(event.newDirEntry.fullPath);
  // Show (or hide) the low space warning.
  this.maybeShowLowSpaceWarning_(root);

  // Add or remove listener to show low space warning, if necessary.
  var isLowSpaceWarningTarget = this.isLowSpaceWarningTarget_(root);
  var previousRoot = PathUtil.getTopDirectory(event.previousDirEntry.fullPath);
  if (isLowSpaceWarningTarget !== this.isLowSpaceWarningTarget_(previousRoot)) {
    if (isLowSpaceWarningTarget) {
      chrome.fileBrowserPrivate.onDirectoryChanged.addListener(
          this.privateOnDirectoryChangedBound_);
    } else {
      chrome.fileBrowserPrivate.onDirectoryChanged.removeListener(
          this.privateOnDirectoryChangedBound_);
    }
  }

  if (!this.isOnDrive()) {
    this.cleanupWelcomeBanner_();
    this.authFailedBanner_.hidden = true;
  }

  this.updateDriveUnmountedPanel_();
  if (this.isOnDrive()) {
    this.unmountedPanel_.classList.remove('retry-enabled');
    this.maybeShowAuthFailBanner_();
  }
};

/**
 * @param {string} root Root directory to be checked.
 * @return {boolean} true if the file system specified by |root| is a target
 *     to show low space warning. Otherwise false.
 * @private
 */
FileListBannerController.prototype.isLowSpaceWarningTarget_ = function(root) {
  return (root == RootDirectory.DOWNLOADS || root == RootDirectory.DRIVE);
};

/**
 * Callback which is invoked when the file system has been changed.
 * @param {Object} event chrome.fileBrowserPrivate.onDirectoryChanged event.
 * @private
 */
FileListBannerController.prototype.privateOnDirectoryChanged_ = function(
    event) {
  var currentRoot = PathUtil.getTopDirectory(
      this.directoryModel_.getCurrentDirPath());
  var eventRoot = PathUtil.getTopDirectory(
      util.extractFilePath(event.directoryUrl));
  if (currentRoot == eventRoot) {
    // The file system we are currently on is changed.
    // So, check the free space.
    this.maybeShowLowSpaceWarning_(eventRoot);
  }
};

/**
 * Shows or hides the low space warning.
 * @param {string} root Root directory of the file system, which we are
 *     interested in.
 * @private
 */
FileListBannerController.prototype.maybeShowLowSpaceWarning_ = function(root) {
  // TODO(kaznacheev): Unify the two low space warning.
  var threshold = 0;
  if (root === RootDirectory.DOWNLOADS) {
    this.showLowDriveSpaceWarning_(false);
    threshold = 0.2;
  } else if (root === RootDirectory.DRIVE) {
    this.showLowDownloadsSpaceWarning_(false);
    threshold = 0.1;
  } else {
    // If the current file system is neither the DOWNLOAD nor the DRIVE,
    // just hide the warning.
    this.showLowDownloadsSpaceWarning_(false);
    this.showLowDriveSpaceWarning_(false);
    return;
  }

  var self = this;
  chrome.fileBrowserPrivate.getSizeStats(
      util.makeFilesystemUrl(root),
      function(sizeStats) {
        var currentRoot = PathUtil.getTopDirectory(
            self.directoryModel_.getCurrentDirPath());
        if (root != currentRoot) {
          // This happens when the current directory is moved during requesting
          // the file system size. Just ignore it.
          return;
        }

        // sizeStats is undefined, if some error occurs.
        var remainingRatio = (sizeStats && sizeStats.totalSizeKB > 0) ?
            (sizeStats.remainingSizeKB / sizeStats.totalSizeKB) : 1;
        var isLowDiskSpace = remainingRatio < threshold;
        if (root == RootDirectory.DOWNLOADS)
          self.showLowDownloadsSpaceWarning_(isLowDiskSpace);
        else
          self.showLowDriveSpaceWarning_(isLowDiskSpace, sizeStats);
      });
};

/**
 * removes the Drive Welcome banner.
 * @private
 */
FileListBannerController.prototype.cleanupWelcomeBanner_ = function() {
  this.showWelcomeBanner_('none');
};

/**
 * Notifies the file manager what layout must be recalculated.
 * @param {number} delay In milliseconds.
 * @private
 */
FileListBannerController.prototype.requestRelayout_ = function(delay) {
  var self = this;
  setTimeout(function() {
    cr.dispatchSimpleEvent(self, 'relayout');
  }, delay);
};

/**
 * Show or hide the "Low disk space" warning.
 * @param {boolean} show True if the box need to be shown.
 * @private
 */
FileListBannerController.prototype.showLowDownloadsSpaceWarning_ =
    function(show) {
  var box = this.document_.querySelector('.downloads-warning');

  if (box.hidden == !show) return;

  if (show) {
    var html = util.htmlUnescape(str('DOWNLOADS_DIRECTORY_WARNING'));
    box.innerHTML = html;
    var link = box.querySelector('a');
    link.href = DOWNLOADS_FAQ_URL;
    link.target = '_blank';
  } else {
    box.innerHTML = '';
  }

  box.hidden = !show;
  this.requestRelayout_(100);
};

/**
 * Creates contents for the DRIVE unmounted panel.
 * @private
 */
FileListBannerController.prototype.ensureDriveUnmountedPanelInitialized_ =
    function() {
  var panel = this.unmountedPanel_;
  if (panel.firstElementChild)
    return;

  var create = function(parent, tag, className, opt_textContent) {
    var div = panel.ownerDocument.createElement(tag);
    div.className = className;
    div.textContent = opt_textContent || '';
    parent.appendChild(div);
    return div;
  };

  var loading = create(panel, 'div', 'loading', str('DRIVE_LOADING'));
  var spinnerBox = create(loading, 'div', 'spinner-box');
  create(spinnerBox, 'div', 'spinner');
  create(panel, 'div', 'error', str('DRIVE_CANNOT_REACH'));

  var retryButton = create(panel, 'button', 'retry', str('DRIVE_RETRY'));
  retryButton.hidden = true;
  var vm = this.volumeManager_;
  retryButton.onclick = function() {
    vm.mountDrive(function() {}, function() {});
  };

  var learnMore = create(panel, 'a', 'learn-more plain-link',
                         str('DRIVE_LEARN_MORE'));
  learnMore.href = GOOGLE_DRIVE_ERROR_HELP_URL;
  learnMore.target = '_blank';
};

/**
 * Shows the panel when current directory is DRIVE and it's unmounted.
 * Hides it otherwise. The pannel shows spinner if DRIVE is mounting or
 * an error message if it failed.
 * @private
 */
FileListBannerController.prototype.updateDriveUnmountedPanel_ = function() {
  var node = this.document_.body;
  if (this.isOnDrive()) {
    var status = this.volumeManager_.getDriveStatus();
    if (status == VolumeManager.DriveStatus.MOUNTING ||
        status == VolumeManager.DriveStatus.ERROR) {
      this.ensureDriveUnmountedPanelInitialized_();
    }
    if (status == VolumeManager.DriveStatus.MOUNTING &&
        this.welcomeHeaderCounter_ == 0) {
      // Do not increment banner counter in order to not prevent the full
      // page banner of being shown (otherwise it would never be shown).
      this.showWelcomeBanner_('header', 'DRIVE_WELCOME_TEXT_SHORT');
    }
    if (status == VolumeManager.DriveStatus.ERROR)
      this.unmountedPanel_.classList.add('retry-enabled');
    else
      this.unmountedPanel_.classList.remove('retry-enabled');
    node.setAttribute('drive', status);
  } else {
    node.removeAttribute('drive');
  }
};

/**
 * Updates the visibility of Drive Connection Warning banner, retrieving the
 * current connection information.
 * @private
 */
FileListBannerController.prototype.maybeShowAuthFailBanner_ = function() {
  var connection = this.volumeManager_.getDriveConnectionState();
  var reasons = connection.reasons;
  var showDriveNotReachedMessage =
      this.isOnDrive() &&
      connection.type == VolumeManager.DriveConnectionType.OFFLINE &&
      // Show the banner only when authentication fails. Don't show it when the
      // drive service is disabled.
      reasons.indexOf(VolumeManager.DriveConnectionReason.NOT_READY) != -1 &&
      reasons.indexOf(VolumeManager.DriveConnectionReason.NO_SERVICE) == -1;
  this.authFailedBanner_.hidden = !showDriveNotReachedMessage;
};


text:
/*
 * Inventory Menu Views
 *
 * js/app/common/menu_views.js
 *
 * MENU VIEW ENTRY POINTS
 */

"use strict";

// Inventory Menu
class InventoryItemMenu extends Backbone.View {

  get events() {
    return {
      'click #projects': 'projects'
    };
  }

  projects(e) {
    e.preventDefault();
    Backbone.trigger('menu:click:projects');
  }
};

// Project Menu
class ProjectItemMenu extends MenuItem {
  get toggle() { return false; }

  constructor(options) {
    super(options);
  }

  onClickCallback(model) {
    App.viewFunctions.projects(model);
  }
};

class ProjectParentMenu extends Menu {
  constructor(options) {
    super(options);
  }

  renderCallback(model) {
    return new ProjectItemMenu({model: model});
  }
};

class ProjectMenu extends Backbone.View {
  get el() { return 'div#projects div.tab-choice-pane div.pane-nav'; }

  constructor(options) {
    super(options);
  }

  initialize() {
    _.bindAll(this);
  }

  render() {
    let menu = new ProjectParentMenu({collection: this.collection});
    this.$el.append(menu.render().el);
  }
};

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Ixudra\Imageable\Presenters;

use Laracasts\Presenter\Presenter;

use URL;

class ImagePresenter extends Presenter {

    public function imageUrl()
    {
        return URL::to($this->imageable->getImagePath() .'/'. $this->file_name);
    }

}


text:
from datetime import timedelta

from django.test import TestCase
from django.utils.timezone import datetime
from django.core.urlresolvers import reverse

from molo.core.tests.base import MoloTestCaseMixin
from molo.core.models import (SiteSettings, Main, Languages,
                              SiteLanguageRelation, ArticlePageTags,
                              SectionPageTags, FooterPage, ArticlePage)
from molo.core.tasks import promote_articles
from itertools import chain

class TestTags(MoloTestCaseMixin, TestCase):
    def setUp(self):
        self.mk_main()
        main = Main.objects.all().first()
        self.english = SiteLanguageRelation.objects.create(
            language_setting=Languages.for_site(main.get_site()),
            locale='en',
            is_active=True)

        self.french = SiteLanguageRelation.objects.create(
            language_setting=Languages.for_site(main.get_site()),
            locale='fr',
            is_active=True)
        self.spanish = SiteLanguageRelation.objects.create(
            language_setting=Languages.for_site(main.get_site()),
            locale='es',
            is_active=True)
        self.arabic = SiteLanguageRelation.objects.create(
            language_setting=Languages.for_site(main.get_site()),
            locale='ar',
            is_active=True)

        self.yourmind = self.mk_section(
            self.section_index, title='Your mind')
        self.yourbody = self.mk_section(
            self.section_index, title='Your body')
        self.yourmind_sub = self.mk_section(
            self.yourmind, title='Your mind subsection')

        self.yourmind_fr = self.mk_section_translation(
            self.yourmind, self.french, title='Your mind in french')
        self.yourmind_sub_fr = self.mk_section_translation(
            self.yourmind_sub, self.french,
            title='Your mind subsection in french')

        self.mk_main2()
        self.main2 = Main.objects.all().last()
        self.language_setting2 = Languages.objects.create(
            site_id=self.main2.get_site().pk)
        self.english2 = SiteLanguageRelation.objects.create(
            language_setting=self.language_setting2,
            locale='en',
            is_active=True)

        self.spanish = SiteLanguageRelation.objects.create(
            language_setting=self.language_setting2,
            locale='es',
            is_active=True)

        self.yourmind2 = self.mk_section(
            self.section_index2, title='Your mind2')
        self.yourmind_sub2 = self.mk_section(
            self.yourmind2, title='Your mind subsection2')

        self.site_settings = SiteSettings.for_site(main.get_site())
        self.site_settings2 = SiteSettings.for_site(self.main2.get_site())
        self.site_settings.enable_clickable_tags = True
        self.site_settings.enable_tag_navigation = True
        self.site_settings.save()

    def unique(self, g):
        s = set()
        for x in g:
            if x.pk in s:
                return False
            s.add(x.pk)
        return True

    def test_tag_nav_data_does_not_pull_in_footer_pages(self):
        self.mk_articles(parent=self.yourmind, count=2)
        footer = FooterPage(title='Test Footer Page')
        self.footer_index.add_child(instance=footer)
        footer.save_revision().publish()
        footer2 = FooterPage(title='Test Footer Page 2')
        self.footer_index.add_child(instance=footer2)
        footer2.save_revision().publish()
        footer3 = FooterPage(title='Test Footer Page 3')
        self.footer_index.add_child(instance=footer3)
        footer3.save_revision().publish()
        footer_pks = [footer.pk, footer2.pk, footer3.pk]

        response = self.client.get('/')
        data = response.context['tag_nav_data']
        hoempage_articles = []
        for section, section_list in data['sections']:
            homepage_articles = list(chain(hoempage_articles, section_list))
        for tag, tag_list in data['tags_list']:
            homepage_articles = list(chain(homepage_articles, tag_list))
        homepage_articles = list(chain(
            homepage_articles, data['latest_articles']))
        for article in homepage_articles:
            self.assertFalse(article.pk in footer_pks)

    def test_article_not_repeated_in_section_for_tag_navigation_enabled(self):
        tag = self.mk_tag(parent=self.tag_index)
        tag.feature_in_section = True
        tag.save_revision().publish()
        articles = self.mk_articles(parent=self.yourmind, count=30)
        other_articles = self.mk_articles(parent=self.yourbody, count=10)
        for article in articles:
            ArticlePageTags.objects.create(page=article, tag=tag)
        for article in other_articles:
            ArticlePageTags.objects.create(page=article, tag=tag)
        SectionPageTags.objects.create(page=self.yourmind, tag=tag)
        SectionPageTags.objects.create(page=self.yourbody, tag=tag)

        response = self.client.get(self.yourmind.url)
        tag_articles = response.context['tags'][0][1]
        section_articles = response.context['articles']
        all_section_articles = list(chain(section_articles, tag_articles))
        self.assertTrue(self.unique(all_section_articles))
        self.assertContains(response, tag.title)
        self.assertEquals(len(tag_articles), 4)

    def test_article_only_site_specific_artcles_show_under_tag(self):
        tag = self.mk_tag(parent=self.tag_index)
        tag.feature_in_homepage = True
        tag.save_revision().publish()
        articles = self.mk_articles(
            parent=self.yourmind,
            featured_in_latest_start_date=datetime.now(),
            featured_in_homepage_start_date=datetime.now(), count=5)
        for article in articles:
            ArticlePageTags.objects.create(page=article, tag=tag)

        promote_articles()
        self.user = self.login()
        response = self.client.post(reverse(
            'wagtailadmin_pages:copy',
            args=(self.main.id,)),
            data={
                'new_title': 'blank',
                'new_slug': 'blank',
                'new_parent_page': self.root.id,
                'copy_subpages': 'true',
                'publish_copies': 'true'})
        self.assertEquals(response.status_code, 302)
        response = self.client.get('/tags/' + tag.slug + '/')
        self.assertEquals(len(response.context['object_list']), 5)
        for article in response.context['object_list']:
            self.assertEquals(article.get_site().pk, self.main.get_site().pk)
        response = self.client.get('/tags/bogus/')
        self.assertEquals(response.status_code, 404)

    def test_new_tag_article_relations_made_when_copying_site(self):
        tag = self.mk_tag(parent=self.tag_index)
        tag.feature_in_homepage = True
        tag.save_revision().publish()
        articles = self.mk_articles(
            parent=self.yourmind,
            featured_in_latest_start_date=datetime.now(),
            featured_in_homepage_start_date=datetime.now(), count=30)
        for article in articles:
            ArticlePageTags.objects.create(page=article, tag=tag)

        promote_articles()

        self.user = self.login()
        response = self.client.post(reverse(
            'wagtailadmin_pages:copy',
            args=(self.main.id,)),
            data={
                'new_title': 'blank',
                'new_slug': 'blank',
                'new_parent_page': self.root.id,
                'copy_subpages': 'true',
                'publish_copies': 'true'})
        self.assertEquals(response.status_code, 302)
        main3 = Main.objects.get(slug='blank')
        new_articles = ArticlePage.objects.descendant_of(main3)
        new_article_tags = ArticlePageTags.objects.filter(
            page__in=new_articles)
        for article_tag_relation in new_article_tags:
            self.assertEquals(
                article_tag_relation.tag.get_site().pk, main3.get_site().pk)

    def test_latest_articles_get_priority_when_tag_navigation_enabled(self):
        tag = self.mk_tag(parent=self.tag_index)
        tag.feature_in_homepage = True
        tag.save_revision().publish()
        articles = self.mk_articles(
            parent=self.yourmind,
            featured_in_latest_start_date=(
                datetime.now() - timedelta(days=1)),
            featured_in_homepage_start_date=datetime.now(), count=30)
        latest_of_latest_articles = self.mk_article(
            parent=self.yourmind, featured_in_latest_start_date=datetime.now(),
            featured_in_homepage_start_date=datetime.now())
        for article in articles:
            ArticlePageTags.objects.create(page=article, tag=tag)

        promote_articles()

        response = self.client.get('/')
        latest_articles = response.context['tag_nav_data']['latest_articles']
        self.assertEqual(latest_articles[0].pk, latest_of_latest_articles.pk)

    def test_latest_articles_translated_when_tag_navigation_enabled(self):
        article_1 = self.mk_article(
            self.yourmind, title='article-1', featured_in_latest_start_date=(
                datetime.now() - timedelta(days=1)), featured_in_latest=True,
            featured_in_homepage_start_date=datetime.now())
        article_2 = self.mk_article(
            self.yourmind, title='article-2', featured_in_latest_start_date=(
                datetime.now() - timedelta(days=1)), featured_in_latest=True,
            featured_in_homepage_start_date=datetime.now())
        tag = self.mk_tag(parent=self.tag_index)
        ArticlePageTags.objects.create(page=article_1, tag=tag)
        ArticlePageTags.objects.create(page=article_2, tag=tag)

        # make the translation for the article and the tag
        fr_article_1 = self.mk_article_translation(
            article_1,
            self.french,
            title=article_1.title + ' in french',)
        self.mk_tag_translation(
            tag,
            self.french,
            title=tag.title + ' in french',)
        tag.feature_in_homepage = True
        tag.save_revision().publish()

        promote_articles()

        self.client.get('/locale/fr/')
        response = self.client.get('/')
        latest_articles = response.context['tag_nav_data']['latest_articles']
        self.assertTrue(fr_article_1 in latest_articles)
        self.assertTrue(article_2 in latest_articles)
        self.assertFalse(article_1 in latest_articles)

    def test_latest_articles_show_only_translations_with_tag_navigation(self):
        self.site_settings.show_only_translated_pages = True
        self.site_settings.save()

        article_1 = self.mk_article(
            self.yourmind, title='article-1', featured_in_latest_start_date=(
                datetime.now() - timedelta(days=1)), featured_in_latest=True,
            featured_in_homepage_start_date=datetime.now())
        article_2 = self.mk_article(
            self.yourmind, title='article-2', featured_in_latest_start_date=(
                datetime.now() - timedelta(days=1)), featured_in_latest=True,
            featured_in_homepage_start_date=datetime.now())
        tag = self.mk_tag(parent=self.tag_index)
        ArticlePageTags.objects.create(page=article_1, tag=tag)
        ArticlePageTags.objects.create(page=article_2, tag=tag)

        tag.feature_in_homepage = True
        tag.save_revision().publish()
        promote_articles()

        # Test no articles are shown if we don't have translations
        self.client.get('/locale/fr/')
        response = self.client.get('/')
        latest_articles = response.context['tag_nav_data']['latest_articles']
        self.assertFalse(latest_articles is None)

        # make the translation for the article and the tag
        fr_article_1 = self.mk_article_translation(
            article_1,
            self.french,
            title=article_1.title + ' in french',)
        self.mk_tag_translation(
            tag,
            self.french,
            title=tag.title + ' in french',)

        self.client.get('/locale/fr/')
        response = self.client.get('/')
        latest_articles = response.context['tag_nav_data']['latest_articles']
        self.assertTrue(fr_article_1 in latest_articles)
        self.assertFalse(article_2 in latest_articles)
        self.assertFalse(article_1 in latest_articles)

    def test_article_not_repeated_when_tag_navigation_enabled_homepage(self):
        tag = self.mk_tag(parent=self.tag_index)
        tag.feature_in_homepage = True
        tag.save_revision().publish()
        articles = self.mk_articles(
            parent=self.yourmind,
            featured_in_latest_start_date=datetime.now(),
            featured_in_homepage_start_date=datetime.now(), count=30)
        for article in articles:
            ArticlePageTags.objects.create(page=article, tag=tag)

        promote_articles()

        response = self.client.get('/')
        data = response.context['tag_nav_data']
        hoempage_articles = []
        for section, section_list in data['sections']:
            homepage_articles = list(chain(hoempage_articles, section_list))
        for tag, tag_list in data['tags_list']:
            homepage_articles = list(chain(homepage_articles, tag_list))
        homepage_articles = list(chain(
            homepage_articles, data['latest_articles']))

        self.assertTrue(self.unique(homepage_articles))

    def test_tag_cloud_homepage(self):
        tag = self.mk_tag(parent=self.tag_index)
        response = self.client.get('/')
        self.assertContains(response, tag.title)

    def test_tag_cloud_homepage_translation(self):
        tag = self.mk_tag(parent=self.tag_index)
        self.mk_tag_translation(
            tag,
            self.french,
            title=tag.title + ' in french',)

        self.client.get('/locale/fr/')
        response = self.client.get('/')
        self.assertContains(response, tag.title + ' in french')

    def test_tag_navigation_setting_overrides_other_tags(self):
        article = self.mk_article(self.yourmind, title='article')
        article.tags.add("old tag")
        article.save_revision().publish()

        tag = self.mk_tag(parent=self.tag_index)
        ArticlePageTags.objects.create(page=article, tag=tag)
        article.save_revision().publish()

        response = self.client.get(article.url)
        self.assertNotContains(response, 'old tag')
        self.assertContains(response, tag.title)

    def test_articles_within_tag(self):
        article1 = self.mk_article(self.yourmind, title='article 1')
        article2 = self.mk_article(self.yourmind, title='article 2')
        article3 = self.mk_article(self.yourmind, title='article 3')

        tag = self.mk_tag(parent=self.tag_index)
        ArticlePageTags.objects.create(page=article1, tag=tag)
        ArticlePageTags.objects.create(page=article2, tag=tag)
        ArticlePageTags.objects.create(page=article3, tag=tag)

        response = self.client.get('/tags/' + tag.slug + '/')
        self.assertContains(
            response,
            '<a href="/sections-main-1/your-mind/article-1/"')
        self.assertContains(
            response,
            '<a href="/sections-main-1/your-mind/article-2/"')
        self.assertContains(
            response,
            '<a href="/sections-main-1/your-mind/article-3/"')

        # check that they ordered by the latest first
        response_articles_list = response.context_data['object_list']
        self.assertEquals(article3.pk, response_articles_list[0].pk)
        self.assertEquals(article2.pk, response_articles_list[1].pk)

    def test_articles_within_tag_order_by_first_published_at(self):
        article1 = self.mk_article(self.yourmind, title='article 1',
                                   first_published_at=datetime.now())
        article2 = self.mk_article(self.yourmind, title='article 2',
                                   first_published_at=datetime.now())
        article3 = self.mk_article(self.yourmind, title='article 3',
                                   first_published_at=datetime.now())

        tag = self.mk_tag(parent=self.tag_index)
        ArticlePageTags.objects.create(page=article1, tag=tag)
        ArticlePageTags.objects.create(page=article2, tag=tag)
        ArticlePageTags.objects.create(page=article3, tag=tag)
        # edit the articles
        article1.title = "Edited article"
        article1.save_revision().publish()
        article3.title = "Another edited article"
        article3.save_revision().publish()

        response = self.client.get('/tags/' + tag.slug + '/')

        # test that editing does not change the order of the articles
        response_articles_list = response.context_data['object_list']
        self.assertEquals(article3.pk, response_articles_list[0].pk)
        self.assertEquals(article2.pk, response_articles_list[1].pk)
        self.assertEquals(article1.pk, response_articles_list[2].pk)

    def test_promoted_tags(self):
        articles = self.mk_articles(self.yourmind, count=5)
        tag = self.mk_tag(parent=self.tag_index)
        for article in articles:
            ArticlePageTags.objects.create(page=article, tag=tag)

        tag.feature_in_homepage = True
        tag.save_revision().publish()

        response = self.client.get('/')
        self.assertEquals(
            str(response.context['tag_nav_data']['tags_list']),
            '[(<Tag: Test Tag>, [<ArticlePage: Test page 0>, <ArticlePage'
            ': Test page 1>, <ArticlePage: Test page 2>, <ArticleP'
            'age: Test page 3>])]')
        self.assertNotContains(response, 'Test Page 5')

        tag = self.mk_tag(parent=self.tag_index, title='Not Promoted Tag 1')
        tag = self.mk_tag(parent=self.tag_index, title='Not Promoted Tag 2')

        articles = self.mk_articles(self.yourmind, count=5)
        tag = self.mk_tag(parent=self.tag_index, title='Test Tag 2')
        for article in articles:
            ArticlePageTags.objects.create(page=article, tag=tag)

        tag.feature_in_homepage = True
        tag.save_revision().publish()

        response = self.client.get('/')
        self.assertEquals(
            str(response.context['tag_nav_data']['tags_list']),
            '[(<Tag: Test Tag>, [<ArticlePage: Test page 0>, <ArticlePage: '
            'Test page 1>, <ArticlePage: Test page 2>, <ArticlePage: Test p'
            'age 3>]), (<Tag: Test Tag 2>, [<ArticlePage: Test page 0>, <Ar'
            'ticlePage: Test page 1>, <ArticlePage: Test page 2>, <Articl'
            'ePage: Test page 3>])]')
        self.assertNotContains(response, 'Test Page 5')

    def test_tag_navigation_shows_correct_tag_for_locale(self):
        article = self.mk_article(self.yourmind, title='article')

        tag = self.mk_tag(parent=self.tag_index)
        ArticlePageTags.objects.create(page=article, tag=tag)

        # make the translation for the article and the tag
        self.mk_article_translation(
            article,
            self.french,
            title=article.title + ' in french',)
        self.mk_tag_translation(
            tag,
            self.french,
            title=tag.title + ' in french',)

        self.client.get('/locale/fr/')
        response = self.client.get(
            '/sections-main-1/your-mind/article-in-french/')
        self.assertContains(response, 'Test Tag in french')

    def test_articles_with_the_same_tag(self):
        self.site_settings.enable_tag_navigation = False
        self.site_settings.save()
        # create two articles with the same tag and check that they can
        # be retrieved
        new_section = self.mk_section(
            self.section_index, title="New Section", slug="new-section")
        first_article = self.mk_article(new_section, title="First article", )
        second_article = self.mk_article(new_section, title="Second article", )

        # add common tag to both articles
        first_article.tags.add("common")
        first_article.save_revision().publish()
        second_article.tags.add("common")
        second_article.save_revision().publish()

        # create another article that doesn't have the tag, and check that
        # it will be excluded from the return list
        self.mk_article(new_section, title="Third article", )

        response = self.client.get(
            reverse("tags_list", kwargs={"tag_name": "common"})
        )
        self.assertEqual(2, len(list(response.context["object_list"])))
        self.assertIn(first_article, list(response.context["object_list"]))
        self.assertIn(second_article, list(response.context["object_list"]))


text:
namespace OpenProtocolInterpreter.AutomaticManualMode
{
    /// <summary>
    /// Automatic/Manual mode acknowledge
    /// <para>Acknowledgement of automatic/manual mode upload.</para>
    /// <para>Message sent by: Integrator</para>
    /// <para>Answer: None</para>
    /// </summary>
    public class Mid0402 : Mid, IAutomaticManualMode, IIntegrator
    {
        private const int LAST_REVISION = 1;
        public const int MID = 402;

        public Mid0402() : base(MID, LAST_REVISION) { }

        public Mid0402(Header header) : base(header)
        {

        }
    }
}


text:
import argparse
import logging
import multiprocessing
import os
import os.path
import pwd
import shutil
import signal
import sys

import fooster.web

import mcp.config

parser = argparse.ArgumentParser(description='start a multi-server management framework for Armagetron Advanced')
parser.add_argument('-a', '--address', dest='address', help='address to bind')
parser.add_argument('-p', '--port', type=int, dest='port', help='port to bind')
parser.add_argument('-t', '--template', dest='template', help='template directory to use')
parser.add_argument('-l', '--log', dest='log', help='log directory to use')
parser.add_argument('--db', '--database', dest='database', help='database directory to use')
parser.add_argument('--prefix', dest='prefix', help='prefix directory to use')
parser.add_argument('--sources', dest='sources', help='sources directory to use')
parser.add_argument('--config', dest='config', help='config directory to use')
parser.add_argument('--scripting', dest='scripting', help='scripting directory to use')
parser.add_argument('--tmp', dest='tmp', help='tmp directory to use')
parser.add_argument('--sftpkey', dest='sftpkey', help='sftp key to use')
parser.add_argument('--user', dest='user', help='user to drop to if run as root')
parser.add_argument('--container', action='store_true', dest='container', help='whether to put servers and scripts in a container')

args = parser.parse_args()

if args.address:
    mcp.config.addr = (args.address, mcp.config.addr[1])

if args.port:
    mcp.config.addr = (mcp.config.addr[0], args.port)

if args.template:
    config.template = args.template

if args.log:
    if args.log == 'none':
        mcp.config.log = None
        mcp.config.cmdlog = None
        mcp.config.httpdlog = None
        mcp.config.accesslog = None
    else:
        mcp.config.log = os.path.join(args.log, 'manager.log')
        mcp.config.cmdlog = os.path.join(args.log, 'command.log')
        mcp.config.httplog = os.path.join(args.log, 'httpd.log')
        mcp.config.accesslog = os.path.join(args.log, 'access.log')

if args.database:
    mcp.config.database = os.path.abspath(args.database)

if args.prefix:
    mcp.config.prefix = os.path.abspath(args.prefix)

if args.sources:
    mcp.config.sources = os.path.abspath(args.sources)

if args.config:
    mcp.config.config = os.path.abspath(args.config)

if args.scripting:
    mcp.config.scripting = os.path.abspath(args.scripting)

if args.tmp:
    mcp.config.tmp = os.path.abspath(args.tmp)

if args.sftpkey:
    mcp.config.sftpkey = os.path.abspath(args.sftpkey)

if args.user:
    mcp.config.user = args.user

if args.container:
    mcp.config.container = args.container

if mcp.config.log:
    logging.getLogger('mcp').addHandler(logging.StreamHandler())
    logging.getLogger('mcp').addHandler(logging.FileHandler(mcp.config.log))

if mcp.config.cmdlog:
    logging.getLogger('cmd').addHandler(logging.FileHandler(mcp.config.cmdlog))

if mcp.config.httpdlog:
    logging.getLogger('web').addHandler(logging.FileHandler(mcp.config.httpdlog))

if mcp.config.accesslog:
    logging.getLogger('http').handlers = []

    accesslog_handler = logging.FileHandler(mcp.config.accesslog)
    accesslog_handler.setFormatter(fooster.web.HTTPLogFormatter())

    logging.getLogger('http').addHandler(accesslog_handler)

from mcp import name, version

import mcp.initial

import mcp.common.util

if os.geteuid() == 0:
    pid = os.fork()
    if pid == 0:
        mcp.common.util.demote(mcp.config.user)
        mcp.initial.check()
        sys.exit(0)
    else:
        os.waitpid(pid, 0)
else:
    # check for initial files
    mcp.initial.check()

import mcp.service.manager

log = logging.getLogger('mcp')

log.info(name + ' ' + version + ' starting...')

if mcp.config.container and os.geteuid() != 0:
    log.error('Root privileges required to create containers.\nNote: The root privileges will be dropped by all daemons except the server management daemon.')
    sys.exit(1)

# fix multiprocessing ctrl+c
signal.signal(signal.SIGINT, signal.SIG_IGN)

# start server manager
mcp.service.manager.start()
# drop root privileges if necessary
if os.geteuid() == 0:
    mcp.common.util.demote(mcp.config.user)

import mcp.common.daemon

# fill in daemon details
mcp.common.daemon.pid = os.getpid()
mcp.common.daemon.sync = multiprocessing.Manager()

import mcp.service.http
import mcp.service.rotate
import mcp.service.update
if os.path.exists(mcp.config.sftpkey):
    import mcp.service.sftp

# start everything else
mcp.service.rotate.start()
mcp.service.update.start()

if os.path.exists(mcp.config.sftpkey):
    mcp.service.sftp.start()

mcp.service.http.start()

# cleanup function
def exit(signum, frame):
    mcp.service.http.stop()

# restart function
def restart(signum, frame):
    mcp.service.manager.stop()
    mcp.service.manager.start()

# use the function for both SIGINT and SIGTERM
for sig in signal.SIGINT, signal.SIGTERM:
    signal.signal(sig, exit)

# use SIGUSR1 for restart
signal.signal(signal.SIGUSR1, restart)

# wait for http to finish
mcp.service.http.join()

# stop background services
if os.path.exists(mcp.config.sftpkey):
    mcp.service.sftp.stop()

mcp.service.update.stop()
mcp.service.rotate.stop()
mcp.service.manager.stop()


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
//*********************************************************

//
// Scenario7.xaml.cpp
// Implementation of the Scenario7 class
//

#include "pch.h"
#include "Scenario7_ContextualCommands.xaml.h"
#include "MainPage.xaml.h"
#include "GridViewPage.xaml.h"

using namespace SDKSample;
using namespace SDKSample::AppBarControl;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Interop;

SDKSample::AppBarControl::Scenario7::Scenario7()
{
    InitializeComponent();
	rootPage = MainPage::Current;
}

void SDKSample::AppBarControl::Scenario7::OnNavigatedTo(NavigationEventArgs^ e)
{

}

void SDKSample::AppBarControl::Scenario7::Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
	TypeName type = { GridViewPage::typeid->FullName, TypeKind::Custom };
	rootPage->Frame->Navigate(type, rootPage);
}


text:
package it.unibz.inf.ontop.model.atom.impl;

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import it.unibz.inf.ontop.model.term.Variable;
import it.unibz.inf.ontop.model.term.VariableOrGroundTerm;

import java.util.HashSet;
import java.util.Set;

public class DataAtomTools {

    /**
     * TODO: explain
     */
    public static boolean areVariablesDistinct(ImmutableList<? extends VariableOrGroundTerm> arguments) {
        Set<Variable> encounteredVariables = new HashSet<>();

        for (VariableOrGroundTerm argument : arguments) {
            if (argument instanceof Variable) {
                if (!encounteredVariables.add((Variable)argument)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean isVariableOnly(ImmutableCollection<? extends VariableOrGroundTerm> arguments) {
        for (VariableOrGroundTerm argument : arguments) {
            if (argument.isGround()) {
                return false;
            }
        }
        return true;
    }
}


text:
<?php

App::uses('TaxonomyAppModel', 'Taxonomy.Model');

/**
 * Term
 *
 * @category Taxonomy.Model
 * @package  Croogo.Taxonomy.Model
 * @version  1.0
 * @author   Fahad Ibnay Heylaal <contact@fahad19.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class Term extends TaxonomyAppModel {

/**
 * Model name
 *
 * @var string
 * @access public
 */
	public $name = 'Term';

	public $findMethods = array(
		'byVocabulary' => true,
	);

/**
 * Behaviors used by the Model
 *
 * @var array
 * @access public
 */
	public $actsAs = array(
		'Croogo.Cached' => array(
			'groups' => array(
				'taxonomy',
				'nodes',
			),
		),
		'Croogo.Trackable',
	);

/**
 * Validation
 *
 * @var array
 * @access public
 */
	public $validate = array(
		'slug' => array(
			'isUnique' => array(
				'rule' => 'isUnique',
				'message' => 'This slug has already been taken.',
			),
			'minLength' => array(
				'rule' => array('minLength', 1),
				'message' => 'Slug cannot be empty.',
			),
		),
	);

/**
 * Model associations: hasAndBelongsToMany
 *
 * @var array
 * @access public
 */
	public $hasAndBelongsToMany = array(
		'Vocabulary' => array(
			'className' => 'Taxonomy.Vocabulary',
			'with' => 'Taxonomy',
			'joinTable' => 'taxonomy',
			'foreignKey' => 'term_id',
			'associationForeignKey' => 'vocabulary_id',
			'unique' => true,
		),
	);

/**
 * Save Term and return ID.
 * If another Term with same slug exists, return ID of that Term without saving.
 *
 * @param  array $data
 * @return integer
 */
	public function saveAndGetId($data) {
		if (!array_key_exists($this->alias, $data)) {
			$data = array($this->alias => $data);
		}
		$termId = $this->field('id', array(
			$this->escapeField('slug') => $data[$this->alias]['slug'],
		));

		$this->id = false;
		if ($termId) {
			$this->id = $termId;
		}
		if ($this->save($data)) {
			return $this->id;
		}

		return false;
	}

/**
 * Allow delete on whether given Term has any association left with Taxonomy
 *
 * @return bool
 */
	public function beforeDelete($cascade = true) {
		$Taxonomy = ClassRegistry::init('Taxonomy.Taxonomy');
		$count = $Taxonomy->find('count', array(
			'recursive' => -1,
			'conditions' => array(
				$Taxonomy->escapeField('term_id') => $this->id,
			),
		));
		return $count === 0;
	}

/**
 * Convenience method to check whether term exists within a vocabulary
 *
 * @param integer $id Term Id
 * @param integer $vocabularyId Vocabulary Id
 * @param integer $taxonomyId Taxonomy Id
 * @return bool True if Term exists in Vocabulary
 */
	public function isInVocabulary($id, $vocabularyId, $taxonomyId = null) {
		$conditions = array('term_id' => $id, 'vocabulary_id' => $vocabularyId);
		if (!is_null($taxonomyId)) {
			$conditions['Taxonomy.id !='] = $taxonomyId;
		}
		return $this->Vocabulary->Taxonomy->hasAny($conditions);
	}

/**
 * Save term
 *
 * @see Term::_save()
 * @return array|bool Array of saved term or boolean false
 */
	public function add($data, $vocabularyId) {
		return $this->_save($data, $vocabularyId);
	}

/**
 * Edit term
 *
 * @see Term::_save()
 * @return array|bool Array of saved term or boolean false
 */
	public function edit($data, $vocabularyId) {
		$id = $data[$this->alias][$this->primaryKey];
		$slug = $data[$this->alias]['slug'];

		if ($this->hasSlugChanged($id, $slug) && $this->slugExists($slug)) {
			$edited = false;
		} else {
			$taxonomyId = !empty($data['Taxonomy']['id']) ? $data['Taxonomy']['id'] : null;
			$edited = $this->_save($data, $vocabularyId, $taxonomyId);
		}
		return $edited;
	}

/**
 * Checks wether slug has changed for given Term id
 *
 * @param int $id Term Id
 * @param string $slug Slug
 * @return bool True if slug has changed
 * @throws NotFoundException
 */
	public function hasSlugChanged($id, $slug) {
		if (!is_numeric($id) || !$this->exists($id)) {
			throw new NotFoundException(__d('croogo', 'Invalid Term Id'));
		}
		return $this->field('slug', array($this->escapeField() => $id)) != $slug;
	}

/**
 * Convenience check for slug
 *
 * @return bool
 */
	public function slugExists($slug) {
		return $this->hasAny(compact('slug'));
	}

/**
 * Remove term
 *
 * @param integer $id Term Id
 * @param integer $vocabularyId Vocabulary Id
 */
	public function remove($id, $vocabularyId) {
		$taxonomyId = $this->Vocabulary->Taxonomy->field('id', array(
			'term_id' => $id, 'vocabulary_id' => $vocabularyId
		));
		$this->setScopeForTaxonomy($vocabularyId);
		return $this->Taxonomy->delete($taxonomyId) && $this->delete($id);
	}

/**
 * Save new/updated term data
 *
 * @param array $data Term data
 * @param integer $vocabularyId Vocabulary Id
 * @param integer $taxonomyId Taxonomy Id
 */
	protected function _save($data, $vocabularyId, $taxonomyId = null) {
		$added = false;

		$termId = $this->saveAndGetId($data);
		if (!$this->isInVocabulary($termId, $vocabularyId, $taxonomyId)) {
			$this->setScopeForTaxonomy($vocabularyId);
			$dataToPersist = array(
				'parent_id' => $data['Taxonomy']['parent_id'],
				'term_id' => $termId,
				'vocabulary_id' => $vocabularyId,
			);
			if (!is_null($taxonomyId)) {
				$dataToPersist['id'] = $taxonomyId;
			}
			$added = $this->Taxonomy->save($dataToPersist);
		}
		return $added;
	}

	protected function _findByVocabulary($state, $query, $results = array()) {
		static $termsId = null;
		if (empty($query['vocabulary_id'])) {
			trigger_error(__d('croogo', '"vocabulary_id" key not found'));
		}
		if ($state == 'before') {
			$vocabularyAlias = $this->Vocabulary->field('alias', array('id' => $query['vocabulary_id']));
			$termsId = $this->Vocabulary->Taxonomy->getTree($vocabularyAlias, array('key' => 'id', 'value' => 'title'));
			$defaultQuery = array(
				'conditions' => array(
					$this->escapeField() => array_keys($termsId)
				)
			);
			return array_merge_recursive($defaultQuery, (array)$query);
		}

		$ordered = array_keys($termsId);
		$terms = array();
		foreach ($results as $tempTerm) {
			$term = $tempTerm;
			$id = $term[$this->alias][$this->primaryKey];
			$term[$this->alias]['indent'] = substr_count($termsId[$id], '_');
			$position = array_search($id, $ordered);
			$terms[$position] = $term;
		}
		ksort($terms);

		$termsId = null;
		return $terms;
	}

/**
 * Set Scope
 *
 * @param integer $vocabularyId Vocabulary Id
 */
	public function setScopeForTaxonomy($vocabularyId) {
		$scopeSettings = array('scope' => array(
			'Taxonomy.vocabulary_id' => $vocabularyId,
		));
		if ($this->Vocabulary->Taxonomy->Behaviors->loaded('Tree')) {
			$this->Vocabulary->Taxonomy->Behaviors->Tree->setup($this->Vocabulary->Taxonomy, $scopeSettings);
		} else {
			$this->Vocabulary->Taxonomy->Behaviors->load('Tree', $scopeSettings);
		}
	}
}


text:
module PathRewrite
  class PathController < ActionController::Base

    def rewrite
      rewrite = PathTranslation.find_by(old_path: "/#{params["path"]}") or raise ActionController::RoutingError.new("Not Found")

      Rails.logger.debug "Redirecting #{rewrite.old_path} to #{rewrite.new_path} from request #{request.url}"

      redirect_to rewrite.new_path, status: 301
    end

  end
end


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Alert component - UIkit tests</title>

Alert

This is an alert using an a element as close button.

This is a success alert using an a element as close button.

This is a warning alert using an a element as close button.

This is a danger alert using an a element as close button.

Alert large

                <button type="button" class="uk-alert-close uk-close"></button>

Today's headline

This is an alert using an button element as close button. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.

                <button type="button" class="uk-alert-close uk-close"></button>

Today's headline

This is a success alert using an button element as close button. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.

                <button type="button" class="uk-alert-close uk-close"></button>

Today's headline

This is a warning alert using an button element as close button. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.

                <button type="button" class="uk-alert-close uk-close"></button>

Today's headline

This is a danger alert using an button element as close button. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.


text:
<?php

namespace Lindelius\JWT\Tests;

use Lindelius\JWT\Exception\InvalidJwtException;
use Lindelius\JWT\Exception\InvalidSignatureException;
use Lindelius\JWT\Exception\JwtException;
use Lindelius\JWT\Tests\JWT\TestJWT;
use PHPUnit\Framework\TestCase;
use TypeError;

final class JWTTest extends TestCase
{
    use TestDataProviders;

    /**
     * @return void
     * @throws JwtException
     */
    public function testCreateWithUnsupportedAlgorithm(): void
    {
        $this->expectException(JwtException::class);
        $this->expectExceptionMessage('Unsupported algorithm ("ABC123").');

        $jwt = TestJWT::create('ABC123');
        $jwt->encode('my_key');
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testDecodeWithUnsupportedAlgorithm(): void
    {
        $this->expectException(JwtException::class);
        $this->expectExceptionMessage('Unsupported algorithm ("ABC123").');

        $jwt = TestJWT::decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJBQkMxMjMifQ.eyJzb21lX2ZpZWxkIjoiYW55X3ZhbHVlIn0.92nuM1zI5H8lARijnJS_NOEe1at9C38kxJxpgHc9D6Q');
        $jwt->verify('my_key');
    }

    /**
     * @dataProvider invalidKeyProvider
     * @param  mixed $key
     * @return void
     * @throws JwtException
     */
    public function testDecodeWithInvalidKey($key): void
    {
        $this->expectException(InvalidJwtException::class);
        $this->expectExceptionMessage('Invalid key.');

        $decodedJwt = TestJWT::decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lX2ZpZWxkIjoiYW55X3ZhbHVlIn0.yQz7d3ZjXJ508tZedOxG3aZPEUVltphXrGFz6lE6Jhk');
        $decodedJwt->verify($key);
    }

    /**
     * @dataProvider invalidKeyProvider
     * @param  mixed $key
     * @return void
     * @throws JwtException
     */
    public function testEncodeWithInvalidKey($key): void
    {
        $this->expectException(InvalidJwtException::class);
        $this->expectExceptionMessage('Invalid key.');

        $jwt = TestJWT::create(TestJWT::HS256);
        $jwt->setClaim('some_field', 'any_value');
        $jwt->encode($key);
    }

    /**
     * @dataProvider invalidAlgorithmProvider
     * @param  mixed $algorithm
     * @return void
     * @throws JwtException
     */
    public function testCreateWithInvalidAlgorithm($algorithm): void
    {
        $this->expectException(TypeError::class);

        $jwt = TestJWT::create($algorithm);
        $jwt->encode('my_key');
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testDecodeWithInvalidAlgorithm(): void
    {
        $this->expectException(JwtException::class);
        $this->expectExceptionMessage('Unsupported algorithm ("1337").');

        $jwt = TestJWT::decode('eyJ0eXAiOiJKV1QiLCJhbGciOjEzMzd9.eyJzb21lX2ZpZWxkIjoiYW55X3ZhbHVlIn0.q4UyVTIKIamLj8ZvlaQMO_yUblMXHwJ_k3qgeGzrnO0');
        $jwt->verify('my_key');
    }

    /**
     * @dataProvider invalidHashProvider
     * @param  mixed $hash
     * @return void
     * @throws JwtException
     */
    public function testDecodeWithInvalidHash($hash): void
    {
        $this->expectException(TypeError::class);

        TestJWT::decode($hash);
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testDecodeMalformedJWT(): void
    {
        $this->expectException(InvalidJwtException::class);
        $this->expectExceptionMessage('Unexpected number of JWT segments.');

        TestJWT::decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lX2ZpZWxkIjoiYW55X3ZhbHVlIn0');
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testDecodeWithIncorrectKeyId(): void
    {
        $this->expectException(InvalidJwtException::class);
        $this->expectExceptionMessage('Unable to find the correct decode key.');

        $keys = ['correct_kid' => 'my_key'];

        $jwt = TestJWT::create(TestJWT::HS256);
        $jwt->setHeaderField('kid', 'wrong_kid');
        $jwt->setClaim('some_field', 'any_value');

        $decodedJwt = TestJWT::decode($jwt->encode('my_key'));
        $decodedJwt->verify($keys);
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testFullLifeCycleHS256(): void
    {
        $jwt = TestJWT::create(TestJWT::HS256);
        $jwt->setClaim('some_field', 'any_value');
        $jwt->encode('my_key');

        $decodedJwt = TestJWT::decode($jwt->getHash());
        $decodedJwt->verify('my_key');

        $this->assertEquals('any_value', $decodedJwt->getClaim('some_field'));
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testFullLifeCycleHS384(): void
    {
        $jwt = TestJWT::create(TestJWT::HS384);
        $jwt->setClaim('some_field', 'any_value');
        $jwt->encode('my_key');

        $decodedJwt = TestJWT::decode($jwt->getHash());
        $decodedJwt->verify('my_key');

        $this->assertEquals('any_value', $decodedJwt->getClaim('some_field'));
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testFullLifeCycleHS512(): void
    {
        $jwt = TestJWT::create(TestJWT::HS512);
        $jwt->setClaim('some_field', 'any_value');
        $jwt->encode('my_key');

        $decodedJwt = TestJWT::decode($jwt->getHash());
        $decodedJwt->verify('my_key');

        $this->assertEquals('any_value', $decodedJwt->getClaim('some_field'));
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testFullLifeCycleRS256(): void
    {
        $privateKey = null;
        $resource = openssl_pkey_new();

        openssl_pkey_export($resource, $privateKey);

        $publicKey = openssl_pkey_get_details($resource)['key'];

        $jwt = TestJWT::create(TestJWT::RS256);
        $jwt->setClaim('some_field', 'any_value');
        $jwt->encode($privateKey);

        $decodedJwt = TestJWT::decode($jwt->getHash());
        $decodedJwt->verify($publicKey);

        $this->assertEquals('any_value', $decodedJwt->getClaim('some_field'));
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testFullLifeCycleRS384(): void
    {
        $privateKey = null;
        $resource = openssl_pkey_new();

        openssl_pkey_export($resource, $privateKey);

        $publicKey = openssl_pkey_get_details($resource)['key'];

        $jwt = TestJWT::create(TestJWT::RS384);
        $jwt->setClaim('some_field', 'any_value');
        $jwt->encode($privateKey);

        $decodedJwt = TestJWT::decode($jwt->getHash());
        $decodedJwt->verify($publicKey);

        $this->assertEquals('any_value', $decodedJwt->getClaim('some_field'));
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testFullLifeCycleRS512(): void
    {
        $privateKey = null;
        $resource = openssl_pkey_new();

        openssl_pkey_export($resource, $privateKey);

        $publicKey = openssl_pkey_get_details($resource)['key'];

        $jwt = TestJWT::create(TestJWT::RS512);
        $jwt->setClaim('some_field', 'any_value');
        $jwt->encode($privateKey);

        $decodedJwt = TestJWT::decode($jwt->getHash());
        $decodedJwt->verify($publicKey);

        $this->assertEquals('any_value', $decodedJwt->getClaim('some_field'));
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testDecodeAndVerifyWithValidSignature(): void
    {
        $jwt = TestJWT::decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lX2ZpZWxkIjoiYW55X3ZhbHVlIn0.yQz7d3ZjXJ508tZedOxG3aZPEUVltphXrGFz6lE6Jhk');
        $jwt->verify('my_key');

        $this->assertEquals('any_value', $jwt->getClaim('some_field'));
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testDecodeAndVerifyWithInvalidSignature(): void
    {
        $this->expectException(InvalidSignatureException::class);

        $jwt = TestJWT::decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lX2ZpZWxkIjoiYW55X3ZhbHVlIn0.JUKQhsQPFfq8fQMkOmJ2x_w3NrEhVZNcYg52vn-GREE');
        $jwt->verify('my_key');
    }

    /**
     * @return void
     * @throws JwtException
     */
    public function testDecodeTokenWithInvalidJson(): void
    {
        $this->expectException(JwtException::class);
        $this->expectExceptionMessage('Unable to decode the given JSON string');

        TestJWT::decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.U29tZXRoaW5nIG90aGVyIHRoYW4gSlNPTg.yQz7d3ZjXJ508tZedOxG3aZPEUVltphXrGFz6lE6Jhk');
    }
}


text:
<?php

namespace Silvestra\Bundle\AcmeBundle\Controller;

use Silvestra\Bundle\FrontendBundle\Controller\FrontendController;

/**
 * @author Tadas Gliaubicas <tadcka89@gmail.com>
 *
 * @since 9/7/14 1:05 PM
 */
class HomeController extends FrontendController
{
    public function indexAction()
    {
        return $this->renderResponse('SilvestraAcmeBundle:Home:index.html.twig');
    }

    /**
     * {@inheritdoc}
     */
    protected function getName()
    {
        return 'silvestra_acme_home';
    }
}


text:
/*
#pragma once

#include "Gwen/Controls/WindowControl.h"

namespace Gwen
{
    namespace Controls
    {
        class Button;
        class TextBox;
    }
}

class NetworkWindow : public Gwen::Controls::WindowControl
{
public:
    NetworkWindow(Gwen::Controls::Base* parent);
    ~NetworkWindow();

private:
    void OnAddressChanged(Gwen::Controls::Base* item);
    void OnConnect(Gwen::Controls::Base* item);

    Gwen::Controls::TextBox* _AddressBox;
    Gwen::Controls::TextBox* _PortBox;
    Gwen::Controls::Button* _ReconnectButton;
};
*/


text:
**This is not an official Google product.**

This application is a simple static file server built on top of `fastify` and
`fastify-auto-push`.

## Notes

The certificate files used in this sample app (`certs/key.pem` and
`certs/cert.pem`) are self-signed certificates only for `localhost`
development, generated by
[`tls-keygen`](https://www.npmjs.com/package/tls-keygen). Chrome ignores
pushed resources when using untrusted certificates. You should register the
certificate with your OS to make Chrome trust the certificate. Or just
generate a new certificate with `tls-keygen` and replace the files with the
newly generated ones.

## Command-line flags

* `--port <number>` or `-p <number>`

  Specifies the port number to be used. Defaults to 3000.

* `--http2` or `--h2`

  Use HTTP/2 when specified, HTTP/1 otherwise.

* `--auto-push` or `--ap`

  Enable auto-push. Works only with `--http2`.


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

import java.util.ArrayList;

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

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

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

/**
 * ContextEntry StAX Unmarshaller
 */

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

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

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

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

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

                if (context.testExpression("ContextKeyName", targetDepth)) {
                    contextEntry.setContextKeyName(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("ContextKeyValues", targetDepth)) {
                    contextEntry.withContextKeyValues(new ArrayList<String>());
                    continue;
                }

                if (context.testExpression("ContextKeyValues/member", targetDepth)) {
                    contextEntry.withContextKeyValues(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("ContextKeyType", targetDepth)) {
                    contextEntry.setContextKeyType(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return contextEntry;
                }
            }
        }
    }

    private static ContextEntryStaxUnmarshaller instance;

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


text:
<#
Copyright 2018 Iain Brighton

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#>

function Remove-NSRADIUSAuthenticationPolicy {
    <#
    .SYNOPSIS
        Removes an existing RADIUS authentication policy.

    .DESCRIPTION
        Removes an existing RADIUS authentication policy.

    .EXAMPLE
        Remove-NSRADIUSAuthenticationPolicy -Name 'pol_radius_nps01'

        Removes the RADIUS authentication policy named 'pol_radius_nps01'.

    .PARAMETER Session
        The NetScaler session object.

    .PARAMETER Name
        The name of the RADIUS authentication policy to remove.

    .PARAMETER Force
        Suppress confirmation when removing a responder action.
    #>
    [cmdletbinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
    param(
        $Session = $script:session,

        [parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]$Name,

        [switch]$Force
    )

    begin {
        _AssertSessionActive
    }

    process {
        foreach ($item in $Name) {
            if ($Force -or $PSCmdlet.ShouldProcess($item, 'Delete RADIUS Authentication Policy')) {
                try {
                    _InvokeNSRestApi -Session $Session -Method DELETE -Type authenticationradiuspolicy -Resource $item -Action delete
                }
                catch {
                    throw $_
                }
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>AugmentedGesture.js</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">

    <link href="http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css" rel="stylesheet">

    <link rel="shortcut icon" href="http://twitter.github.com/bootstrap/assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://twitter.github.com/bootstrap/assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://twitter.github.com/bootstrap/assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="http://twitter.github.com/bootstrap/assets/ico/apple-touch-icon-57-precomposed.png">

          AugmentedGesture.js

Github

Examples

Twitter

AugmentedGesture.js

			This is a library which use getUserMedia and WebRTC to grab the webcam.
			It analizes the image with imageprocessing.js and extract the location
			of flashy balls.
			It can be a nice way to interact with computers.
			The Wii or PS3 did good as game controllers. kinect is
			super cool obviously. Augmented gesture is different. It detect objects which are cheap
			and readily available in our everyday life.
			You can use kids toy, postit or even dishgloves :)
			Thus people got easily access to the content, in a pure web vibe.

		Learn more »

Examples

Basic

Learn More »

Drawing

Learn More »

Augmented pong

						Mini game when augmentedgesture.js is used in a multiplayer game.
						You controls the rackets of a pong and play with your friends.

Learn More »

Punch QuakeII Characters

						Mini game when augmentedgesture.js is used to punch
						QuakeII characters. maybe a good workout for geeks :)

Learn More »

Two hands

Learn More »


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>Doslo je na vrijeme i toplo, ali pizza zna biti i bolja.</Text>
  <Rating>4.5</Rating>
  <Source>http://pauza.hr/menu/meduza-catering-remiza</Source>
</CrawlItem>


text:
from mcpi import minecraft, block
import time

mc = minecraft.Minecraft.create()
y = mc.getHeight(0,0)

mc.postToChat("Begin")
mc.setting("world_immutable", True)
mc.setBlock(-5, y-1, 5, block.GLOWING_OBSIDIAN)
mc.setBlock( -5, y, 5, block.GOLD_ORE)
mc.setBlock( -5, y, -5, block.GOLD_ORE)
mc.setBlock( 5, y, 5, block.GOLD_ORE)
mc.setBlock( 5, y, -5, block.GOLD_ORE)
mc.setBlock(5, y - 1, -5, block.GOLD_ORE)

mc.player.setTilePos(0, y, 0)
points = 0
timer = 5
while True:
    blockEvents = mc.events.pollBlockHits()
    for event in blockEvents:
        hitBlock = mc.getBlock(event.pos.x, event.pos.y, event.pos.z)
        if hitBlock == block.GOLD_ORE.id:
            points += 1
            mc.setBlock(event.pos.x, event.pos.y, event.pos.z, block.AIR.id)
            timer += 3
        if hitBlock == block.GLOWING_OBSIDIAN.id:
            points += 3
            mc.setBlock(event.pos.x, event.pos.y, event.pos.z, block.GRASS.id)
            timer += 5
        if points == 7:
            mc.postToChat("Du hast gewonnen in " + str(timer) + " Sekunden")
            break
    timer -= 1
    print timer
    time.sleep(1)
    if timer == 0:
        mc.postToChat("deine Zeit ist um, du hast verloren :(")
        break


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('translations', '0004_auto_20160630_2104'),
    ]

    operations = [
        migrations.AlterField(
            model_name='translateditem',
            name='system',
            field=models.CharField(choices=[(b'Android', b'Android'), (b'iOS', b'iOS'), (b'Twig', b'Twig'), (b'xliff', b'.xliff'), (b'json', b'.json'), (b'po', b'.po'), (b'Text', b'Text')], default=b'Text', max_length=30),
        ),
    ]


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="48dp">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/et_pwd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:text=""
            android:digits="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
            android:textColor="@color/v5_login_text"
            android:inputType="textPassword"
            android:textSize="16sp"/>
    </LinearLayout>

    <CheckBox
        android:id="@+id/cb_pwd_hide"
        android:layout_width="22dp"
        android:layout_height="22dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:background="@drawable/checkbox_eye5"
        android:button="@null"
        android:checked="false"/>

</RelativeLayout>


text:
frappe.ui.toolbar.Toolbar = Class.extend({
	init: function() {
		this.make();
		//this.make_modules();
		this.make_file();
		this.make_history();
		this.make_bookmarks();
		this.make_help();
		this.make_user_menu();
		this.make_notification();

		$('.dropdown-toggle').dropdown();

		$(document).trigger('toolbar_setup');

		// clear all custom menus on page change
		$(document).on("page-change", function() {
			$("header .navbar .custom-menu").remove();
		});

		frappe.search.setup();
	},
	make: function() {
		$('header').append('
\

\

\
					<button type="button" class="navbar-toggle" data-toggle="collapse" \
						data-target=".navbar-responsive-collapse">\
						\
						\
						\
					</button>\
					\

\

\

\

\
			        <form class="navbar-form navbar-left" role="search" onsubmit="return false;">\

\
			            <input id="navbar-search" type="text" class="form-control small"\
							placeholder="' + __("Search or type a command") + '" \
							style="padding: 2px 6px; height: 24px; margin-top: 5px; \
								margin-left: 10px; background-color: #ddd; \
								min-width: 230px; font-size: 85%;\
								border-radius: 10px;">\

\
			        </form>\
					\

\

\
							\
								\

\

\

\

\

\

\

');
	},
	make_home: function() {
		$('.navbar-brand').attr('href', "#");
	},

	make_notification: function() {
		$('.navbar .navbar-right').append('
\
			0\

\

\

');

		$(document).on("notification-update", function() {
			frappe.ui.toolbar.update_notifications();
		})
	},

	make_file: function() {
		frappe.ui.toolbar.new_dialog = new frappe.ui.toolbar.NewDialog();
		frappe.ui.toolbar.search = new frappe.ui.toolbar.Search();
		frappe.ui.toolbar.report = new frappe.ui.toolbar.Report();
		// $('.navbar .nav:first').append('
\
		//
');
		$('.navbar .nav:first').append('
\
			'+__("File")+'\

\

\
					 '+__('New')+'...
\

\
					 '+__('Report')+'...
\

\

');
	},

	make_history: function() {
		frappe.ui.toolbar.recent = new frappe.ui.toolbar.RecentDocs();
	},

	make_bookmarks: function() {
		frappe.ui.toolbar.bookmarks = new frappe.ui.toolbar.Bookmarks();
	},

	make_help: function() {
		$('.navbar .nav:first').append('
\
			'+__("Help")+'\

 \

\
					 '
					+__('About')+'
\

\
					 '+__('Documentation')+'
 \

\
					 '+__('Forums')+'
 \

\
						 '+__('Report an Issue')+'
 \

 \

\
					 '
					+__('Clear Cache')+'
\

\

');
	},
	set_user_name: function() {
		$('#toolbar-user-name').html('');
	},

	make_user_menu: function() {
		this.set_user_name();

		$(repl('
\
				%(my_settings)s
\

 \
				%(website)s
\

\

 \
				%(logout)s
', {
				"logout": __('Logout'),
				"website": __('Switch to Website'),
				"user_form": encodeURIComponent("Form/User/"+user),
				"my_settings": __("My Settings")
			})
		).appendTo("#toolbar-user");
	}
});

$.extend(frappe.ui.toolbar, {
	add_dropdown_button: function(parent, label, click, icon) {
		var menu = frappe.ui.toolbar.get_menu(parent);
		if(menu.find("li:not(.custom-menu)").length && !menu.find(".divider").length) {
			frappe.ui.toolbar.add_menu_divider(menu);
		}

		return $('
 '+label+'
')
			.insertBefore(menu.find(".divider"))
			.find("a")
			.click(function() {
				click();
			});
	},
	get_menu: function(label) {
		return $("#navbar-" + label.toLowerCase());
	},
	add_menu_divider: function(menu) {
		menu = typeof menu == "string" ?
			frappe.ui.toolbar.get_menu(menu) : menu;

		$('

').prependTo(menu);
	},
})

frappe.ui.toolbar.update_notifications = function() {
	var total = 0;
	var doctypes = keys(frappe.boot.notification_info.open_count_doctype).sort();
	var modules = keys(frappe.boot.notification_info.open_count_module).sort();

	$("#navbar-notification").empty();

	$.each(modules, function(i, module) {
		var count = frappe.boot.notification_info.open_count_module[module];
		if(count) {
			$(repl('
\
				\
					%(count)s \
				 %(module)s
', {
					module: module,
					count: count,
					icon: frappe.modules[module].icon
				}))
				.appendTo("#navbar-notification")
					.find("a")
					.attr("data-module", module)
					.css({"min-width":"200px"})
					.on("click", function() {
						frappe.set_route(frappe.modules[$(this).attr("data-module")].link);
					});
			total += count;
		}
	});

	if(total) {
		$('

').appendTo("#navbar-notification");
	}

	$.each(doctypes, function(i, doctype) {
		var count = frappe.boot.notification_info.open_count_doctype[doctype];
		if(count) {
			$(repl('
\
				\
					%(count)s \
				 %(doctype)s
', {
					doctype: doctype,
					icon: frappe.boot.doctype_icons[doctype],
					count: count
				}))
				.appendTo("#navbar-notification")
					.find("a")
					.attr("data-doctype", doctype)
					.css({"min-width":"200px"})
					.on("click", function() {
						frappe.views.show_open_count_list(this);
					});
			total += count;
		}
	});

	$(".navbar-new-comments")
		.html(total)
		.toggleClass("navbar-new-comments-true", total ? true : false);

}

frappe.ui.toolbar.clear_cache = function() {
	localStorage && localStorage.clear();
	$c('frappe.sessions.clear',{},function(r,rt){
		if(!r.exc) {
			show_alert(r.message);
			location.reload();
		}
	});
	return false;
}

frappe.ui.toolbar.download_backup = function() {
	msgprint(__("Your download is being built, this may take a few moments..."));
	return $c('frappe.utils.backups.get_backup',{},function(r,rt) {});
	return false;
}

frappe.ui.toolbar.show_about = function() {
	try {
		frappe.ui.misc.about();
	} catch(e) {
		console.log(e);
	}
	return false;
}

frappe.ui.toolbar.show_banner = function(msg) {
	$banner = $('
'+msg+'×
')
		.appendTo($('header'));
	$banner.find(".close").click(function() { $(".toolbar-banner").toggle(false); });
	return $banner;
}


text:
import run from "ember-metal/run_loop";
import { Mixin } from "ember-metal/mixin";
import Controller from "ember-runtime/controllers/controller";
import EmberObject from "ember-runtime/system/object";
import View from "ember-views/views/view";

var view;

QUnit.module("View action handling", {
  teardown() {
    run(function() {
      if (view) { view.destroy(); }
    });
  }
});

QUnit.test("Action can be handled by a function on actions object", function() {
  expect(1);
  view = View.extend({
    actions: {
      poke() {
        ok(true, 'poked');
      }
    }
  }).create();
  view.send("poke");
});

QUnit.test("A handled action can be bubbled to the target for continued processing", function() {
  expect(2);
  view = View.extend({
    actions: {
      poke() {
        ok(true, 'poked 1');
        return true;
      }
    },
    target: Controller.extend({
      actions: {
        poke() {
          ok(true, 'poked 2');
        }
      }
    }).create()
  }).create();
  view.send("poke");
});

QUnit.test("Action can be handled by a superclass' actions object", function() {
  expect(4);

  var SuperView = View.extend({
    actions: {
      foo() {
        ok(true, 'foo');
      },
      bar(msg) {
        equal(msg, "HELLO");
      }
    }
  });

  var BarViewMixin = Mixin.create({
    actions: {
      bar(msg) {
        equal(msg, "HELLO");
        this._super(msg);
      }
    }
  });

  var IndexView = SuperView.extend(BarViewMixin, {
    actions: {
      baz() {
        ok(true, 'baz');
      }
    }
  });

  view = IndexView.create();
  view.send("foo");
  view.send("bar", "HELLO");
  view.send("baz");
});

QUnit.test("Actions cannot be provided at create time", function() {
  expectAssertion(function() {
    view = View.create({
      actions: {
        foo() {
          ok(true, 'foo');
        }
      }
    });
  });
  // but should be OK on an object that doesn't mix in Ember.ActionHandler
  EmberObject.create({
    actions: ['foo']
  });
});


text:
import { each } from './utils'

/**
 * Returns a mapping of the getDataBinding keys to
 * the reactor values
 */
function getState(reactor, data) {
  let state = {}
  each(data, (value, key) => {
    state[key] = reactor.evaluate(value)
  })
  return state
}

/**
 * @param {Reactor} reactor
 */
export default function(reactor) {
  return {
    getInitialState() {
      return getState(reactor, this.getDataBindings())
    },

    componentDidMount() {
      this.__unwatchFns = []
      each(this.getDataBindings(), (getter, key) => {
        const unwatchFn = reactor.observe(getter, (val) => {
          this.setState({
            [key]: val
          })
        })

        this.__unwatchFns.push(unwatchFn)
      })
    },

    componentWillUnmount() {
      while (this.__unwatchFns.length) {
        this.__unwatchFns.shift()()
      }
    },
  }
}


text:
package htmls

import (
	"strings"

	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"
)

// MatchFunc matches HTML nodes, should return true when a desired node is found.
type MatchFunc func(*html.Node) bool

// MatchAtom returns a MatchFunc that matches a Node with the specified Atom.
func MatchAtom(a atom.Atom) MatchFunc {
	return func(n *html.Node) bool {
		return n.DataAtom == a
	}
}

// FindAll returns all nodes which match the provided MatchFunc. After discovering a matching
// node, it will _not_ discover matching subnodes of that node.
func FindAll(node *html.Node, mf MatchFunc) []*html.Node {
	return findAllInternal(node, mf, false)
}

// FindAllNested returns all nodes which match the provided MatchFunc and _will_ discover
// matching subnodes of matching nodes.
func FindAllNested(node *html.Node, mf MatchFunc) []*html.Node {
	return findAllInternal(node, mf, true)
}

// Find returns the first node which matches the MatchFunc using depth-first search.
// If no node is found, ok will be false.
//
//     root, err := html.Parse(resp.Body)
//     if err != nil {
//         // handle error
//     }
//     mf := func(n *html.Node) bool {
//         return n.DataAtom == atom.Body
//     }
//     body, ok := scrape.Find(root, mf)
func Find(node *html.Node, mf MatchFunc) (n *html.Node, ok bool) {
	if mf(node) {
		return node, true
	}

	for c := node.FirstChild; c != nil; c = c.NextSibling {
		n, ok := Find(c, mf)
		if ok {
			return n, true
		}
	}
	return nil, false
}

// FindParent searches up HTML tree from the current node until either a
// match is found or the top is hit.
func FindParent(node *html.Node, mf MatchFunc) (n *html.Node, ok bool) {
	for p := node.Parent; p != nil; p = p.Parent {
		if mf(p) {
			return p, true
		}
	}
	return nil, false
}

// Text returns text from all descendant text nodes joined.
// For control over the join function, see TextJoin.
func Text(node *html.Node) string {
	joiner := func(s []string) string {
		n := 0
		for i := range s {
			trimmed := strings.TrimSpace(s[i])
			if trimmed != "" {
				s[n] = trimmed
				n++
			}
		}
		return strings.Join(s[:n], " ")
	}
	return TextJoin(node, joiner)
}

// TextJoin returns a string from all descendant text nodes joined by a
// caller provided join function.
func TextJoin(node *html.Node, join func([]string) string) string {
	nodes := FindAll(node, func(n *html.Node) bool { return n.Type == html.TextNode })
	parts := make([]string, len(nodes))
	for i, n := range nodes {
		parts[i] = n.Data
	}
	return join(parts)
}

// Attr returns the value of an HTML attribute.
func Attr(node *html.Node, key string) string {
	for _, a := range node.Attr {
		if a.Key == key {
			return a.Val
		}
	}
	return ""
}

// ByTag returns a MatchFunc which matches all nodes of the provided tag type.
//
//     root, err := html.Parse(resp.Body)
//     if err != nil {
//         // handle error
//     }
//     title, ok := scrape.Find(root, scrape.ByTag(atom.Title))
func ByTag(a atom.Atom) MatchFunc {
	return func(node *html.Node) bool { return node.DataAtom == a }
}

// ByID returns a MatchFunc which matches all nodes with the provided id.
func ByID(id string) MatchFunc {
	return func(node *html.Node) bool { return Attr(node, "id") == id }
}

// ByClass returns a MatchFunc which matches all nodes with the provided class.
func ByClass(class string) MatchFunc {
	return func(node *html.Node) bool {
		classes := strings.Fields(Attr(node, "class"))
		for _, c := range classes {
			if c == class {
				return true
			}
		}
		return false
	}
}

// findAllInternal encapsulates the node tree traversal
func findAllInternal(node *html.Node, mf MatchFunc, searchNested bool) []*html.Node {
	matched := []*html.Node{}

	if mf(node) {
		matched = append(matched, node)

		if !searchNested {
			return matched
		}
	}

	for c := node.FirstChild; c != nil; c = c.NextSibling {
		found := findAllInternal(c, mf, searchNested)
		if len(found) > 0 {
			matched = append(matched, found...)
		}
	}
	return matched
}

// FindNextSibling returns the first node which matches the MatchFunc using next sibling search.
// If no node is found, ok will be false.
//
//     root, err := html.Parse(resp.Body)
//     if err != nil {
//         // handle error
//     }
//     mf := func(n *html.Node) bool {
//         return n.DataAtom == atom.Body
//     }
//     body, ok := scrape.FindNextSibling(root, mf)
func FindNextSibling(node *html.Node, mf MatchFunc) (n *html.Node, ok bool) {

	for s := node.NextSibling; s != nil; s = s.NextSibling {
		if mf(s) {
			return s, true
		}
	}
	return nil, false
}

// FindPrevSibling returns the first node which matches the MatchFunc using previous sibling search.
// If no node is found, ok will be false.
//
//     root, err := html.Parse(resp.Body)
//     if err != nil {
//         // handle error
//     }
//     mf := func(n *html.Node) bool {
//         return n.DataAtom == atom.Body
//     }
//     body, ok := scrape.FindPrevSibling(root, mf)
func FindPrevSibling(node *html.Node, mf MatchFunc) (n *html.Node, ok bool) {
	for s := node.PrevSibling; s != nil; s = s.PrevSibling {
		if mf(s) {
			return s, true
		}
	}
	return nil, false
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FMODUnity
{
    [Serializable]
    public class ParamRef
    {
        public string Name;
        public float Value;
    }
}