text:
""" Python script for local testing (compatible with both Python 2 and Python 3)

Disclaimer: this is a way to test your solutions, but it is NOT the real judging
system. The judging system behavior might be different.
"""

from __future__ import print_function
import subprocess
import sys

USAGE_MSG = """
Usage:
Linux and Mac users:
  From your terminal, run
    python testing_tool.py command_to_run_your_script_or_executable
  Note that command_to_run_your_script_or_executable is read as a list of
  arguments, so you should NOT wrap it with quotation marks.

Examples:
C++, after compilation:
  python testing_tool.py ./my_binary
Python:
  python testing_tool.py python my_code.py
Java, after compilation:
  python testing_tool.py java my_main_class_name

See https://code.google.com/codejam/resources/faq#languages for how we compile
and run your solution in the language of your choice.

Windows users:
  Follow the instructions for Linux and Mac users if you are familiar with
  terminal tools on Windows. Otherwise, please be advised that this script might
  not work with Python 2 (it works with Python 3). In addition, if you cannot
  pass arguments to Python, you will need to modify the "cmd = sys.argv[1:]"
  line below.
"""

# Hard-coded list for numbers to guess. You can modify this list, as well as
# A, B, N below as you wish.
CORRECT_GUESS_LIST = [3, 7, 8, 1, 5]
A = 0
B = 10
N = 10
assert (A < min(CORRECT_GUESS_LIST)) and (max(CORRECT_GUESS_LIST) <= B)
NUM_TEST_CASES = len(CORRECT_GUESS_LIST)

def PrintSubprocessResults(p):
  # Print the return code and stderr output for your code.
  print("Your code finishes with exit status {}.".format(p.returncode))
  code_stderr_output = p.stderr.read()
  if code_stderr_output:
    print("The stderr output of your code is:")
    sys.stdout.write(code_stderr_output)
  else:
    print("Your code doesn't have stderr output.")

def WaitForSubprocess(p):
  # Wait for your code to finish and print the stderr output of your code for
  # debugging purposes.
  if p.poll() is None:
    print("Waiting for your code to finish...")
    p.wait()
  PrintSubprocessResults(p)

def CheckSubprocessExit(p, case_id):
  # Exit if your code finishes in the middle of a test case.
  if p.poll() is not None:
    print("Your code exited early, in the middle of Case #{}.".format(case_id))
    PrintSubprocessResults(p)
    sys.exit(-1)

def WrongAnswerExit(p, case_id, error_msg):
  print("Case #{} failed: {}".format(case_id, error_msg))
  try:
    print("WRONG_ANSWER", file=p.stdin)
  except IOError:
    print("Failed to print WRONG_ANSWER because your code finished already.")
  WaitForSubprocess(p)
  sys.exit(-1)

"""Main function begins"""
# Retrieve the command to run your code from the arguments.
# If you cannot pass arguments to Python when running this testing tool, please
# replace sys.argv[1:] with the command list to run your code.
# e.g. C++ users: cmd = ["./my_binary"]
#      Python users: cmd = [sys.executable, "my_code.py"]
#      Java users: cmd = ["java", "my_main_class_name"]
cmd = sys.argv[1:]
assert cmd, "There should be at least one argument." + USAGE_MSG
if (cmd[0] == "-h") or (cmd[0] == "-help") or (cmd[0] == "--h") or (
    cmd[0] == "--help"):
  print(USAGE_MSG)
  sys.exit(0)

# Run your code in a separate process. You can debug your code by printing to
# stderr inside your code, or adding print statements in this testing tool.
# Note that your stderr output will be printed by this testing tool only after
# your code finishes, e.g. if your code hangs, you wouldn't get your stderr
# output.
try:
  p = subprocess.Popen(
      cmd,
      stdin=subprocess.PIPE,
      stdout=subprocess.PIPE,
      stderr=subprocess.PIPE,
      bufsize=1,
      universal_newlines=True)
except Exception as e:
  print("Failed to start running your code. Error:")
  print(e)
  sys.exit(-1)

print(NUM_TEST_CASES, file=p.stdin)
for i in range(NUM_TEST_CASES):
  print(A, B, file=p.stdin)
  print(N, file=p.stdin)
  answer = CORRECT_GUESS_LIST[i]
  test_case_passed = False
  for _ in range(N):
    # Detect whether the subprocess has finished running.
    CheckSubprocessExit(p, i + 1)

    user_input = None
    try:
      user_input = p.stdout.readline()
      q = int(user_input)
    except:
      # Note that your code might finish after the first CheckSubprocessExit
      # check above but before the readline(), so we will need to again check
      # whether your code has finished.
      CheckSubprocessExit(p, i + 1)
      if user_input == "":
        WrongAnswerExit(p, i + 1,
                        "Read an empty string for the guess. This might happen "
                        "because your code printed an extra newline character.")
      else:
        WrongAnswerExit(
            p, i + 1,
            "Failed to read the guess. Expected an integer ending with one new"
            "line character. Read \"{}\" (quotes added to isolate your output) "
            "instead.".format(user_input))
    if (q <= A) or (q > B):
      WrongAnswerExit(p, i + 1, "Your guess, {}, is out of range!".format(q))
    if q == answer:
      print("CORRECT", file=p.stdin)
      test_case_passed = True
      break
    elif q < answer:
      print("TOO_SMALL", file=p.stdin)
    else:
      print("TOO_BIG", file=p.stdin)
  if not test_case_passed:
    WrongAnswerExit(p, i + 1, "Too many queries.")

extra_output = p.stdout.readline()
WaitForSubprocess(p)
if extra_output == "":
  print("Congratulations! All test cases passed :)")
else:
  print("Wrong Answer because of extra output:")
  sys.stdout.write(extra_output)
  sys.exit(-1)


text:
var App = require('app');
var blueprintUtils = require('utils/blueprint');

App.EnhancedConfigsMixin = Em.Mixin.create(App.ConfigWithOverrideRecommendationParser, {

  /**
   * this value is used for observing
   * whether recommendations for dependent properties was received from server
   * @type {number}
   */
  recommendationTimeStamp: null,

  /**
   * this property is used to force update min/max values
   * for not default config groups
   * @type {boolean}
   */
  forceUpdateBoundaries: false,

  /**
   * object with loaded recommendations
   *
   * @type {Object}
   */
  recommendationsConfigs: null,

  /**
   * list of recommendations that should be applied without any config changes
   *
   * @type {Object[]}
   */
  initialRecommendations: [],

  /**
   * flag is true when Ambari changes some of the dependent properties
   * @type {boolean}
   */
  hasChangedDependencies: Em.computed.and('isControllerSupportsEnhancedConfigs', 'changedProperties.length'),

  /**
   * defines is block with changed dependent configs should be shown
   * rely on controller
   * @type {boolean}
   */
  isControllerSupportsEnhancedConfigs: Em.computed.existsIn('name', ['wizardStep7Controller','mainServiceInfoConfigsController']),

  /**
   * Stores name and file name of changed config
   * This used only for capacity-scheduler
   *
   * @property {object}
   */
  currentlyChangedConfig: null,

  dependenciesGroupMessage: Em.I18n.t('popup.dependent.configs.dependencies.for.groups'),
  /**
   * message fro alert box for dependent configs
   * @type {string}
   */
  dependenciesMessage: function() {
    var changedProperties = this.get('changedProperties').filterProperty('saveRecommended');
    var changedServices = changedProperties.mapProperty('serviceName').uniq();
    var cfgLenSuffix = changedProperties.length === 1 ? 'singular' : 'plural';
    var sLenSuffix = changedServices.length === 1 ? 'singular' : 'plural';
    return Em.I18n.t('popup.dependent.configs.dependencies.config.' + cfgLenSuffix).format(changedProperties.length)
      + Em.I18n.t('popup.dependent.configs.dependencies.service.' + sLenSuffix).format(changedServices.length);
  }.property('changedProperties.length'),

  /**
   * dependent properties that was changed by Ambari
   * @type {Object[]}
   */
  changedProperties: function() {
    return this.get('recommendations').filter(function(dp) {
      return (this.get('selectedConfigGroup.isDefault') && Em.get(dp, 'configGroup').contains('Default'))
        || [this.get('selectedConfigGroup.name'), this.get('selectedConfigGroup.dependentConfigGroups') && this.get('selectedConfigGroup.dependentConfigGroups')[Em.get(dp, 'serviceName')]].contains(Em.get(dp, 'configGroup'));
    }, this);
  }.property('recommendations.@each.saveRecommended', 'recommendations.@each.recommendedValue', 'selectedConfigGroup'),

  /**
   * defines if change dependent group message should be shown
   * @type {boolean}
   */
  showSelectGroupsPopup: Em.computed.and('!selectedConfigGroup.isDefault', 'selectedService.dependentServiceNames.length'),

  /**
   * set default values for dependentGroups
   * @method setDependentGroups
   */
  setDependentGroups: function () {
    if (this.get('selectedConfigGroup') && this.get('isControllerSupportsEnhancedConfigs') && !this.get('selectedConfigGroup.isDefault') && this.get('selectedService.dependentServiceNames.length')) {
      this.get('selectedService.dependentServiceNames').forEach(function (serviceName) {
        if (!this.get('selectedConfigGroup.dependentConfigGroups')[serviceName]) {
          var stepConfig = this.get('stepConfigs').findProperty('serviceName', serviceName);
          if (stepConfig) {
            stepConfig.get('configGroups').filterProperty('isDefault', false).forEach(function (configGroup) {
              this.get('selectedService.configGroups').filterProperty('isDefault', false).forEach(function (currentServiceGroup) {
                if (currentServiceGroup.get('dependentConfigGroups')[serviceName] != configGroup.get('name')) {
                  var dependentGroups = $.extend({},this.get('selectedConfigGroup.dependentConfigGroups'));
                  dependentGroups[serviceName] = configGroup.get('name');
                  this.set('selectedConfigGroup.dependentConfigGroups', dependentGroups);
                }
              }, this);
            }, this);
          }
        }
      }, this);
    }
  }.observes('selectedConfigGroup'),

  /******************************METHODS THAT WORKS WITH DEPENDENT CONFIGS *************************************/

  /**
   * get config group object for current service
   * @param serviceName
   * @returns {App.ConfigGroup|null}
   */
  getGroupForService: function(serviceName) {
    if (!this.get('stepConfigs') || this.get('stepConfigs.length') === 0) {
      return null;
    }
    if (this.get('selectedService.serviceName') === serviceName) {
      return this.get('selectedConfigGroup');
    } else {
      var stepConfig = this.get('stepConfigs').findProperty('serviceName', serviceName);
      if (stepConfig) {
        var groups = stepConfig.get('configGroups');
        if (this.get('selectedConfigGroup.isDefault')) {
          return groups.length ? groups.findProperty('isDefault', true) : null;
        } else {
          return groups.length ? groups.findProperty('name', this.get('selectedConfigGroup.dependentConfigGroups')[serviceName]) : null;
        }
      } else {
        return null;
      }
    }
  },

  clearRecommendationsInfo: function() {
    this.set('recommendationsConfigs', null);
  },

  clearRecommendations: function () {
    this.clearRecommendationsInfo();
    this.clearAllRecommendations();
  },

  /**
   * sends request to get values for dependent configs
   * @param {{type: string, name: string}[]} changedConfigs - list of changed configs to track recommendations
   * @param {Function} [onComplete]
   * @returns {$.ajax|null}
   */
  loadConfigRecommendations: function (changedConfigs, onComplete) {
    var self = this;
    var updateDependencies = Em.isArray(changedConfigs) && changedConfigs.length > 0;
    var stepConfigs = this.get('stepConfigs');
    if (updateDependencies || Em.isNone(this.get('recommendationsConfigs'))) {
      var configGroup = this.get('selectedConfigGroup');
      var recommendations = this.get('hostGroups');

      var dataToSend = {
        recommend: updateDependencies ? 'configuration-dependencies' : 'configurations',
        hosts: this.get('hostNames'),
        services: this.get('serviceNames')
      };
      if (updateDependencies) {
        dataToSend.changed_configurations = changedConfigs;
      }
      if (Em.isArray(changedConfigs) && changedConfigs.mapProperty('type').uniq()[0] === 'capacity-scheduler') {
        this.set('currentlyChangedConfig', {
          name: 'capacity-scheduler',
          fileName: 'capacity-scheduler.xml'
        });
      } else {
        this.set('currentlyChangedConfig', null);
      }

      if (configGroup && !configGroup.get('isDefault') && configGroup.get('hosts.length') > 0) {
        recommendations.config_groups = [this.buildConfigGroupJSON(this.get('selectedService.configs'), configGroup)];
      } else {
        delete recommendations.config_groups;
      }
      this.setUserContext(dataToSend);
      if (stepConfigs.someProperty('serviceName', 'MISC')) {
        recommendations.blueprint.configurations = blueprintUtils.buildConfigsJSON(stepConfigs);
        dataToSend.recommendations = recommendations;
        return this.getRecommendationsRequest(dataToSend, onComplete);
      } else {
        App.config.getClusterEnvConfigs().done(function (clusterEnvConfigs) {
          stepConfigs = stepConfigs.concat(Em.Object.create({
            serviceName: 'MISC',
            configs: clusterEnvConfigs
          }));

          recommendations.blueprint.configurations = blueprintUtils.buildConfigsJSON(stepConfigs);
          dataToSend.recommendations = recommendations;
          return self.getRecommendationsRequest(dataToSend, onComplete);
        });
      }
    } else {
      if (onComplete) {
        onComplete()
      }
    }
    return $.Deferred().resolve().promise();
  },

  getRecommendationsRequest: function (dataToSend, callback) {
    var self = this;
    this.set('recommendationsInProgress', true);
    return App.ajax.send({
      name: 'config.recommendations',
      sender: self,
      data: {
        stackVersionUrl: App.get('stackVersionURL'),
        dataToSend: dataToSend
      },
      success: 'loadRecommendationsSuccess',
      error: 'loadRecommendationsError',
      callback: function () {
        self.set('recommendationsInProgress', false);
        self.set('recommendationTimeStamp', (new Date).getTime());
        if (callback) {
          callback()
        }
      }
    });
  },

  setUserContext: function(dataToSend) {
    var controllerName = this.get('content.controllerName');
    var changes = dataToSend.changed_configurations;
    if (changes) {
      dataToSend['user_context'] = {"operation" : "EditConfig"};
    } else {
      if (!controllerName) {
        dataToSend['user_context'] = {"operation" : "RecommendAttribute"};
      } else if (controllerName == 'addServiceController') {
        dataToSend['user_context'] = {
          "operation" : "AddService",
          "operation_details" : (this.get('content.services')|| []).filterProperty('isSelected').filterProperty('isInstalled', false).mapProperty('serviceName').join(',')
        };
      } else if (controllerName == 'installerController'){
        dataToSend['user_context'] = {"operation" : "ClusterCreate"};
      }
    }
  },

  /**
   * Defines if there is any changes made by user.
   * Check all properties except recommended properties from popup
   *
   * @returns {boolean}
   */
  isConfigHasInitialState: function() {
    return this.get('selectedConfigGroup.isDefault') && !Em.isNone(this.get('recommendationsConfigs'))
      && !this.get('stepConfigs').filter(function(stepConfig) {
      return stepConfig.get('changedConfigProperties').filter(function(c) {
        var changedConfigIds = this.get('changedProperties').map(function(changed) {
          return App.config.configId(changed.propertyName, changed.propertyFileName);
        });
        return !changedConfigIds.contains(App.config.configId(c.get('name'), c.get('filename')));
      }, this).length;
    }, this).length;
  },

  /**
   * generates JSON with config group info to send it for recommendations
   * @param configs
   * @param configGroup
   * @returns {{configurations: Object[], hosts: string[]}}
   */
  buildConfigGroupJSON: function(configs, configGroup) {
    Em.assert('configGroup can\'t be null', configGroup);
    var hosts = configGroup.get('hosts');
    var configurations = {};
    var overrides = configs.forEach(function(cp) {
      var override = cp.get('overrides') && cp.get('overrides').findProperty('group.name', configGroup.get('name'));
      if (override) {
        var tag = App.config.getConfigTagFromFileName(cp.get('filename'));
        if (!configurations[tag]) {
          configurations[tag] = { properties: {} };
        }
        configurations[tag].properties[cp.get('name')] = override.get('value');
      }
    });
    return {
      configurations: [configurations],
      hosts: hosts
    }
  },

  /**
   * shows popup with results for recommended value
   * if case properties that was changes belongs to not default group
   * user should pick to what config group from dependent service dependent properties will be saved
   * @param data
   * @param opt
   * @param params
   * @method dependenciesSuccess
   */
  loadRecommendationsSuccess: function (data, opt, params) {
    this._saveRecommendedValues(data, params.dataToSend.changed_configurations);
    if (this.isConfigHasInitialState()) {
      /** clearing all recommendations info **/
      this.undoRedoRecommended(this.get('recommendations'), false);
      this.clearAllRecommendations();

      /**
       * resetting recommendations to initial state
       * this case can be present when installed services depends on new added service on ADW
       **/
      this.undoRedoRecommended(this.get('initialRecommendations'), true);
      this.get('initialRecommendations').forEach(function (r) {
        this.get('recommendations').pushObject(r);
      }, this);
    }
    this.set("recommendationsConfigs", Em.get(data, "resources.0.recommendations.blueprint.configurations"));
  },

  loadRecommendationsError: Em.K,

  changedDependentGroup: function () {
    var dependentServices = this.get('selectedService.dependentServiceNames');
    var isInstallWizard = this.get('content.controllerName') === 'installerController';
    var installedServices = App.Service.find().mapProperty('serviceName');
    var services = this.get('stepConfigs').filter(function (stepConfig) {
      if (dependentServices.contains(stepConfig.get('serviceName'))) {
        return isInstallWizard ? true : installedServices.contains(stepConfig.get('serviceName'));
      }
      return false;
    }, this);
    App.showSelectGroupsPopup(this.get('selectedService.serviceName'),
        this.get('selectedService.configGroups').findProperty('name', this.get('selectedConfigGroup.name')),
        services, this.get('recommendations'));
  },

  /**
   * saves values from response for dependent config properties to recommendations
   * @param data
   * @param [changedConfigs=null]
   * @method saveRecommendedValues
   * @private
   */
  _saveRecommendedValues: function(data, changedConfigs) {
    Em.assert('invalid data - `data.resources[0].recommendations.blueprint.configurations` not defined ', data && data.resources[0] && Em.get(data.resources[0], 'recommendations.blueprint.configurations'));
    var recommendations = data.resources[0].recommendations;
    if (recommendations['config-groups'] && this.get('selectedConfigGroup') && !this.get('selectedConfigGroup.isDefault')) {
      var configFroGroup = recommendations['config-groups'][0];
      this.get('stepConfigs').forEach(function(stepConfig) {
        var configGroup = this.getGroupForService(stepConfig.get('serviceName'));
        if (configGroup && this.isConfigGroupAffected(configFroGroup.hosts, configGroup.get('hosts'))) {
          this.updateOverridesByRecommendations(configFroGroup.configurations, stepConfig.get('configs'), changedConfigs, configGroup);
          this.updateOverridesByRecommendations(configFroGroup.dependent_configurations, stepConfig.get('configs'), changedConfigs, configGroup);
          this.toggleProperty('forceUpdateBoundaries');
        }
      }, this);
    } else {
      var configObject = recommendations.blueprint.configurations;
      this.get('stepConfigs').forEach(function(stepConfig) {
        this.updateConfigsByRecommendations(configObject, stepConfig.get('configs'), changedConfigs);
      }, this);
      this.addByRecommendations(configObject, changedConfigs);
    }
    this.cleanUpRecommendations();
  },

  /**
   * determine whether hosts of group affected by config modifications
   * @param {Array} affectedHosts
   * @param {Array} groupHosts
   * @returns {boolean}
   */
  isConfigGroupAffected: function(affectedHosts, groupHosts) {
    return _.intersection(affectedHosts, groupHosts).length > 0;
  },

  /**
   * method to show popup with dependent configs
   * @method showChangedDependentConfigs
   */
  showChangedDependentConfigs: function(event, callback, secondary) {
    var self = this;
    var recommendations = event ? this.get('changedProperties') : this.get('recommendations'),
      recommendedChanges = recommendations.filterProperty('isEditable'),
      requiredChanges = this.filterRequiredChanges(recommendations);
    if (recommendedChanges.length > 0 || requiredChanges.length > 0) {
      App.showDependentConfigsPopup(recommendedChanges, requiredChanges, function() {
        self.onSaveRecommendedPopup(recommendedChanges.concat(requiredChanges));
        if (callback) callback();
      }, secondary);
    } else {
      if (callback) callback();
    }
  },

  /**
   *
   * @param {Array} recommendations
   * @returns {Array}
   */
  filterRequiredChanges: function(recommendations) {
    return recommendations.filter(function(recommendation) {
      if (recommendation.isEditable === false) {
        if (!this.get('selectedConfigGroup.isDefault')) {
          return App.ServiceConfigGroup.defaultGroupName !== recommendation.configGroup
        } else {
          return true;
        }
      }
    }, this);
  },

  /**
   * update configs when toggle checkbox on dependent configs popup
   */
  onSaveRecommendedPopup: function(recommendations) {
    var propertiesToUpdate = recommendations.filter(function(c) {
        return Em.get(c, 'saveRecommendedDefault') != Em.get(c, 'saveRecommended');
      }),
      propertiesToUndo = propertiesToUpdate.filterProperty('saveRecommended', false),
      propertiesToRedo = propertiesToUpdate.filterProperty('saveRecommended', true);

    this.undoRedoRecommended(propertiesToUndo, false);
    this.undoRedoRecommended(propertiesToRedo, true);
    this.set('recommendationTimeStamp', (new Date).getTime());
  },

  /**
   * run through config properties list (form dependent popup)
   * and set value to default (undo) or recommended (redo)
   * this happens when toggle checkbox in popup
   * @param {Object[]} propertiesToUpdate
   * @param {boolean} redo
   */
  undoRedoRecommended: function(propertiesToUpdate, redo) {
    propertiesToUpdate.forEach(function(p) {
      var initial = redo ? Em.get(p, 'initialValue') : Em.get(p, 'recommendedValue');
      var recommended = redo ? Em.get(p, 'recommendedValue') : Em.get(p, 'initialValue');
      var stepConfig = this.get('stepConfigs').findProperty('serviceName', Em.get(p, 'serviceName'));
      var config = stepConfig.get('configs').find(function(scp) {
        return scp.get('name') == Em.get(p, 'propertyName') && scp.get('filename') == App.config.getOriginalFileName(Em.get(p, 'propertyFileName'));
      });
      var selectedGroup = App.ServiceConfigGroup.find().filterProperty('serviceName', Em.get(p, 'serviceName')).findProperty('name', Em.get(p, 'configGroup'));
      if (selectedGroup.get('isDefault')) {
        if (Em.isNone(recommended)) {
          stepConfig.get('configs').removeObject(config);
        } else if (Em.isNone(initial)) {
          var stackConfigProperty = App.configsCollection.getConfigByName(Em.get(p, 'propertyName'), Em.get(p, 'propertyFileName'));
          stepConfig.get('configs').pushObject(this._createNewProperty(Em.get(p, 'propertyName'), Em.get(p, 'propertyFileName'),Em.get(p, 'serviceName'),
              recommended, stackConfigProperty? stackConfigProperty.propertyDependsOn : []));
        } else {
          Em.set(config, 'value', recommended);
        }
      } else {
        if (Em.isNone(recommended)) {
          config.get('overrides').removeObject(config.getOverride(selectedGroup.get('name')));
        } else if (Em.isNone(initial)) {
          this._addConfigOverrideRecommendation(config, recommended, null, selectedGroup);
        } else {
          var override = config.getOverride(selectedGroup.get('name'));
          if (override) {
            override.set('value', recommended);
          }
        }
      }
    }, this);
  },

  saveInitialRecommendations: function() {
    this.get('recommendations').forEach(function (r) {
      this.get('initialRecommendations').pushObject(r);
    }, this);
  },

  /**
   * disable saving recommended value for current config
   * @param config
   * @param {boolean} saveRecommended
   * @method removeCurrentFromDependentList
   */
  removeCurrentFromDependentList: function (config, saveRecommended) {
    var recommendation = this.getRecommendation(config.get('name'), config.get('filename'), config.get('group.name'));
    if (recommendation) this.saveRecommendation(recommendation, saveRecommended);
  }
});

redpajama_set_name: RedPajamaGithub


text:
using System;
using Microsoft.Framework.Configuration;
using Microsoft.Dnx.Runtime;

namespace Smidge
{
    public static class ConfigurationExtensions
    {
        public static bool GetBool(this IConfiguration config, string key)
        {
            var val = config[key];
            bool output;
            if (bool.TryParse(val, out output))
            {
                return output;
            }
            throw new InvalidCastException("Could not parse value " + val + " to a boolean");
        }
    }

    /// <summary>
    /// Smidge configuration
    /// </summary>
    public class SmidgeConfig : ISmidgeConfig
    {
        public SmidgeConfig(IApplicationEnvironment appEnv)
        {
            var cfg = new ConfigurationBuilder(appEnv.ApplicationBasePath)
                 //.AddEnvironmentVariables()
                .AddJsonFile("Smidge.json");

            _config = cfg.Build();
        }

        private readonly IConfigurationRoot _config;

        public string ServerName
        {
            get
            {
                return GetFileSafeMachineName(_config["COMPUTERNAME"] ?? "Default");
            }
        }

        public bool IsDebug
        {
            get
            {
				return _config.GetBool("debug");
            }
        }

        public string Version
        {
            get
            {
                return _config["version"] ?? "1";
            }
        }

        public string DataFolder
        {
            get
            {
                return (_config["dataFolder"] ?? "App_Data/Smidge").Replace("/", "\\");
            }
        }

        private string GetFileSafeMachineName(string name)
        {
            return name.ReplaceNonAlphanumericChars('-');
        }
    }
}


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var replace = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof replace, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function replaces matches of a regular expression', function test( t ) {
	var expected;
	var out;

	out = replace( 'aBcDeFgHiJkLmNoPqRsTuVwXYZ', /[A-Z]+/, '' );
	expected = 'acDeFgHiJkLmNoPqRsTuVwXYZ';
	t.equal( out, expected, 'replaces letters matching the regular expression (first occurrence)' );

	out = replace( 'aBcDeFgHiJkLmNoPqRsTuVwXYZ', /[A-Z]+/g, '' );
	expected = 'acegikmoqsuw';
	t.equal( out, expected, 'replaces letters matching the regular expression (global)' );

	t.end();
});

tape( 'the function replaces matches with values returned by a replacer function', function test( t ) {
	var expected;
	var out;
	var str;

	str = 'Oranges and lemons say the bells of St. Clement\'s';
	out = replace( str, /([^\s]+)/gi, replacer );

	expected = '/Oranges/ /and/ /lemons/ /say/ /the/ /bells/ /of/ /St./ /Clement\'s/';
	t.equal( out, expected, 'replaces matches using replacer function' );

	t.end();

	function replacer( match, p1 ) {
		return '/' + p1 + '/';
	}
});


text:
package org.apache.hadoop.hbase.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.FutureUtils;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category({ ClientTests.class, SmallTests.class })
public class TestAsyncRegistryLeak {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestAsyncRegistryLeak.class);

  public static final class AsyncRegistryForTest extends DoNothingAsyncRegistry {

    private boolean closed = false;

    public AsyncRegistryForTest(Configuration conf) {
      super(conf);
      CREATED.add(this);
    }

    @Override
    public CompletableFuture<String> getClusterId() {
      return FutureUtils.failedFuture(new IOException("inject error"));
    }

    @Override
    public void close() {
      closed = true;
    }
  }

  private static final List<AsyncRegistryForTest> CREATED = new ArrayList<>();

  private static Configuration CONF = HBaseConfiguration.create();

  @BeforeClass
  public static void setUp() {
    CONF.setClass(AsyncRegistryFactory.REGISTRY_IMPL_CONF_KEY, AsyncRegistryForTest.class,
      AsyncRegistry.class);
  }

  @Test
  public void test() throws InterruptedException {
    for (int i = 0; i < 10; i++) {
      try {
        ConnectionFactory.createAsyncConnection(CONF).get();
        fail();
      } catch (ExecutionException e) {
        // expected
      }
    }
    assertEquals(10, CREATED.size());
    CREATED.forEach(r -> assertTrue(r.closed));
  }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<module>
	<name>productpaymentlogos</name>
	<displayName><![CDATA[Product payment logos block]]></displayName>
	<version><![CDATA[1.3.5]]></version>
	<description><![CDATA[Displays the logos of the available payment systems on the product page.]]></description>
	<author><![CDATA[PrestaShop]]></author>
	<tab><![CDATA[front_office_features]]></tab>
	<is_configurable>1</is_configurable>
	<need_instance>0</need_instance>
	<limited_countries></limited_countries>
</module>


text:
Install and manage Atlassian JIRA.

##Usage

Example:

```
class { 'jira': }
```

##Limitations

The module has been tested on the following operating systems. Testing and patches for other platforms are welcome.

* Debian 7.0 (Wheezy)
* Ubuntu 12.04 (Precise Pangolin)
* Ubuntu 14.04 (Trusty Tahr)

[![Build Status](https://travis-ci.org/tohuwabohu/tohuwabohu-jira.png?branch=master)](https://travis-ci.org/tohuwabohu/tohuwabohu-jira)

##Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

###Development

This project uses rspec-puppet and beaker to ensure the module works as expected and to prevent regressions.

```
gem install bundler
bundle install --path vendor

bundle exec rake spec
bundle exec rake beaker
```
(note: see [Beaker - Supported ENV variables](https://github.com/puppetlabs/beaker/wiki/How-to-Write-a-Beaker-Test-for-a-Module#beaker-rspec-details)
for a list of environment variables to control the default behaviour of Beaker)


text:
<?php

namespace RawPHP\RawApplication\Contract;

/**
 * The application interface.
 *
 * @category  PHP
 * @package   RawPHP\RawApplication\Contract
 * @author    Tom Kaczocha <tom@rawphp.org>
 * @copyright 2014 Tom Kaczocha
 * @license   http://rawphp.org/license.txt MIT
 * @link      http://rawphp.org/
 */
interface IApplication
{
    /**
     * Initialises the application.
     *
     * @param array $config configuration array
     *
     * @action ON_BEFORE_APP_INIT_ACTION
     * @action ON_AFTER_APP_INIT_ACTION
     */
    public function init( $config = NULL );

    /**
     * Initialises the application request process.
     *
     * @action ON_BEFORE_RUN_ACTION
     * @action ON_AFTER_RUN_ACTION
     */
    public function run();

    /**
     * Creates a new url.
     *
     * @param string $route    controller/method route
     * @param array  $params   list of parameters
     * @param bool   $absolute whether it should be an absolute url
     *
     * @return string the url
     */
    public function createUrl( $route, $params = array(), $absolute = FALSE );

    /**
     * Adds a flash message to appear on the next page.
     *
     * Error   => 'error' ( default )
     * Success => 'success'
     *
     * @param string $message success or error message
     * @param string $type    the type of message
     */
    public function addFlash( $message, $type = 'error' );

    /**
     * Returns a list of error flash messages.
     *
     * @filter ON_GET_ERRORS_FILTER
     *
     * @return array list of error messages
     */
    public function getErrors( );

    /**
     * Returns a list of success flash messages.
     *
     * @filter ON_GET_MESSAGES_FILTER
     *
     * @return array list of success messages
     */
    public function getMessages( );

    /**
     * This function outputs caught errors and exceptions.
     *
     * This method can be overriden in a subclass to change the
     * error output format.
     *
     * @param array $error the error array
     */
    public static function displayError( $error );

    /**
     * Removes old flash messages.
     */
    public function cleanFlash( );
}


text:
body {
  margin: 30px;
}

.customizer-feature-list {
  /* Override default list styling. */
  list-style-type: none;
  padding: 0;
}

.customizer-task-function {
  /* Use a smaller width for narrow iDevices. */
  width: 10em;
}


text:
package com.commonsware.cwac.loaderex;

import android.content.Context;
import java.io.File;
import java.io.IOException;
import net.sqlcipher.database.SQLiteDatabase;

public class SQLCipherUtils {
  public static enum State {
    DOES_NOT_EXIST, UNENCRYPTED, ENCRYPTED, UNKNOWN
  }

  public static State getDatabaseState(Context context, String dbName) {
    File dbPath=context.getDatabasePath(dbName);

    if (dbPath.exists()) {
      SQLiteDatabase db=null;

      try {
        db=
            SQLiteDatabase.openDatabase(dbPath.getAbsolutePath(), "",
                                        null,
                                        SQLiteDatabase.OPEN_READONLY);

        db.getVersion();

        return(State.UNENCRYPTED);
      }
      catch (Exception e) {
        return(State.ENCRYPTED);
      }
      finally {
        if (db != null) {
          db.close();
        }
      }
    }

    return(State.DOES_NOT_EXIST);
  }

  public static void encrypt(Context ctxt, String dbName,
                             String passphrase) throws IOException {
    File originalFile=ctxt.getDatabasePath(dbName);

    if (originalFile.exists()) {
      File newFile=
          File.createTempFile("sqlcipherutils", "tmp",
                              ctxt.getCacheDir());
      SQLiteDatabase db=
          SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
                                      "", null,
                                      SQLiteDatabase.OPEN_READWRITE);

      db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';",
                                  newFile.getAbsolutePath(), passphrase));
      db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
      db.rawExecSQL("DETACH DATABASE encrypted;");

      int version=db.getVersion();

      db.close();

      db=
          SQLiteDatabase.openDatabase(newFile.getAbsolutePath(),
                                      passphrase, null,
                                      SQLiteDatabase.OPEN_READWRITE);
      db.setVersion(version);
      db.close();

      originalFile.delete();
      newFile.renameTo(originalFile);
    }
  }
}


text:
begin
  require_dependency 'application_controller'
rescue LoadError => e
  require_dependency 'application'
end

module ResourceController
  ACTIONS           = [:index, :show, :new_action, :create, :edit, :update, :destroy].freeze
  SINGLETON_ACTIONS = (ACTIONS - [:index]).freeze
  FAILABLE_ACTIONS  = ACTIONS - [:index, :new_action, :edit].freeze
  NAME_ACCESSORS    = [:model_name, :route_name, :object_name]

  module ActionControllerExtension
    unloadable

    def resource_controller(*args)
      include ResourceController::Controller

      if args.include?(:singleton)
        include ResourceController::Helpers::SingletonCustomizations
      end
    end
  end
end

require File.dirname(__FILE__)+'/../rails/init.rb' unless ActionController::Base.include?(Urligence)


text:
<?php

namespace ToDoListBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use ToDoListBundle\Form\Type\TaskType;

class TaskGoogleController extends Controller implements TaskInterface
{
    private function getGoogleServiceTasks()
    {
        $client = $this->container->get("happyr.google.api.client");
        $googleClient = $client->getGoogleClient();
        $this->securityContext = $this->get("security.context");
        $token = $this->securityContext->getToken();
        $googleClient->setAccessToken($token->getUser());

        return new \Google_Service_Tasks($googleClient);
    }

    public function getTasksAction($idList)
    {
        $service = $this->getGoogleServiceTasks();
        $tasks = $service->tasks->listTasks($idList);
        $taskList = $service->tasklists->get($idList);
        $content = $this->get('templating')->render('ToDoListBundle:Task:indexGoogle.html.twig', ['tasks' => $tasks, 'taskList' => $taskList]);

        return new Response($content);
    }

    public function addTaskAction(Request $request, $idList)
    {
        $service = $this->getGoogleServiceTasks();
        $task = new \Google_Service_Tasks_Task();
        $form = $this->createForm(new TaskType(false, '\Google_Service_Tasks_Task', true));
        $form->handleRequest($request);
        if ($form->isValid()) {
            $task->setTitle($form->getData()['title']);
            $task->setParent($idList);
            $service->tasks->insert($idList, $task);

            return $this->redirect($this->generateUrl("todolist_google_tasks", ["idList" => $idList]));
        }
        $content = $this->get('templating')->render('ToDoListBundle:Task:addTaskGoogleForm.html.twig', ['form' => $form->createView()]);

        return new Response($content);
    }

    public function editTaskAction(Request $request, $idList, $idTask)
    {
        $service = $this->getGoogleServiceTasks();
        $task = $service->tasks->get($idList, $idTask);
        $form = $this->createForm(new TaskType(true, '\Google_Service_Tasks_Task', true), $task);
        $form->handleRequest($request);
        if ($form->isValid()) {
            $service->tasks->update($idList, $idTask ,$task);

            return $this->redirect($this->generateUrl("todolist_google_tasks", ["idList" => $idList]));
        }
        $content = $this->get('templating')->render('ToDoListBundle:Task:editTaskGoogleForm.html.twig', ['form' => $form->createView()]);

        return new Response($content);
    }

    public function validateTaskAction($idList, $idTask)
    {
        $service = $this->getGoogleServiceTasks();
        $task = $service->tasks->get($idList, $idTask);
        if ($task->getStatus() === "completed") {
            $task->setStatus("needsAction");
            $task->setCompleted(null);
        } else {
            $task->setStatus("completed");
        }
        $service->tasks->update($idList, $idTask ,$task);

        return $this->redirect($this->generateUrl("todolist_google_tasks", ["idList" => $idList]));
    }

    public function deleteTaskAction(Request $request)
    {
        $service = $this->getGoogleServiceTasks();
        $idList = $request->request->get('idList');
        $idTask = $request->request->get('idTask');
        $service->tasks->delete($idList, $idTask);

        return $this->redirect($this->generateUrl("todolist_google_tasks", ["idList" => $idList]));
    }
}


text:
'use strict';

/* eslint-env jest */

/* eslint-disable no-console */

const {generateTraceEvents, createTraceString} = require('../../lib/timing-trace-saver.js');

const mockEntries = [{
  startTime: 650,
  name: 'lh:init:config',
  duration: 210,
  entryType: 'measure',
},
{
  startTime: 870,
  name: 'lh:runner:run',
  duration: 120,
  entryType: 'measure',
},
{
  startTime: 990,
  name: 'lh:runner:auditing',
  duration: 750,
  entryType: 'measure',
},
{
  startTime: 1010,
  name: 'lh:audit:is-on-https',
  duration: 10,
  entryType: 'measure',
},
];

describe('generateTraceEvents', () => {
  it('generates a pair of trace events', () => {
    const events = generateTraceEvents([mockEntries[0]]);
    expect(events.slice(0, 2)).toMatchSnapshot();
  });
});

describe('createTraceString', () => {
  it('creates a real trace', () => {
    const jsonStr = createTraceString({
      timing: {
        entries: mockEntries,
      },
    });
    const traceJson = JSON.parse(jsonStr);
    const eventsWithoutMetadata = traceJson.traceEvents.filter(e => e.cat !== '__metadata');
    expect(eventsWithoutMetadata).toMatchSnapshot();
  });
});


text:
(function() {
    'use strict';
    angular
        .module('assessoriaTorrellesApp')
        .factory('Notification', Notification);

    Notification.$inject = ['$resource', 'DateUtils'];

    function Notification ($resource, DateUtils) {
        var resourceUrl =  'api/notifications/:id';

        return $resource(resourceUrl, {}, {
            'query': { method: 'GET', isArray: true},
            'byUser': { method: 'GET', isArray: true, url: 'api/notifications/byUser'},
            'byUserActive': { method: 'GET', isArray: true, url: 'api/notifications/byUser/active'},
            'multipleDelete': { method: 'DELETE', isArray: true,  url: 'api/notifications/multiple'},
            'multipleUpdate': { method: 'PUT', isArray: true,  url: 'api/notifications/multiple'},
            'get': {
                method: 'GET',
                transformResponse: function (data) {
                    if (data) {
                        data = angular.fromJson(data);
                        data.date = DateUtils.convertDateTimeFromServer(data.date);
                    }
                    return data;
                }
            },
            'update': { method:'PUT' }
        });
    }
})();


text:
package org.apache.ignite.internal.processors.cache;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
import org.apache.ignite.cluster.ClusterState;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.processors.cache.distributed.dht.IgniteClusterReadOnlyException;
import org.apache.ignite.internal.util.GridConcurrentHashSet;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.spi.IgniteSpiException;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.MvccFeatureChecker;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;

import static org.apache.ignite.cluster.ClusterState.ACTIVE;
import static org.apache.ignite.cluster.ClusterState.ACTIVE_READ_ONLY;
import static org.apache.ignite.cluster.ClusterState.INACTIVE;
import static org.apache.ignite.testframework.GridTestUtils.assertActive;
import static org.apache.ignite.testframework.GridTestUtils.assertThrowsAnyCause;
import static org.apache.ignite.testframework.GridTestUtils.assertThrowsWithCause;

/**
 *
 */
public class IgniteClusterActivateDeactivateTestWithPersistence extends IgniteClusterActivateDeactivateTest {
    /** {@inheritDoc} */
    @Override protected boolean persistenceEnabled() {
        return true;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        cleanPersistenceDir();

        super.beforeTest();
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        super.afterTest();

        cleanPersistenceDir();
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        return super.getConfiguration(igniteInstanceName).setAutoActivationEnabled(false);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateCachesRestore_SingleNode() throws Exception {
        activateCachesRestore(1, false, ACTIVE);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateReadOnlyCachesRestore_SingleNode() throws Exception {
        activateCachesRestore(1, false, ACTIVE_READ_ONLY);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateCachesRestore_SingleNode_WithNewCaches() throws Exception {
        activateCachesRestore(1, true, ACTIVE);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateReadOnlyCachesRestore_SingleNode_WithNewCaches() throws Exception {
        activateCachesRestore(1, true, ACTIVE_READ_ONLY);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateCachesRestore_5_Servers() throws Exception {
        activateCachesRestore(5, false, ACTIVE);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateReadOnlyCachesRestore_5_Servers() throws Exception {
        activateCachesRestore(5, false, ACTIVE_READ_ONLY);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateCachesRestore_5_Servers_WithNewCaches() throws Exception {
        activateCachesRestore(5, true, ACTIVE);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateReadOnlyCachesRestore_5_Servers_WithNewCaches() throws Exception {
        activateCachesRestore(5, true, ACTIVE_READ_ONLY);
    }

    /**
     * Test deactivation on cluster that is not yet activated.
     *
     * @throws Exception If failed.
     */
    @Test
    public void testDeactivateInactiveCluster() throws Exception {
        checkDeactivateInactiveCluster(ACTIVE);
    }

    /**
     * Test deactivation on cluster that is not yet activated.
     *
     * @throws Exception If failed.
     */
    @Test
    public void testDeactivateInactiveClusterReadOnly() throws Exception {
        checkDeactivateInactiveCluster(ACTIVE_READ_ONLY);
    }

    /** */
    private void checkDeactivateInactiveCluster(ClusterState activationMode) throws Exception {
        assertActive(activationMode);

        ccfgs = new CacheConfiguration[] {
            new CacheConfiguration<>("test_cache_1")
                .setGroupName("test_cache")
                .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL),
            new CacheConfiguration<>("test_cache_2")
                .setGroupName("test_cache")
                .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)
        };

        Ignite ignite = startGrids(3);

        ignite.cluster().state(activationMode);

        if (activationMode == ACTIVE) {
            ignite.cache("test_cache_1")
                .put("key1", "val1");
            ignite.cache("test_cache_2")
                .put("key1", "val1");
        }

        ignite.cluster().state(INACTIVE);

        assertEquals(INACTIVE, ignite.cluster().state());

        stopAllGrids();

        ignite = startGrids(2);

        assertEquals(INACTIVE, ignite.cluster().state());

        ignite.cluster().state(INACTIVE);

        assertEquals(INACTIVE, ignite.cluster().state());
    }

    /** */
    private Map<Integer, Integer> startGridsAndLoadData(int srvs, ClusterState activationMode) throws Exception {
        assertActive(activationMode);

        Ignite srv = startGrids(srvs);

        srv.cluster().state(activationMode);

        srv.createCaches(Arrays.asList(cacheConfigurations1()));

        Map<Integer, Integer> cacheData = new LinkedHashMap<>();

        for (CacheConfiguration ccfg : cacheConfigurations1()) {
            for (int i = 1; i <= 100; i++) {
                int key = -i;
                int val = i;

                if (activationMode == ACTIVE) {
                    srv.cache(ccfg.getName()).put(key, val);

                    cacheData.put(key, val);
                }
                else {
                    assertThrowsWithCause(() -> srv.cache(ccfg.getName()).put(key, val), IgniteClusterReadOnlyException.class);

                    cacheData.put(key, null);
                }
            }
        }

        return cacheData;
    }

    /**
     * @param srvs Number of server nodes.
     * @param withNewCaches If {@code true} then after restart has new caches in configuration.
     * @param activationMode Cluster activation mode.
     * @throws Exception If failed.
     */
    private void activateCachesRestore(int srvs, boolean withNewCaches, ClusterState activationMode) throws Exception {
        assertActive(activationMode);

        Map<Integer, Integer> cacheData = startGridsAndLoadData(srvs, activationMode);

        stopAllGrids();

        for (int i = 0; i < srvs; i++) {
            if (withNewCaches)
                ccfgs = cacheConfigurations2();

            startGrid(i);
        }

        Ignite srv = ignite(0);

        checkNoCaches(srvs);

        srv.cluster().state(activationMode);

        final int CACHES = withNewCaches ? 4 : 2;

        for (int i = 0; i < srvs; i++)
            checkCachesOnNode(i, CACHES);

        DataStorageConfiguration dsCfg = srv.configuration().getDataStorageConfiguration();

        checkCachesData(cacheData, dsCfg);

        checkCaches(srvs, CACHES);

        int nodes = srvs;

        startGrid(nodes++, false);

        for (int i = 0; i < nodes; i++)
            checkCachesOnNode(i, CACHES);

        checkCaches(nodes, CACHES);

        startGrid(nodes++, true);

        checkCachesOnNode(nodes - 1, CACHES, false);

        checkCaches(nodes, CACHES);

        for (int i = 0; i < nodes; i++)
            checkCachesOnNode(i, CACHES);

        checkCachesData(cacheData, dsCfg);
    }

    /** {@inheritDoc} */
    @Override protected void doFinalChecks(int startNodes, int nodesCnt) {
        for (int i = 0; i < startNodes; i++) {
            int j = i;

            assertThrowsAnyCause(log, () -> startGrid(j), IgniteSpiException.class, "not compatible");
        }
    }

    /**
     * @see IGNITE-7330 for more information about context of the test
     */
    @Test
    public void testClientJoinsWhenActivationIsInProgress() throws Exception {
        checkClientJoinsWhenActivationIsInProgress(ACTIVE);
    }

    /** */
    @Test
    public void testClientJoinsWhenActivationReanOnlyIsInProgress() throws Exception {
        checkClientJoinsWhenActivationIsInProgress(ACTIVE_READ_ONLY);
    }

    /** */
    private void checkClientJoinsWhenActivationIsInProgress(ClusterState state) throws Exception {
        assertActive(state);

        startGridsAndLoadData(5, state);

        stopAllGrids();

        Ignite srv = startGrids(5);

        final CountDownLatch clientStartLatch = new CountDownLatch(1);

        IgniteInternalFuture clStartFut = GridTestUtils.runAsync(
            () -> {
                try {
                    clientStartLatch.await();

                    Thread.sleep(10);

                    client = true;

                    Ignite cl = startGrid("client0");

                    IgniteCache<Object, Object> atomicCache = cl.cache(CACHE_NAME_PREFIX + '0');
                    IgniteCache<Object, Object> txCache = cl.cache(CACHE_NAME_PREFIX + '1');

                    assertEquals(state == ACTIVE ? 100 : 0, atomicCache.size());
                    assertEquals(state == ACTIVE ? 100 : 0, txCache.size());
                }
                catch (Exception e) {
                    log.error("Error occurred", e);

                    fail("Error occurred in client thread. Msg: " + e.getMessage());
                }
            },
            "client-starter-thread"
        );

        clientStartLatch.countDown();
        srv.cluster().state(state);

        clStartFut.get();
    }

    /**
     * Checks that persistent caches are present with actual data and volatile caches are missing.
     *
     * @param cacheData Cache data.
     * @param dsCfg DataStorageConfiguration.
     */
    private void checkCachesData(Map<Integer, Integer> cacheData, DataStorageConfiguration dsCfg) {
        for (CacheConfiguration ccfg : cacheConfigurations1()) {
            if (CU.isPersistentCache(ccfg, dsCfg))
                checkCacheData(cacheData, ccfg.getName());
            else {
                for (Ignite node : G.allGrids())
                    assertTrue(node.cache(ccfg.getName()) == null || node.cache(ccfg.getName()).size() == 0);
            }
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateCacheRestoreConfigurationConflict() throws Exception {
        checkActivateCacheRestoreConfigurationConflict(ACTIVE);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testActivateReadOnlyCacheRestoreConfigurationConflict() throws Exception {
        checkActivateCacheRestoreConfigurationConflict(ACTIVE_READ_ONLY);
    }

    /** */
    private void checkActivateCacheRestoreConfigurationConflict(ClusterState state) throws Exception {
        assertActive(state);

        final int SRVS = 3;

        Ignite srv = startGrids(SRVS);

        srv.cluster().state(state);

        CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME)
            .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);

        srv.createCache(ccfg);

        stopAllGrids();

        ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME + 1)
            .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);

        ccfg.setGroupName(DEFAULT_CACHE_NAME);

        ccfgs = new CacheConfiguration[] {ccfg};

        assertThrowsAnyCause(log, () -> startGrids(SRVS), IgniteCheckedException.class, "Failed to start configured cache.");
    }

    /**
     * Test that after deactivation during eviction and rebalance and activation again after
     * all data in cache is consistent.
     *
     * @throws Exception If failed.
     */
    @Test
    public void testDeactivateDuringEvictionAndRebalance() throws Exception {
        Assume.assumeFalse("https://issues.apache.org/jira/browse/IGNITE-7384", MvccFeatureChecker.forcedMvcc());

        IgniteEx srv = startGrids(3);

        srv.cluster().state(ACTIVE);

        CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME)
            .setBackups(1)
            .setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC)
            .setIndexedTypes(Integer.class, Integer.class)
            .setAffinity(new RendezvousAffinityFunction(false, 64))
            .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);

        IgniteCache cache = srv.createCache(ccfg);

        // High number of keys triggers long partition eviction.
        final int keysCount = 100_000;

        try (IgniteDataStreamer ds = srv.dataStreamer(DEFAULT_CACHE_NAME)) {
            log.info("Writing initial data...");

            ds.allowOverwrite(true);
            for (int k = 1; k <= keysCount; k++) {
                ds.addData(k, k);

                if (k % 50_000 == 0)
                    log.info("Written " + k + " entities.");
            }

            log.info("Writing initial data finished.");
        }

        AtomicInteger keyCounter = new AtomicInteger(keysCount);
        AtomicBoolean stop = new AtomicBoolean(false);

        Set<Integer> addedKeys = new GridConcurrentHashSet<>();

        IgniteInternalFuture cacheLoadFuture = GridTestUtils.runMultiThreadedAsync(
            () -> {
                while (!stop.get()) {
                    int key = keyCounter.incrementAndGet();
                    try {
                        cache.put(key, key);

                        addedKeys.add(key);

                        Thread.sleep(10);
                    }
                    catch (Exception ignored) { }
                }
            },
            2,
            "cache-load"
        );

        stopGrid(2);

        // Wait for some data.
        Thread.sleep(3000);

        startGrid(2);

        log.info("Stop load...");

        stop.set(true);

        cacheLoadFuture.get();

        // Deactivate and activate again.
        srv.cluster().state(INACTIVE);

        srv.cluster().state(ACTIVE);

        awaitPartitionMapExchange();

        log.info("Checking data...");

        for (Ignite ignite : G.allGrids()) {
            IgniteCache cache1 = ignite.getOrCreateCache(DEFAULT_CACHE_NAME);

            for (int k = 1; k <= keysCount; k++) {
                Object val = cache1.get(k);

                Assert.assertNotNull("node=" + ignite.name() + ", key=" + k, val);

                Assert.assertTrue("node=" + ignite.name() + ", key=" + k + ", val=" + val, (int) val == k);
            }

            for (int k : addedKeys) {
                Object val = cache1.get(k);

                Assert.assertNotNull("node=" + ignite.name() + ", key=" + k, val);

                Assert.assertTrue("node=" + ignite.name() + ", key=" + k + ", val=" + val, (int) val == k);
            }
        }
    }
}


text:
using Fotografix.Shaders;
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using Newtonsoft.Json;
using System;
using System.ComponentModel;

namespace Fotografix
{
    public sealed class SharpnessAdjustment : NotifyPropertyChangedBase, ISharpnessAdjustment, IDisposable
    {
        private readonly GaussianBlurEffect blurEffect;
        private readonly PixelShaderEffect unsharpMaskEffect;

        private float amount;
        private float radius;
        private float threshold;

        private float renderScale;
        private ICanvasImage source;

        public SharpnessAdjustment()
        {
            this.blurEffect = new GaussianBlurEffect { BorderMode = EffectBorderMode.Hard, Optimization = EffectOptimization.Quality };
            this.unsharpMaskEffect = ShaderFactory.CreatePixelShaderEffect("UnsharpMask");
            unsharpMaskEffect.Source2 = blurEffect;

            this.RenderScale = 1;
            this.Radius = 1;
        }

        public void Dispose()
        {
            unsharpMaskEffect.Dispose();
            blurEffect.Dispose();
        }

        public float Amount
        {
            get => amount;

            set
            {
                if (SetProperty(ref amount, value))
                {
                    unsharpMaskEffect.Properties["amount"] = value;
                }
            }
        }

        [DefaultValue(1f)]
        public float Radius
        {
            get => radius;

            set
            {
                if (SetProperty(ref radius, value))
                {
                    UpdateRadius();
                }
            }
        }

        public float Threshold
        {
            get => threshold;

            set
            {
                if (SetProperty(ref threshold, value))
                {
                    unsharpMaskEffect.Properties["threshold"] = value;
                }
            }
        }

        [JsonIgnore]
        public ICanvasImage Source
        {
            get => source;

            set
            {
                this.source = value;
                blurEffect.Source = value;
                unsharpMaskEffect.Source1 = value;
            }
        }

        [JsonIgnore]
        public ICanvasImage Output => amount == 0 ? source : unsharpMaskEffect;

        [JsonIgnore]
        public float RenderScale
        {
            get => renderScale;

            set
            {
                if (SetProperty(ref renderScale, value))
                {
                    UpdateRadius();
                }
            }
        }

        private void UpdateRadius()
        {
            // BlurAmount is the standard deviation of the Gaussian blur
            blurEffect.BlurAmount = renderScale * radius / 2;
        }
    }
}


text:
define(['runtime'], function(jade){
  return function anonymous(locals, attrs, escape, rethrow, merge) {
attrs = attrs || jade.attrs; escape = escape || jade.escape; rethrow = rethrow || jade.rethrow; merge = merge || jade.merge;
var buf = [];
with (locals || {}) {
var interp;
buf.push('
Hello, tester!
');
}
return buf.join("");
};
});


text:
package com.red_folder.phonegap.plugin.backgroundservice;

import java.util.Enumeration;
import java.util.Hashtable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.content.ServiceConnection;

public class BackgroundServicePluginLogic {

	/*
	 ************************************************************************************************
	 * Static values
	 ************************************************************************************************
	 */
	public static final String TAG = BackgroundServicePluginLogic.class.getSimpleName();

	/*
	 ************************************************************************************************
	 * Keys
	 ************************************************************************************************
	 */
	public static final String ACTION_START_SERVICE = "startService";
	public static final String ACTION_STOP_SERVICE = "stopService";

	public static final String ACTION_ENABLE_TIMER = "enableTimer";
	public static final String ACTION_DISABLE_TIMER = "disableTimer";

	public static final String ACTION_SET_CONFIGURATION = "setConfiguration";

	public static final String ACTION_REGISTER_FOR_BOOTSTART = "registerForBootStart";
	public static final String ACTION_DEREGISTER_FOR_BOOTSTART = "deregisterForBootStart";

	public static final String ACTION_GET_STATUS = "getStatus";

	public static final String ACTION_RUN_ONCE = "runOnce";

	public static final String ACTION_REGISTER_FOR_UPDATES = "registerForUpdates";
	public static final String ACTION_DEREGISTER_FOR_UPDATES = "deregisterForUpdates";

	public static final int ERROR_NONE_CODE = 0;
	public static final String ERROR_NONE_MSG = "";

	public static final int ERROR_PLUGIN_ACTION_NOT_SUPPORTED_CODE = -1;
	public static final String ERROR_PLUGIN_ACTION_NOT_SUPPORTED_MSG = "Passed action not supported by Plugin";

	public static final int ERROR_INIT_NOT_YET_CALLED_CODE = -2;
	public static final String ERROR_INIT_NOT_YET_CALLED_MSG = "Please call init prior any other action";

	public static final int ERROR_SERVICE_NOT_RUNNING_CODE = -3;
	public static final String ERROR_SERVICE_NOT_RUNNING_MSG = "Sevice not currently running";

	public static final int ERROR_UNABLE_TO_BIND_TO_BACKGROUND_SERVICE_CODE = -4;
	public static final String ERROR_UNABLE_TO_BIND_TO_BACKGROUND_SERVICE_MSG ="Plugin unable to bind to background service";

	public static final int ERROR_UNABLE_TO_RETRIEVE_LAST_RESULT_CODE = -5;
	public static final String ERROR_UNABLE_TO_RETRIEVE_LAST_RESULT_MSG = "Unable to retrieve latest result (reason unknown)";

	public static final int ERROR_LISTENER_ALREADY_REGISTERED_CODE = -6;
	public static final String ERROR_LISTENER_ALREADY_REGISTERED_MSG = "Listener already registered";

	public static final int ERROR_LISTENER_NOT_REGISTERED_CODE = -7;
	public static final String ERROR_LISTENER_NOT_REGISTERED_MSG = "Listener not registered";

	public static final int ERROR_UNABLE_TO_CLOSED_LISTENER_CODE = -8;
	public static final String ERROR_UNABLE_TO_CLOSED_LISTENER_MSG = "Unable to close listener";

	public static final int ERROR_ACTION_NOT_SUPPORTED__IN_PLUGIN_VERSION_CODE = -9;
	public static final String ERROR_ACTION_NOT_SUPPORTED__IN_PLUGIN_VERSION_MSG = "Action is not supported in this version of the plugin";

	public static final int ERROR_EXCEPTION_CODE = -99;

	/*
	 ************************************************************************************************
	 * Fields
	 ************************************************************************************************
	 */
	private Context mContext;
	private Hashtable<String, ServiceDetails> mServices = new Hashtable<String, ServiceDetails>();

	/*
	 ************************************************************************************************
	 * Constructors
	 ************************************************************************************************
	 */
	// Part fix for https://github.com/Red-Folder/Cordova-Plugin-BackgroundService/issues/19
	//public BackgroundServicePluginLogic() {
	//}

	public BackgroundServicePluginLogic(Context pContext) {
		this.mContext = pContext;
	}

	/*
	 ************************************************************************************************
	 * Public Methods
	 ************************************************************************************************
	 */

	// Part fix for https://github.com/Red-Folder/Cordova-Plugin-BackgroundService/issues/19
	//public void initialize(Context pContext) {
	//	this.mContext = pContext;
	//}

	//public boolean isInitialized() {
	//	if (this.mContext == null)
	//		return false;
	//	else
	//		return true;
	//}

	public boolean isActionValid(String action) {
		boolean result = false;

		if(ACTION_START_SERVICE.equals(action)) result = true;
		if(ACTION_STOP_SERVICE.equals(action)) result = true;

		if(ACTION_ENABLE_TIMER.equals(action)) result = true;
		if(ACTION_DISABLE_TIMER.equals(action)) result = true;

		if(ACTION_SET_CONFIGURATION.equals(action)) result = true;

		if(ACTION_REGISTER_FOR_BOOTSTART.equals(action)) result = true;
		if(ACTION_DEREGISTER_FOR_BOOTSTART.equals(action)) result = true;

		if(ACTION_GET_STATUS.equals(action)) result = true;

		if(ACTION_RUN_ONCE.equals(action)) result = true;

		if(ACTION_REGISTER_FOR_UPDATES.equals(action)) result = true;
		if(ACTION_DEREGISTER_FOR_UPDATES.equals(action)) result = true;

		return result;
	}

	public ExecuteResult execute(String action, JSONArray data) {
		return execute(action, data, null, null);
	}

	public ExecuteResult execute(String action, JSONArray data, IUpdateListener listener, Object[] listenerExtras) {
		ExecuteResult result = null;

		Log.d(TAG, "Start of Execute");
		try {
			Log.d(TAG, "Withing try block");
			if ((data != null) &&
					(!data.isNull(0)) &&
					(data.get(0) instanceof String) &&
					(data.getString(0).length() > 0)) {

				String serviceName = data.getString(0);

				Log.d(TAG, "Finding servicename " + serviceName);

				ServiceDetails service = null;

				Log.d(TAG, "Services contain " + this.mServices.size() + " records");

				if (this.mServices.containsKey(serviceName)) {
					Log.d(TAG, "Found existing Service Details");
					service = this.mServices.get(serviceName);
				} else {
					Log.d(TAG, "Creating new Service Details");
					service = new ServiceDetails(this.mContext, serviceName);
					this.mServices.put(serviceName, service);
				}

				Log.d(TAG, "Action = " + action);

				if (!service.isInitialised())
					service.initialise();

				if (ACTION_GET_STATUS.equals(action)) result = service.getStatus();

				if (ACTION_START_SERVICE.equals(action)) result = service.startService();

				if (ACTION_REGISTER_FOR_BOOTSTART.equals(action)) result = service.registerForBootStart();
				if (ACTION_DEREGISTER_FOR_BOOTSTART.equals(action)) result = service.deregisterForBootStart();

				if (ACTION_REGISTER_FOR_UPDATES.equals(action)) result = service.registerForUpdates(listener, listenerExtras);
				if (ACTION_DEREGISTER_FOR_UPDATES.equals(action)) result = service.deregisterForUpdates();

				if (result == null) {
					Log.d(TAG, "Check if the service is running?");

					if (service != null && service.isServiceRunning()) {
						Log.d(TAG, "Service is running?");

						if (ACTION_STOP_SERVICE.equals(action)) result = service.stopService();

						if (ACTION_ENABLE_TIMER.equals(action)) result = service.enableTimer(data);
						if (ACTION_DISABLE_TIMER.equals(action)) result = service.disableTimer();

						if (ACTION_SET_CONFIGURATION.equals(action)) result = service.setConfiguration(data);

						if (ACTION_RUN_ONCE.equals(action)) result = service.runOnce();

					} else {
						result = new ExecuteResult(ExecuteStatus.INVALID_ACTION);
					}
				}

				if (result == null)
					result = new ExecuteResult(ExecuteStatus.INVALID_ACTION);
			} else {
				result = new ExecuteResult(ExecuteStatus.ERROR);
				Log.d(TAG, "ERROR - no servicename");
			}
		} catch (Exception ex) {
			result = new ExecuteResult(ExecuteStatus.ERROR);
			Log.d(TAG, "Exception - " + ex.getMessage());
		}

		return result;
	}

	public void onDestroy() {

		Log.d(TAG, "On Destroy Start");
		try {
			Log.d(TAG, "Checking for services");
			if (this.mServices != null &&
				this.mServices.size() > 0 ) {

				Log.d(TAG, "Found services");

				Enumeration<String> keys = this.mServices.keys();

				while( keys.hasMoreElements() ) {
					String key = keys.nextElement();
					ServiceDetails service = this.mServices.get(key);
					Log.d(TAG, "Calling service.close()");
					service.close();
				}
			}
		} catch (Throwable t) {
			// catch any issues, typical for destroy routines
			// even if we failed to destroy something, we need to continue destroying
			Log.d(TAG, "Error has occurred while trying to close services", t);
		}

		this.mServices = null;
		Log.d(TAG, "On Destroy Finish");

	}

	/*
	 ************************************************************************************************
	 * Internal Class
	 ************************************************************************************************
	 */
	protected class ServiceDetails {
		/*
		 ************************************************************************************************
		 * Static values
		 ************************************************************************************************
		 */
		public final String LOCALTAG = BackgroundServicePluginLogic.ServiceDetails.class.getSimpleName();

		/*
		 ************************************************************************************************
		 * Fields
		 ************************************************************************************************
		 */
		private String mServiceName = "";
		private Context mContext;

		private BackgroundServiceApi mApi;

		private String mUniqueID = java.util.UUID.randomUUID().toString();

		private boolean mInitialised = false;

		private Intent mService = null;

		private Object mServiceConnectedLock = new Object();
		private Boolean mServiceConnected = null;

		private IUpdateListener mListener = null;
		private Object[] mListenerExtras = null;

		/*
		 ************************************************************************************************
		 * Constructors
		 ************************************************************************************************
		 */
		public ServiceDetails(Context context, String serviceName)
		{
			this.mContext = context;
			this.mServiceName = serviceName;
		}

		/*
		 ************************************************************************************************
		 * Public Methods
		 ************************************************************************************************
		 */
		public void initialise()
		{
			this.mInitialised = true;

			// If the service is running, then automatically bind to it
			if (this.isServiceRunning()) {
				startService();
			}
		}

		public boolean isInitialised()
		{
			return mInitialised;
		}

		public ExecuteResult startService()
		{
			Log.d(LOCALTAG, "Starting startService");
			ExecuteResult result = null;

			try {
				Log.d(LOCALTAG, "Attempting to bind to Service");
				if (this.bindToService()) {
					Log.d(LOCALTAG, "Bind worked");
					result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
				} else {
					Log.d(LOCALTAG, "Bind Failed");
					result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_UNABLE_TO_BIND_TO_BACKGROUND_SERVICE_CODE, ERROR_UNABLE_TO_BIND_TO_BACKGROUND_SERVICE_MSG));
				}
			} catch (Exception ex) {
				Log.d(LOCALTAG, "startService failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			Log.d(LOCALTAG, "Finished startService");
			return result;
		}

		public ExecuteResult stopService()
		{
			ExecuteResult result = null;

			Log.d("ServiceDetails", "stopService called");

			try {

				Log.d("ServiceDetails", "Unbinding Service");
				this.mContext.unbindService(serviceConnection);

				Log.d("ServiceDetails", "Stopping service");
				if (this.mContext.stopService(this.mService))
				{
					Log.d("ServiceDetails", "Service stopped");
				} else {
					Log.d("ServiceDetails", "Service not stopped");
				}
				result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
			} catch (Exception ex) {
				Log.d(LOCALTAG, "stopService failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			return result;
		}

		public ExecuteResult enableTimer(JSONArray data)
		{
			ExecuteResult result = null;

			int milliseconds = data.optInt(1, 60000);
			try {
				mApi.enableTimer(milliseconds);
				result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
			} catch (RemoteException ex) {
				Log.d(LOCALTAG, "enableTimer failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			return result;
		}

		public ExecuteResult disableTimer()
		{
			ExecuteResult result = null;

			try {
				mApi.disableTimer();
				result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
			} catch (RemoteException ex) {
				Log.d(LOCALTAG, "disableTimer failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			return result;
		}

		public ExecuteResult registerForBootStart()
		{
			ExecuteResult result = null;

			try {
				PropertyHelper.addBootService(this.mContext, this.mServiceName);

				result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
			} catch (Exception ex) {
				Log.d(LOCALTAG, "registerForBootStart failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			return result;
		}

		public ExecuteResult deregisterForBootStart()
		{
			ExecuteResult result = null;

			try {
				PropertyHelper.removeBootService(this.mContext, this.mServiceName);

				result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
			} catch (Exception ex) {
				Log.d(LOCALTAG, "deregisterForBootStart failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			return result;
		}

		public ExecuteResult setConfiguration(JSONArray data)
		{
			ExecuteResult result = null;

			try {
				if (this.isServiceRunning()) {
					Object obj;
					try {
						obj = data.get(1);
						mApi.setConfiguration(obj.toString());
						result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
					} catch (JSONException e) {
						Log.d(LOCALTAG, "Processing config JSON from background service failed", e);
						result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, e.getMessage()));
					}
				} else {
					result = new ExecuteResult(ExecuteStatus.INVALID_ACTION, createJSONResult(false, ERROR_SERVICE_NOT_RUNNING_CODE, ERROR_SERVICE_NOT_RUNNING_MSG));
				}
			} catch (RemoteException ex) {
				Log.d(LOCALTAG, "setConfiguration failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			return result;
		}

		public ExecuteResult getStatus()
		{
			ExecuteResult result = null;

			result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));

			return result;
		}

		public ExecuteResult runOnce()
		{
			ExecuteResult result = null;

			try {
				if (this.isServiceRunning()) {
					mApi.run();
					result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
				} else {
					result = new ExecuteResult(ExecuteStatus.INVALID_ACTION, createJSONResult(false, ERROR_SERVICE_NOT_RUNNING_CODE, ERROR_SERVICE_NOT_RUNNING_MSG));
				}
			} catch (RemoteException ex) {
				Log.d(LOCALTAG, "runOnce failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			return result;
		}

		public ExecuteResult registerForUpdates(IUpdateListener listener, Object[] listenerExtras)
		{
			ExecuteResult result = null;
			try {

				// Check for if the listener is null
				// If it is then it will be because the Plguin version doesn't support the method
				if (listener == null) {
					result = new ExecuteResult(ExecuteStatus.INVALID_ACTION, createJSONResult(false, ERROR_ACTION_NOT_SUPPORTED__IN_PLUGIN_VERSION_CODE, ERROR_ACTION_NOT_SUPPORTED__IN_PLUGIN_VERSION_MSG));
				} else {

					// If a listener already exists, then we fist need to deregister the original
					// Ignore any failures (likely due to the listener not being available anymore)
					if (this.isRegisteredForUpdates())
						this.deregisterListener();

					this.mListener = listener;
					this.mListenerExtras = listenerExtras;

					result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG), false);
				}
			} catch (Exception ex) {
				Log.d(LOCALTAG, "regsiterForUpdates failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			return result;
		}

		public ExecuteResult deregisterForUpdates()
		{
			ExecuteResult result = null;
			try {
				if (this.isRegisteredForUpdates())
					if (this.deregisterListener())
						result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG));
					else
						result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_UNABLE_TO_CLOSED_LISTENER_CODE, ERROR_UNABLE_TO_CLOSED_LISTENER_MSG));
				else
					result = new ExecuteResult(ExecuteStatus.INVALID_ACTION, createJSONResult(false, ERROR_LISTENER_NOT_REGISTERED_CODE, ERROR_LISTENER_NOT_REGISTERED_MSG));

			} catch (Exception ex) {
				Log.d(LOCALTAG, "deregsiterForUpdates failed", ex);
				result = new ExecuteResult(ExecuteStatus.ERROR, createJSONResult(false, ERROR_EXCEPTION_CODE, ex.getMessage()));
			}

			return result;
		}

		/*
		 * Background Service specific methods
		 */
		public void close()
		{
			Log.d("ServiceDetails", "Close called");
			try {
				// Remove the lister to this publisher
				this.deregisterListener();

				Log.d("ServiceDetails", "Removing ServiceListener");
				mApi.removeListener(serviceListener);
				Log.d("ServiceDetails", "Removing ServiceConnection");
				this.mContext.unbindService(serviceConnection);
			} catch (Exception ex) {
				// catch any issues, typical for destroy routines
				// even if we failed to destroy something, we need to continue destroying
				Log.d(LOCALTAG, "close failed", ex);
				Log.d(LOCALTAG, "Ignoring exception - will continue");
			}
			Log.d("ServiceDetails", "Close finished");
		}

		private boolean deregisterListener() {
			boolean result = false;

			if (this.isRegisteredForUpdates()) {
				Log.d("ServiceDetails", "Listener deregistering");
				try {
					Log.d("ServiceDetails", "Listener closing");
					this.mListener.closeListener(new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG)), this.mListenerExtras);
					Log.d("ServiceDetails", "Listener closed");
				} catch (Exception ex) {
					Log.d("ServiceDetails", "Error occurred while closing the listener", ex);
				}

				this.mListener = null;
				this.mListenerExtras = null;
				Log.d("ServiceDetails", "Listener deregistered");

				result = true;
			}

			return result;
		}

		/*
		 ************************************************************************************************
		 * Private Methods
		 ************************************************************************************************
		 */
		private boolean bindToService() {
			boolean result = false;

			Log.d(LOCALTAG, "Starting bindToService");

			try {
				// Fix to https://github.com/Red-Folder/bgs-core/issues/18
				// Gets the class from string
				Class<?> serviceClass = ReflectionHelper.LoadClass(this.mServiceName);
				this.mService = new Intent(this.mContext, serviceClass);

				Log.d(LOCALTAG, "Attempting to start service");
				this.mContext.startService(this.mService);

				Log.d(LOCALTAG, "Attempting to bind to service");
				if (this.mContext.bindService(this.mService, serviceConnection, 0)) {
					Log.d(LOCALTAG, "Waiting for service connected lock");
					synchronized(mServiceConnectedLock) {
						while (mServiceConnected==null) {
							try {
								mServiceConnectedLock.wait();
							} catch (InterruptedException e) {
								Log.d(LOCALTAG, "Interrupt occurred while waiting for connection", e);
							}
						}
						result = this.mServiceConnected;
					}
				}
			} catch (Exception ex) {
				Log.d(LOCALTAG, "bindToService failed", ex);
			}

			Log.d(LOCALTAG, "Finished bindToService");

			return result;
		}

		private ServiceConnection serviceConnection = new ServiceConnection() {
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				// that's how we get the client side of the IPC connection
				mApi = BackgroundServiceApi.Stub.asInterface(service);
				try {
					mApi.addListener(serviceListener);
				} catch (RemoteException e) {
					Log.d(LOCALTAG, "addListener failed", e);
				}

				synchronized(mServiceConnectedLock) {
					mServiceConnected = true;

					mServiceConnectedLock.notify();
				}

			}

			@Override
			public void onServiceDisconnected(ComponentName name) {
				synchronized(mServiceConnectedLock) {
					mServiceConnected = false;

					mServiceConnectedLock.notify();
				}
			}
		};

		private BackgroundServiceListener.Stub serviceListener = new BackgroundServiceListener.Stub() {
			@Override
			public void handleUpdate() throws RemoteException {
				handleLatestResult();
			}

			@Override
			public String getUniqueID() throws RemoteException {
				return mUniqueID;
			}
		};

		private void handleLatestResult() {
			Log.d("ServiceDetails", "Latest results received");

			if (this.isRegisteredForUpdates()) {
				Log.d("ServiceDetails", "Calling listener");

				ExecuteResult result = new ExecuteResult(ExecuteStatus.OK, createJSONResult(true, ERROR_NONE_CODE, ERROR_NONE_MSG), false);
				try {
					this.mListener.handleUpdate(result, this.mListenerExtras);
					Log.d("ServiceDetails", "Listener finished");
				} catch (Exception ex) {
					Log.d("ServiceDetails", "Listener failed", ex);
					Log.d("ServiceDetails", "Disabling listener");
					this.mListener = null;
					this.mListenerExtras = null;
				}
			} else {
				Log.d("ServiceDetails", "No action performed");
			}
		}

		private JSONObject createJSONResult(Boolean success, int errorCode, String errorMessage) {
			JSONObject result = new JSONObject();

			// Append the basic information
			try {
				result.put("Success", success);
				result.put("ErrorCode", errorCode);
				result.put("ErrorMessage", errorMessage);
			} catch (JSONException e) {
				Log.d(LOCALTAG, "Adding basic info to JSONObject failed", e);
			}

			if (this.mServiceConnected != null && this.mServiceConnected && this.isServiceRunning()) {
				try { result.put("ServiceRunning", true); } catch (Exception ex) {Log.d(LOCALTAG, "Adding ServiceRunning to JSONObject failed", ex);};
				try { result.put("TimerEnabled", isTimerEnabled()); } catch (Exception ex) {Log.d(LOCALTAG, "Adding TimerEnabled to JSONObject failed", ex);};
				try { result.put("Configuration", getConfiguration()); } catch (Exception ex) {Log.d(LOCALTAG, "Adding Configuration to JSONObject failed", ex);};
				try { result.put("LatestResult", getLatestResult()); } catch (Exception ex) {Log.d(LOCALTAG, "Adding LatestResult to JSONObject failed", ex);};
				try { result.put("TimerMilliseconds", getTimerMilliseconds()); } catch (Exception ex) {Log.d(LOCALTAG, "Adding TimerMilliseconds to JSONObject failed", ex);};
			} else {
				try { result.put("ServiceRunning", false); } catch (Exception ex) {Log.d(LOCALTAG, "Adding ServiceRunning to JSONObject failed", ex);};
				try { result.put("TimerEnabled", null); } catch (Exception ex) {Log.d(LOCALTAG, "Adding TimerEnabled to JSONObject failed", ex);};
				try { result.put("Configuration", null); } catch (Exception ex) {Log.d(LOCALTAG, "Adding Configuration to JSONObject failed", ex);};
				try { result.put("LatestResult", null); } catch (Exception ex) {Log.d(LOCALTAG, "Adding LatestResult to JSONObject failed", ex);};
				try { result.put("TimerMilliseconds", null); } catch (Exception ex) {Log.d(LOCALTAG, "Adding TimerMilliseconds to JSONObject failed", ex);};
			}

			try { result.put("RegisteredForBootStart", isRegisteredForBootStart()); } catch (Exception ex) {Log.d(LOCALTAG, "Adding RegisteredForBootStart to JSONObject failed", ex);};
			try { result.put("RegisteredForUpdates", isRegisteredForUpdates()); } catch (Exception ex) {Log.d(LOCALTAG, "Adding RegisteredForUpdates to JSONObject failed", ex);};

			return result;
		}

		private boolean isServiceRunning()
		{
			boolean result = false;

			try {
				// Return Plugin with ServiceRunning true/ false
				ActivityManager manager = (ActivityManager)this.mContext.getSystemService(Context.ACTIVITY_SERVICE);
				for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
					if (this.mServiceName.equals(service.service.getClassName())) {
						result = true;
					}
				}
			} catch (Exception ex) {
				Log.d(LOCALTAG, "isServiceRunning failed", ex);
			}

		    return result;
		}

		private Boolean isTimerEnabled()
		{
			Boolean result = false;

			try {
				result = mApi.isTimerEnabled();
			} catch (Exception ex) {
				Log.d(LOCALTAG, "isTimerEnabled failed", ex);
			}

			return result;
		}

		private Boolean isRegisteredForBootStart()
		{
			Boolean result = false;

			try {
				result = PropertyHelper.isBootService(this.mContext, this.mServiceName);
			} catch (Exception ex) {
				Log.d(LOCALTAG, "isRegisteredForBootStart failed", ex);
			}

			return result;
		}

		private Boolean isRegisteredForUpdates()
		{
			if (this.mListener == null)
				return false;
			else
				return true;
		}

		private JSONObject getConfiguration()
		{
			JSONObject result = null;

			try {
				String data = mApi.getConfiguration();
				result = new JSONObject(data);
			} catch (Exception ex) {
				Log.d(LOCALTAG, "getConfiguration failed", ex);
			}

			return result;
		}

		private JSONObject getLatestResult()
		{
			JSONObject result = null;

			try {
				String data = mApi.getLatestResult();
				result = new JSONObject(data);
			} catch (Exception ex) {
				Log.d(LOCALTAG, "getLatestResult failed", ex);
			}

			return result;
		}

		private int getTimerMilliseconds()
		{
			int result = -1;

			try {
				result = mApi.getTimerMilliseconds();
			} catch (Exception ex) {
				Log.d(LOCALTAG, "getTimerMilliseconds failed", ex);
			}

			return result;
		}

	}

	protected class ExecuteResult {

		/*
		 ************************************************************************************************
		 * Fields
		 ************************************************************************************************
		 */
		private ExecuteStatus mStatus;
		private JSONObject mData;
		private boolean mFinished = true;

		public ExecuteStatus getStatus() {
			return this.mStatus;
		}

		public void setStatus(ExecuteStatus pStatus) {
			this.mStatus = pStatus;
		}

		public JSONObject getData() {
			return this.mData;
		}

		public void setData(JSONObject pData) {
			this.mData = pData;
		}

		public boolean isFinished() {
			return this.mFinished;
		}

		public void setFinished(boolean pFinished) {
			this.mFinished = pFinished;
		}

		/*
		 ************************************************************************************************
		 * Constructors
		 ************************************************************************************************
		 */
		public ExecuteResult(ExecuteStatus pStatus) {
			this.mStatus = pStatus;
		}

		public ExecuteResult(ExecuteStatus pStatus, JSONObject pData) {
			this.mStatus = pStatus;
			this.mData = pData;
		}

		public ExecuteResult(ExecuteStatus pStatus, JSONObject pData, boolean pFinished) {
			this.mStatus = pStatus;
			this.mData = pData;
			this.mFinished = pFinished;
		}

	}

	public interface IUpdateListener {
		public void handleUpdate(ExecuteResult logicResult, Object[] listenerExtras);
		public void closeListener(ExecuteResult logicResult, Object[] listenerExtras);
	}

	/*
	 ************************************************************************************************
	 * Enums
	 ************************************************************************************************
	 */
	protected enum ExecuteStatus {
		OK,
		ERROR,
		INVALID_ACTION
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
- Copyright (c) 2012 Research In Motion Limited.
-
- 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.
-->

<widget	xmlns="http://www.w3.org/ns/widgets"
		xmlns:rim="http://www.blackberry.com/ns/widgets"
		version="1.0.0.0"
		id="com.oros.eula">

	<name>EULA Example</name>
	<author>Oros</author>
	<content src="index.html" />
</widget>


text:
DMSplitView is available through [CocoaPods](http://cocoapods.org), to install
it simply add the following line to your Podfile:

    pod "DMSplitView"

## License

DMSplitView is available under the MIT license. See the LICENSE file for more info.

Documentation is available [here](http://devmode.com/projects/dm-split-view).


text:
<!DOCTYPE HTML>
<!--

-->
<html>
<!--
Copyright 2011 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
 <head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta charset="UTF-8" />
  <title>
   Closure Unit Tests - goog.positioning.AnchoredPosition
  </title>
  <script src="../base.js">
  </script>
  <script>
    goog.require('goog.positioning.AnchoredPositionTest');
  </script>
 </head>
 <body>
  <!-- Use IFRAME to avoid non-deterministic window size problems in Selenium. -->
  <iframe id="frame1" style="width:200px; height:200px;" src="anchoredviewportposition_test_iframe.html">
  </iframe>
 </body>
</html>


text:
@interface CSProgressHUD_MBProgressHUD ()<MBProgressHUDDelegate>

@property (nonatomic ,strong) MBProgressHUD *hud;

@property(nonatomic, strong) UIView *backView;

@property(nonatomic, assign) float viewAlpha;

@end

@implementation CSProgressHUD_MBProgressHUD

- (float)viewAlpha {
    return 0.65;
}

- (void)show{
    [self showWithMessage:nil cancelCallBackBlock:nil];
}

- (void)showWithMessage:(NSString *)message cancelCallBackBlock:(CancelCallBackBlock)block {
    [self showWithMessage:message imagaName:@"new_loading" cancelCallBackBlock:block];
}

- (UIView *)createCustomViewWithImageName:(NSString *)imageName {
    CSProgressCustomView *customView = [[CSProgressCustomView alloc] initWithFrame:CGRectMake(0, 0, 90, 90) WithImageName:imageName];
//    customView.layer.borderWidth = 1.0;
//    customView.layer.borderColor = [UIColor blackColor].CGColor;
//    customView.layer.cornerRadius = 6.0;
//    customView.clipsToBounds = YES;
    [customView startAnimating];
    return customView;
}

- (void)showWithMessage:(NSString *)message imagaName:(NSString *)imageName cancelCallBackBlock:(CancelCallBackBlock)block{

    BOOL isNew = YES;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    if (isNew) {
        self.backView = [UIView new];
        self.backView.frame = [UIScreen mainScreen].bounds;
        self.backView.backgroundColor = [UIColor blackColor];
        self.backView.alpha = self.viewAlpha;
        [keyWindow addSubview:self.backView];
    }

    [MBProgressHUD hideAllHUDsForView:keyWindow animated:NO];

    self.hud = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
//    self.hud.alpha=0.8;
    self.hud.delegate = self;
    self.hud.labelText = message;
    self.hud.labelColor = [UIColor darkTextColor];
    self.hud.customView = [self createCustomViewWithImageName:imageName];
    self.hud.mode = MBProgressHUDModeCustomView;
    self.hud.margin = 10;
    self.hud.color = [UIColor clearColor];

//    if (isNew) {
//        return;
//    }

    if (block) {
        self.didClickCancelButtonBlock = block;
        CGPoint centerOfHUD = self.hud.center;
        __block UIButton *click=[UIButton buttonWithType:UIButtonTypeCustom];
        CALayer *layer=[click layer];
        //是否设置边框以及是否可见
        [layer setMasksToBounds:YES];
        //设置边框圆角的弧度
        [layer setCornerRadius:6.0];

        [click setBackgroundImage: [UIImage imageNamed:@"btn_login_cancel"] forState:UIControlStateNormal];
        [click setFrame:CGRectMake(0, 0,30, 30)];
        [click setCenter:CGPointMake(centerOfHUD.x+80, centerOfHUD.y-45)];
        [click setBackgroundColor:[UIColor clearColor]];
        [click addTarget:self action:@selector(didClickCancleButton:) forControlEvents:UIControlEventTouchUpInside];
        [click.titleLabel setFont:[UIFont fontWithName:@"helvetica" size:16]];

        [self.hud addSubview:click];
        self.hud.layoutSubviewsCallBack = ^(CGSize size){
            [click setCenter:CGPointMake(centerOfHUD.x + size.width/2 , centerOfHUD.y - size.height/2 )];
        };
    }

}

- (void)showWithImageName:(NSString *)imageName cancelCallBackBlock:(CancelCallBackBlock)block {
    BOOL isNew = YES;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    if (isNew) {
        self.backView = [UIView new];
        self.backView.frame = [UIScreen mainScreen].bounds;
        self.backView.backgroundColor = [UIColor blackColor];
        self.backView.alpha = self.viewAlpha;
        [keyWindow addSubview:self.backView];
    }

    [MBProgressHUD hideAllHUDsForView:keyWindow animated:NO];

    self.hud = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
    self.hud.alpha=1.0;
    self.hud.delegate = self;
    self.hud.customView = [self createCustomViewWithImageName:imageName];
    self.hud.mode = MBProgressHUDModeCustomView;
    self.hud.margin = 10;
    self.hud.color = [UIColor clearColor];
//    if (isNew) {
//        return;
//    }
    if (block) {
        self.didClickCancelButtonBlock = block;
        CGPoint centerOfHUD = self.hud.center;
        __block UIButton *click=[UIButton buttonWithType:UIButtonTypeCustom];
        CALayer *layer=[click layer];
        //是否设置边框以及是否可见
        [layer setMasksToBounds:YES];
        //设置边框圆角的弧度
        [layer setCornerRadius:6.0];

        [click setBackgroundImage: [UIImage imageNamed:@"btn_login_cancel"] forState:UIControlStateNormal];
        CGFloat common = 30.0;
        [click setFrame:CGRectMake(0, 0, common, common)];
        CGRect iframe = self.hud.bounds;
        CGPoint icenter = self.hud.customView.center;
        icenter.x += (CGRectGetWidth(iframe) - common)/2;
        icenter.y -= (CGRectGetHeight(iframe) - common)/2;
        [click setCenter:icenter];
        [click setBackgroundColor:[UIColor clearColor]];
        [click addTarget:self action:@selector(didClickCancleButton:) forControlEvents:UIControlEventTouchUpInside];
        [click.titleLabel setFont:[UIFont fontWithName:@"helvetica" size:16]];

        [self.hud addSubview:click];
        self.hud.layoutSubviewsCallBack = ^(CGSize size){
            [click setCenter:CGPointMake(centerOfHUD.x + size.width/2 , centerOfHUD.y - size.height/2 )];
        };
    }
}

- (void)didClickCancleButton:(UIButton *)sender{
    if (_didClickCancelButtonBlock) {
        _didClickCancelButtonBlock(sender);
    }
}

- (void)dismmis{
    [self.backView removeFromSuperview];
    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:NO];
}

#pragma mark- MBProgressHUD Delegate

- (void)hudWasHidden:(MBProgressHUD *)hud{

}

@end