text:
const Promise = require('bluebird')
const path = require('path')
const debug = require('debug')('mhio:test-helpers:TestEnv')
const klaw = require('klaw')
const escapeRegExp = require('lodash.escapeRegExp')
const randomHex =  require('./random_hex')
const { arrayOnNil } = require('./ensure_array')

const { TestEnvException,
      TestEnvFsException } = require('./errors')
const { TestEnvStatic } = require('./test_env_static')
const { TestEnvPath,
      TestEnvPathWriteable,
      TestEnvPathReadable,
      TestEnvPathOutput,
      TestEnvPathFixture } = require('./test_env_path')

class TestEnv {

  // Requires the path to your `test` directory that your
  // `fixture` and `output` directories live under.
  // This will normally be `__dirname` from where you required
  // this file.
  static init( base ){

    // The app base bath
    // Take a guess if the user doesn't provide one.
    // The guess removes `node_modules/@mhio/test/lib`.
    // If you are somehow referencing a sub module of a sub module
    // the guess will be wrong. Also if you `npm link`
    this.base_path = (!base)
      ? path.resolve(__dirname, '..', '..', '..', '..')
      : path.resolve(base)

    // Where the tests at
    this.test_dir_name = 'test'
    this.test_path = path.join(this.base_path, this.test_dir_name)

    // Fixtures in test
    this.fixture_dir = 'fixture'
    this.fixture_path = path.join(this.base_path, this.fixture_dir)

    // Output in test
    this.output_dir = 'output'
    this.output_path = path.join(this.base_path, this.output_dir)

    // The prefix used for a  tmp- dir in output
    this.tmp_output_dir_prefix = 'tmp-'

    // Attach modules for users
    this.path = path

    // alias
    this.setupTestDir = this.setupFromTestDirname

    return this
  }

  static join (...args) { return path.join(...args) }
  static resolve (...args) { return path.resolve(...args) }

  // Remove a single directory from the end of a path, if it's there
  // This should be removed - 0.5.0
  static trimDirNameFromPath(full_path, dir_name){
    console.warn('trimDirNameFromPath deprecated')
    let last = full_path.split(path.sep).pop()
    if ( last === dir_name ){
      full_path = path.normalize(path.join(full_path, '..'))
      debug('Removed "%s" from base path "%s"', dir_name, full_path)
    }
    return full_path
  }

  // Remove everything up to a directory from the end of a path, if it's there
  static trimUpToDirNameFromPath(full_path, dir_name_to_trim){
    let all = path.parse(full_path)
    let dirs = all.dir.split(path.sep)
    let delete_from = null
    for (let i = dirs.length - 1; i > -1; --i) {
      let current_dir = dirs[i]
      if ( current_dir === dir_name_to_trim ) delete_from = i
    }
    if ( delete_from !== null ) dirs = dirs.splice(0, delete_from)
    let new_path = path.join(all.root, ...dirs)
    debug('Removed up to "%s" from base path "%s" "%s"', dir_name_to_trim, full_path, new_path)
    return new_path
  }

  // Remove everything up to 2 directories from the end of a path, if it's there
  static trimUpToTwoDirNamesFromPath(full_path, dir_name_to_trim){
    let dirs = full_path.split(path.sep)
    let last = dirs.pop()
    let second_last = dirs.pop()
    if ( last === dir_name_to_trim ){
      full_path = path.normalize(path.join(full_path, '..'))
      debug('Removed "%s" from base path "%s"', dir_name_to_trim, full_path)
    }
    else if ( second_last === dir_name_to_trim ){
      full_path = path.normalize(path.join(full_path, '..', '..'))
      debug('Removed "%s" from base path "%s"', dir_name_to_trim, full_path)
    }
    return full_path
  }

  static setupFromTestDirname( base_path, options = {} ){
    options.strip_test_dir = true
    options.base_path = base_path
    return new this(options)
  }

  static setup( ...args ){
    return new this(...args)
  }
  // ## Instance

  constructor( options = {} ) {

    // Go up to the app base path. "node_modules/@mhio/test/lib"
    // If we are not a direct dependency of the app we are testing then :/
    if (!options.base_path) {
      this.base_path = path.resolve(__dirname, '..', '..', '..', '..')
    } else {
      let base_path = ( options.base_path.join )
        ? path.join(...options.base_path)
        : options.base_path
      this.base_path = path.resolve(base_path)
    }
    debug('TestEnv base_path "%s"', this.base_path)

    // Where the tests at
    this.test_dir_name = options.test_dir_name || 'test'

    // Optionally remove the `test` or `test/x` dir from the end
    if ( options.strip_test_dir && this.base_path.split ) {
      this.base_path = TestEnv.trimUpToTwoDirNamesFromPath(this.base_path, this.test_dir_name)
    }

    // The path object for the tests
    this.test_tep = new TestEnvPathReadable(this, this.test_path)

    // Path object for fixture directory in test
    this.fixture_dir = options.fixture_dir || 'fixture'
    this.fixture_tep = new TestEnvPathFixture(this, this.fixture_path)

    // Path object for output directory in test
    this.output_dir = options.output_dir || 'output'
    this.output_tep = new TestEnvPathOutput(this, this.output_path)

    // The prefix used for a  tmp- dir in output
    this.tmp_output_dir_prefix =
      options.tmp_prefix ||
      options.tmp_output_dir_prefix ||
      'tmp-'

    // Attach modules for users
    this.path = path

    debug('TestEnv new', this.base_path)
  }

  // Return the fixture dir
  get test_path(){
    return path.join(this.base_path, this.test_dir_name)
  }

  // // Return the fixture dir
  get fixture_path(){
    return path.join(this.base_path, this.test_dir_name, this.fixture_dir)
  }

  // // Return the output dir
  get output_path(){
    return path.join(this.base_path, this.test_dir_name, this.output_dir)
  }

  join (...args) { return path.join(...args) }
  resolve (...args) { return path.resolve(...args) }

  // Return dir joined to a path string
  // Deletes the path from the start of the join directory
  // argument in case it's already there
  // `/home/jim/test + /home/jim/test/2/3 = /home/jim/test/2/3`
  genericPath(path_str, arg, ...args) {
    if ( !arg ) {
      arg = ''
    } else {
      if ( arg.startsWith && arg.startsWith(path_str) ) return arg
    }
    return path.join(path_str, arg, ...args)
  }

  // #### `basePath(...args)`
  // Return a directory with `.join`  from base dir
  basePath(...args) {
    return this.genericPath(this.base_path, ...args)
  }

  // #### `testPath(...args)`
  // Return a directory with `.join` from test dir
  testPath(...args) {
    return this.genericPath(this.test_path, ...args)
  }

  // #### `fixturePath( ...args )`
  // Return a fixture directory + subdirs with `.join`
  fixturePath(...args){
    return this.genericPath(this.fixture_path, ...args)
  }

  // #### `outputPath( ...args )`
  // Return the output directory + subdirs with `.join`
  outputPath(...args){
    return this.genericPath(this.output_path, ...args)
  }

  // #### `outputTmpPath(suffix, ...extras)`
  // create a `tmp-<something>` dir in output
  //tmpOutputPath
  outputTmpPath(suffix, ...extras){
    if (suffix === undefined) suffix = randomHex(5)
    let path_str = this.tmp_output_dir_prefix + suffix
    return this.outputPath( path_str, ...extras )
  }

  // #### `checkFixturePath('dir','subdir')`
  //
  // Promise to check if a fixture exists.
  // Resolves `true` or `false`
  checkFixturePathAsync(...args){
    let fixture_path = this.fixturePath(...args)
    return TestEnvStatic.statAsync(fixture_path)
      .then(()=> true)
      .catch(error => {
        if ( error.code === 'ENOENT' ) return false
        throw error
      })
  }
  checkFixturePath(...args){
    return TestEnvStatic.existsSync(this.fixturePath(...args))
  }

  // #### `cleanAsync( dir, options = {} )`
  // Promise to clean the contents of a directory
  // ```
  // cleanAsync(dir)
  // cleanAsync(outside_dir, force: true)
  // ```
  cleanAsync(dir, options = {}){
    return new Promise((resolve, reject)=>{
      if (!dir)
        return reject(new TestEnvException('No dir to clean'))

      if (typeof dir !== 'string')
        return reject(new TestEnvException(`directory must be a string. ${typeof dir}`))

      // Be careful when deleting paths
      let base_path = this.basePath()
      if ( !dir.startsWith(base_path) && !options.force ) {
        return reject(new TestEnvException(`Can't clean outside of project without force option: ${dir}`))
      }

      // Be more careful when deleting paths
      if ( (dir === base_path || dir === `${base_path}/`) && !options.force ) {
        return reject(new TestEnvException(`Can't clean entire project without force option: ${dir}`))
      }

      // The environment variable `DEBUG_CLEAN` will turn off deletions
      if ( process.env.DEBUG_CLEAN ) {
        debug('clean debug - would have removed dir "%s"', dir)
        return resolve(dir)
      }

      // Now the actual remove. `rm -rf` equivelant, hence the checks
      debug('cleaning up dir "%s"', dir)
      return resolve(TestEnvStatic.emptyDirAsync(dir).then(res => {
        debug('cleaned up dir "%s"', dir)
        return res
      }))
    })
  }

  // #### `removeAsync( dir, options = {} )`
  // Promise to remove the a directory
  // ```
  // removeAsync(dir)
  // removeAsync(outside_dir, force: true)
  // ```
  removeAsync(dir, options = {}){
    return new Promise((resolve, reject)=>{
      if (!dir)
        return reject(new TestEnvException('No dir to remove'))

      if (typeof dir !== 'string')
        return reject(new TestEnvException(`directory must be a string. ${typeof dir}`))

      // Be careful when deleting paths
      let base_path = this.basePath()
      if ( !dir.startsWith(base_path) && !options.force ) {
        return reject(new TestEnvException(`Can't remove outside of project without force option: ${dir}`))
      }

      // Be more careful when deleting paths
      if ( (dir === base_path || dir === `${base_path}/`) && !options.force ) {
        return reject(new TestEnvException(`Can't remove entire project without force option: ${dir}`))
      }

      // The environment variable `DEBUG_CLEAN` will turn off deletions
      if ( process.env.DEBUG_CLEAN ) {
        debug('remove debug - would have removed dir "%s"', dir)
        return resolve(dir)
      }

      // Now the actual remove. `rm -rf` equivelant
      debug('remove removing dir "%s"', dir)
      return resolve(TestEnvStatic.removeAsync(dir).then(res => {
        debug('remove removed dir "%s"', dir)
        return res
      }))
    })
  }

  // #### `cleanAllOutputAsync()`
  // Clean everything in the `output/` dir
  cleanAllOutputAsync(){
    return new Promise((resolve) => {
      let dir = this.outputPath()
      debug('emptying output dir', dir)
      return resolve(this.cleanAsync(dir))
    })
  }

  // #### `cleanOutputAsync(subdir)`
  // Clean a named `output/subdir`
  cleanOutputAsync(subdir){
    return new Promise((resolve) => {
      if (!subdir) throw new TestEnvException('No subdir to clean')
      debug('cleaning up output dir "%s"', subdir)
      return resolve(this.cleanAsync( this.outputPath(subdir) ))
    })
  }

  // #### `cleanOutputAsync(subdir)`
  // Remove a named `output/subdir`
  removeOutputAsync(subdir){
    return new Promise((resolve) => {
      if (!subdir) throw new TestEnvException('No subdir to clean')
      debug('removing output dir "%s"', subdir)
      return resolve(this.removeAsync( this.outputPath(subdir) ))
    })
  }

  // #### `removeAllOutputTmpAsync()`
  // Removes any `tmp-*` dirs created (Named with `tmp_output_dir_prefix`)
  cleanAllOutputTmpAsync(){
    console.error('cleanAllOutputTmpAsync() has been deprecated. Use removeAllOutputTmpAsync() instead')
    this.removeAllOutputTmpAsync()
  }
  removeAllOutputTmpAsync(){
    return new Promise((resolve, reject) => {
      let output_dir = this.outputPath()
      let output_tmp = this.outputPath(this.tmp_output_dir_prefix)
      debug('cleaning all output tmp- directories dir', output_dir)

      let items = [] // files, directories, symlinks, etc

      klaw(output_dir)
        .on('readable', function () {
          let item
          while ( (item = this.read()) ) {
            debug('klaw clean found item', item.path)
            if ( item.path.startsWith(output_tmp) ) items.push(item.path)
          }
        })
        .on('error', reject)
        .on('end', function () {
          debug('klaw items', items.length) // => [ ... array of files]
          resolve(items)
        })
    }).then(items_to_delete => {
      return Promise.all(items_to_delete.map(item => this.removeAsync(item)))
    })

  }

  // #### `cleanOutputTmpAsync(suffix)`
  // Clean a named `output/tmp-suffix` dir
  cleanOutputTmpAsync(suffix){
    return new Promise((resolve) => {
      // Deal with a full tmp path
      suffix = this.removeTmpPrefixFromPath(suffix)
      let dir = this.outputTmpPath(suffix)
      debug('cleaning up tmp dir', dir)
      return resolve(this.cleanAsync( dir ))
    })
  }

  // #### `removeOutputTmpAsync(suffix)`
  // Remove a named `output/tmp-suffix` dir
  removeOutputTmpAsync(suffix){
    return new Promise((resolve) => {
      // Deal with a full tmp path
      suffix = this.removeTmpPrefixFromPath(suffix)
      let dir = this.outputTmpPath(suffix)
      debug('removing tmp dir', dir)
      return resolve(this.removeAsync( dir ))
    })
  }

  fixture(...args) { return new TestEnvPathFixture(this, this.fixturePath(...args)) }
  output(...args) { return new TestEnvPathOutput(this, this.outputPath(...args)) }
  outputTmp(...args) { return new TestEnvPathOutput(this, this.outputTmpPath(...args)) }

  // #### `mkdirOutputAsync(...args)`

  // Promise to make a directory in the `output/` dir.
  // Resolve a `TestEnvPath` for the new directory

  mkdirOutputAsync(...args){
    return new Promise((resolve) => {
      let out_dir = this.output(...args)
      let p = TestEnvStatic.mkdirsAsync( out_dir.path() )
        .then(()=> out_dir )
      resolve(p)
    })
  }

  // #### `mkdirOutput(...args)`
  //
  // Make an output directory synchronously.
  // makeOutput(...args){
  //   let out_dir = this.outputPath(...args)
  //   return TestEnvStatic.mkdirsSync(out_dir)
  // }

  // #### `mkdirOutputTmpAsync(suffix)`
  //
  // Promise to make a tmp- directory in output.
  // Resolve a `TestEnvPath` for the new directory

  mkdirOutputTmpAsync(suffix, ...paths){
    return new Promise((resolve) => {
      let out_dir = this.outputTmp(suffix, ...paths)
      let p = TestEnvStatic.mkdirsAsync( out_dir.path() )
        .then(()=> out_dir )
      resolve(p)
    })
  }

  // #### `mkdirOutputTmp(...args)`
  //
  // Make a tmp- directory synchronously in output.

  // makeOutputTmp(suffix, ...paths){
  //   let out_dir = this.outputTmpPath(suffix, ...paths)
  //   return resolve(TestEnvStatic.mkdirsSync(out_dir))
  // }

  // #### `removeTmpPrefixFromPath(tmppath)`
  removeTmpPrefixFromPath(tmppath){
    debug('removeTmpPrefixFromPath tmppath', tmppath)
    let tmp_path_prefix = this.outputPath(this.tmp_output_dir_prefix)
    let re = new RegExp( `^${escapeRegExp(tmp_path_prefix)}` )
    let str = tmppath.replace(re, '')
    debug('removeTmpPrefixFromPath new', str)
    return str
  }

  // #### `copyAsync(src, dest, options)`
  // Promise `fs-extra` copy.
  copyAsync(src, dest, options){
    return TestEnvStatic.copyAsync(src, dest, options)
  }

  // #### `copyFixtureToTmpOutputAsync(fixture_suffix)`
  // No output_suffix copies to a random output tmp dir
  // No fixture suffix copy all fixtures to a random output tmp dir
  copyFixtureToTmpOutputAsync(fixture_suffix){
    return new Promise.try(() => {
      debug('copyFixtureTmpOutputAsync', fixture_suffix)
      let src = this.fixturePath(fixture_suffix)
      let dest = this.outputTmpPath(undefined, fixture_suffix)
      return this.copyAsync(src, dest).then(()=> dest)
    })
  }

  // #### `copyFixtureToOutputAsync(fixture_suffix, output_suffix = fixture_suffix)`
  // No output_suffix copies directly to output
  // No fixture suffix copies all fixtures to output
  copyFixtureToOutputAsync(fixture_suffix, output_suffix = fixture_suffix){
    return new Promise((resolve) => {
      debug('copyFixtureOutputAsync', fixture_suffix, output_suffix)

      let src = this.fixturePath(...arrayOnNil(fixture_suffix))
      let dest = this.outputPath(...arrayOnNil(output_suffix))
      resolve( this.copyAsync(src, dest).then(()=> dest) )
    })
  }

}

// Manually attach class static data as es2015 can't
// do this inside the class.
TestEnv.init()

module.exports = { TestEnv, TestEnvPath, TestEnvException }


text:
package khs.trouble.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketHandler;

import khs.trouble.model.Event;
import khs.trouble.repository.EventRepository;
import khs.trouble.controller.EventsHandler;

@Service
public class EventService {

	@Autowired
	private EventRepository repository;

	@Autowired
	private WebSocketHandler eventsHandler;

	@Value("${trouble.timeout:300000}")
	private Long timeout;

	private void sendEvent(Event event) {
		try {
			((EventsHandler) eventsHandler).sendSingleEvent(event);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void killed(String serviceName, String url) {
		Event event = new Event();
		event.setCreated(new Date());
		event.setAction("KILLED");
		event.setDescription(serviceName.toUpperCase() + " killed at: " + url);
		this.repository.save(event);

		sendEvent(event);
	}

	public void randomKilled(String serviceName) {
		Event event = new Event();
		event.setCreated(new Date());
		event.setAction("RANDOM");
		event.setDescription(serviceName.toUpperCase() + " selected to be killed");
		this.repository.save(event);

		sendEvent(event);
	}

	public void load(String serviceName, String url, int threads) {
		Event event = new Event();
		event.setCreated(new Date());
		event.setAction("LOAD");
		event.setDescription(serviceName.toUpperCase() + " Load of (" + threads + " threads) started at: " + url + " will timeout in " + timeout());
		this.repository.save(event);

		sendEvent(event);
	}

	public void exception(String serviceName, String url) {
		Event event = new Event();
		event.setCreated(new Date());
		event.setAction("EXCEPTION");
		event.setDescription(serviceName.toUpperCase() + " Exception thrown at: " + url);
		this.repository.save(event);

		sendEvent(event);
	}

	public void memory(String serviceName, String url) {
		Event event = new Event();
		event.setCreated(new Date());
		event.setAction("MEMORY");
		event.setDescription(serviceName.toUpperCase() + " Memory Consumed at: " + url + " will timeout in " + timeout());
		this.repository.save(event);

		sendEvent(event);
	}

	public void eventInfo(String msg) {
		Event event = new Event();
		event.setCreated(new Date());
		event.setAction("INFO");
		event.setDescription(msg);
		this.repository.save(event);

		sendEvent(event);
	}

	public void attempted(String msg) {
		Event event = new Event();
		event.setCreated(new Date());
		event.setAction("ATTEMPTED");
		event.setDescription(msg);
		this.repository.save(event);

		sendEvent(event);
	}

	public void started() {
		Event event = new Event();
		event.setCreated(new Date());
		event.setAction("STARTED");
		event.setDescription("Trouble maker started");
		this.repository.save(event);

		sendEvent(event);
	}

	public void notStarted() {
		Event event = new Event();
		event.setCreated(new Date());
		event.setAction("NOT STARTED");
		event.setDescription("Service Registry Not Found, Make sure it has been started or is accessible");
		this.repository.save(event);

		sendEvent(event);
	}

	public String timeout() {
		String msg = timeout == 0 ? "NEVER" : "" + (timeout / 60000) + " minute(s)";
		return msg;
	}

	public Iterable<Event> events() {
		return this.repository.findAll(new Sort(Sort.Direction.ASC, "created"));
	}
}

redpajama_set_name: RedPajamaGithub


text:
{% extends 'idm/base.html' %}
{% load i18n %}

{% block main %}
  {% include "idm/myApplications/roles/_role_delete.html" %}
{% endblock %}


text:
namespace Microsoft.Azure.Management.StorSimple1200Series.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Upload Certificate Request to IDM
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class UploadCertificateRequest
    {
        /// <summary>
        /// Initializes a new instance of the UploadCertificateRequest class.
        /// </summary>
        public UploadCertificateRequest()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the UploadCertificateRequest class.
        /// </summary>
        /// <param name="certificate">Gets or sets the base64 encoded
        /// certificate raw data string</param>
        /// <param name="authType">Specify the Authentication type. Possible
        /// values include: 'Invalid', 'AccessControlService',
        /// 'AzureActiveDirectory'</param>
        /// <param name="contractVersion">Gets ContractVersion. Possible values
        /// include: 'InvalidVersion', 'V2011_09', 'V2012_02', 'V2012_05',
        /// 'V2012_12', 'V2013_04', 'V2013_10', 'V2013_11', 'V2014_04',
        /// 'V2014_06', 'V2014_07', 'V2014_09', 'V2014_10', 'V2014_12',
        /// 'V2015_01', 'V2015_02', 'V2015_04', 'V2015_05', 'V2015_06',
        /// 'V2015_07', 'V2015_08', 'V2015_10', 'V2015_12', 'V2016_01',
        /// 'V2016_02', 'V2016_04', 'V2016_05', 'V2016_07', 'V2016_08'</param>
        public UploadCertificateRequest(string certificate, AuthType? authType = default(AuthType?), ContractVersions? contractVersion = default(ContractVersions?))
        {
            AuthType = authType;
            Certificate = certificate;
            ContractVersion = contractVersion;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets specify the Authentication type. Possible values
        /// include: 'Invalid', 'AccessControlService', 'AzureActiveDirectory'
        /// </summary>
        [JsonProperty(PropertyName = "properties.authType")]
        public AuthType? AuthType { get; set; }

        /// <summary>
        /// Gets or sets the base64 encoded certificate raw data string
        /// </summary>
        [JsonProperty(PropertyName = "properties.certificate")]
        public string Certificate { get; set; }

        /// <summary>
        /// Gets ContractVersion. Possible values include: 'InvalidVersion',
        /// 'V2011_09', 'V2012_02', 'V2012_05', 'V2012_12', 'V2013_04',
        /// 'V2013_10', 'V2013_11', 'V2014_04', 'V2014_06', 'V2014_07',
        /// 'V2014_09', 'V2014_10', 'V2014_12', 'V2015_01', 'V2015_02',
        /// 'V2015_04', 'V2015_05', 'V2015_06', 'V2015_07', 'V2015_08',
        /// 'V2015_10', 'V2015_12', 'V2016_01', 'V2016_02', 'V2016_04',
        /// 'V2016_05', 'V2016_07', 'V2016_08'
        /// </summary>
        [JsonProperty(PropertyName = "contractVersion")]
        public ContractVersions? ContractVersion { get; private set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Certificate == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Certificate");
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="kg_password_wrong_pin_code">
        <item quantity="other">Yanlış SIM PIN kodu, %d cəhdiniz qalır.</item>
        <item quantity="one">Yanlış SIM PIN kodu, %d cəhddən sonra cihazı kiliddən çıxarmaq üçün operatorla əlaqə saxlamalısınız.</item>
    </plurals>
    <plurals name="kg_password_wrong_puk_code">
        <item quantity="other">Yanlış SIM PUK kodu,%d cəhddən sonra SIM kart həmişəlik yararsız olacaq.</item>
        <item quantity="one">Yanlış SIM PUK kodu, %d cəhddən sonra SIM kart həmişəlik yararsız olacaq.</item>
    </plurals>
    <plurals name="kg_prompt_reason_time_password">
        <item quantity="other">Cihaz %d saat kiliddən çıxarılmayıb. Parolu təsdiq edin.</item>
        <item quantity="one">Cihaz %d saat kiliddən çıxarılmayıb. Parolu təsdiq edin.</item>
    </plurals>
    <plurals name="kg_prompt_reason_time_pattern">
        <item quantity="other">Cihaz %d saat kiliddən çıxarılmayıb. Nümunə kodu təsdiq edin.</item>
        <item quantity="one">Cihaz %d saat kiliddən çıxarılmayıb. Nümunə kodu təsdiq edin.</item>
    </plurals>
    <plurals name="kg_prompt_reason_time_pin">
        <item quantity="other">Cihaz %d saat kiliddən çıxarılmayıb. PIN kodu təsdiq edin.</item>
        <item quantity="one">Cihaz %d saat kiliddən çıxarılmayıb. PIN kodu təsdiq edin.</item>
    </plurals>
    <plurals name="notification_channels_list_desc_2_and_others">
        <item quantity="other">%1$s, %2$s, və %3$d digər</item>
        <item quantity="one">%1$s, %2$s, və %3$d digər</item>
    </plurals>
    <plurals name="notification_num_channels_desc">
        <item quantity="other">Bu tətbiqin %d bildiriş kateqoriyasından 1 kanal</item>
        <item quantity="one">Bu tətbiqin %d bildiriş kateqoriyasından 1 kanal</item>
    </plurals>
    <plurals name="status_bar_accessibility_recent_apps">
        <item quantity="other">İcmalda %d ekran</item>
        <item quantity="one">İcmalda 1 ekran</item>
    </plurals>
    <plurals name="notification_group_overflow_description">
        <item quantity="other">Daxilində daha %s bildiriş.</item>
        <item quantity="one">Daxilində daha %s bildiriş.</item>
    </plurals>
</resources>


text:
rails_spa.directive('fileupload', ['$http', function ($http) {
  return {
    scope: {
      fileupload: "=",
      ngModel: "=ngModel"
    },
    restrict: 'A',
    link: function($scope, element, attrs) {
      element.bind('change', function(){
        var fd = new FormData();
        _.each(element[0].files, function (file) {
          fd.append("attachments[]", file);
        })
        $http.post($scope.fileupload, fd, {headers: {'Content-Type': undefined}})
          .success(function (res) {
            _.each(res, function (attachment) {
              if (attrs.multiple) {
                $scope.ngModel = $scope.ngModel || [];
                $scope.ngModel.push(attachment);
              } else {
                $scope.ngModel = res[0];
              }
            });
          })

        element[0].value = '';
      });
    }
  };
}]);


text:
define([],function(){
  function _blank_vm(params,element){
    this.Node_Type = '_blank';
    this.Node = element;
    this.mainclass = ko.observable('_blank');

    /* Place Properties Here */

    /* important! this is what ties this viewmodel to the main class,
     * whenever a new vm is made it calls its constructor which is the
     * main class constructor */
    this.methods = this.constructor()
    .viewmodel(this)
    .call();

    Object.keys(this).forEach((function(k,i){
      ko.attachProp(k,this);
    }).bind(this));
  }

  _blank_vm.prototype.attachProp = function(k,el){ko.attachProp(k,this,el);return this.methods;};

  /* Place Prototypes here */

  return _blank_vm;
})


text:
<?php
	#viewresource.php is a special join of rules, resource instances and statements, provides an excel-like struture for each resource class;
	#Syntax: viewresource.php?key=xxx&collection_id=yyy
	#Helena F Deus, April 20, 2007
	ini_set('display_errors',0);
	if($_REQUEST['su3d']) {
		ini_set('display_errors',1);
	}

	if($_SERVER['HTTP_X_FORWARDED_HOST']!='') {
			$def = $_SERVER['HTTP_X_FORWARDED_HOST'];
	} else {
			$def = $_SERVER['HTTP_HOST'];
	}
	if(file_exists('config.inc.php')) {
		include('config.inc.php');
	} else {
		Header('Location: http://'.$def.'/s3db/');
		exit;
	}

	$key = $_REQUEST['key'];

	#Get the key, send it to check validity
	include_once('core.header.php');

	//  if($key)
	//	  $user_id = get_entry('access_keys', 'account_id', 'key_id', $key, $db);
	//	else
	//	  $user_id = $_SESSION['user']['account_id'];

	#Universal variables
	$class_id = ($_REQUEST['collection_id']=='')?$_REQUEST['class_id']:$_REQUEST['collection_id'];
	$collection_info = URIinfo('C'.$class_id,$user_id, $key, $db);

	include('webActions.php');
	if($class_id=='') {
		echo "Please provide a collection_id";
		exit;
	} elseif(!$collection_info['view']) {
		echo "User does not have access to this resource";
		exit;
	} else {
		##For viewing statments as a table will need to have a slighly different sintax for diaplay because one combination of row/col can have more than 1 value, in that case a complete new line will need to be repeated
		#will needs rules and items
		if($_SESSION['queryresult']=='') {
			$s3ql=compact('user_id','db');
			$s3ql['select']='*';
			$s3ql['from']='items';
			$s3ql['where']['collection_id']=$class_id;
			$items = S3QLaction($s3ql);
		} else {
			$items = $_SESSION['queryresult'];
		}

		if($_REQUEST['num_per_page']!='' && $_REQUEST['current_page']!='') {
			$start = (($_REQUEST['current_page']-1)*$_REQUEST['num_per_page']);
			$end=($_REQUEST['num_per_page']*$_REQUEST['current_page']);
		} else {
			$start = 0;
			$end= count($items);
		}

		$end=(count($items)<$end)?count($items):$end;
		if(is_array($items)) {
			for ($i=$start; $i < $end; $i++) {
				if(!is_array($items[$i]['stats'])) {
					$s3ql=compact('user_id','db');
					$s3ql['from']='statements';
					$s3ql['where']['item_id']=$items[$i]['item_id'];
					$items[$i]['stats'] = S3QLaction($s3ql);
					$_SESSION['queryresult'][$i]['stats'] = $items[$i]['stats'];
				}
			}
		}

		$s3ql=compact('user_id','db');
		$s3ql['select']='*';
		$s3ql['from']='rules';
		$s3ql['where']['subject_id']=$class_id;
		$s3ql['where']['object'] = "!='UID'";
		$rules = S3QLaction($s3ql);

		##Find the values that are to be sent to datamatrix.php, both header and data
		if(!empty($rules)) {
			$verbs = array_map('grab_verb', $rules);
			foreach($verbs as $i=>$value) {
				$objects = array_map('grab_object', $rules, $verbs);
			}
		}
		#A matrix will need to be built that has rules on top,  resource_id as rows and statements in the middle
		#Create the header, which will not differ for listall or query
		$head = array('key'=>$key, 'user_id'=>$user_id,'db'=>$db, 'resource_class_id'=>$class_info['resource_id'],'class_info'=>$class_info, 'project_id'=>$project_id, 'rules'=>$rules, 'objects'=>$objects, 'verbs'=>$verbs, 'instances'=>$items,'format'=>strval($s3ql['format']), 'color'=>strval($s3ql['color']),'start'=>$start,'end'=>$end);

		$display .= create_datamatrix_header($head);
		if(is_array($items)) { $display .= render_datamatrix_values($head); }
		else echo '

Your query returned no results.

';

		echo $display;
		exit;
	}
?>


text:
package kafka.admin

import java.io.IOException
import java.nio.ByteBuffer
import java.util.{Collections, Properties}
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.{ConcurrentLinkedQueue, Future, TimeUnit}

import kafka.admin.AdminClient.DeleteRecordsResult
import kafka.common.KafkaException
import kafka.coordinator.group.GroupOverview
import kafka.utils.Logging
import org.apache.kafka.clients._
import org.apache.kafka.clients.consumer.internals.{ConsumerNetworkClient, ConsumerProtocol, RequestFuture, RequestFutureAdapter}
import org.apache.kafka.common.config.ConfigDef.{Importance, Type}
import org.apache.kafka.common.config.{AbstractConfig, ConfigDef}
import org.apache.kafka.common.errors.TimeoutException
import org.apache.kafka.common.metrics.Metrics
import org.apache.kafka.common.network.Selector
import org.apache.kafka.common.protocol.{ApiKeys, Errors}
import org.apache.kafka.common.requests._
import org.apache.kafka.common.requests.ApiVersionsResponse.ApiVersion
import org.apache.kafka.common.requests.DescribeGroupsResponse.GroupMetadata
import org.apache.kafka.common.requests.OffsetFetchResponse
import org.apache.kafka.common.utils.{KafkaThread, Time, Utils}
import org.apache.kafka.common.{Cluster, Node, TopicPartition}

import scala.collection.JavaConverters._
import scala.util.{Failure, Success, Try}

/**
  * A Scala administrative client for Kafka which supports managing and inspecting topics, brokers,
  * and configurations.  This client is deprecated, and will be replaced by KafkaAdminClient.
  * @see KafkaAdminClient
  */
class AdminClient(val time: Time,
                  val requestTimeoutMs: Int,
                  val retryBackoffMs: Long,
                  val client: ConsumerNetworkClient,
                  val bootstrapBrokers: List[Node]) extends Logging {

  @volatile var running: Boolean = true
  val pendingFutures = new ConcurrentLinkedQueue[RequestFuture[ClientResponse]]()

  val networkThread = new KafkaThread("admin-client-network-thread", new Runnable {
    override def run() {
      try {
        while (running) {
          client.poll(Long.MaxValue)
        }
      } catch {
        case t : Throwable =>
          error("admin-client-network-thread exited", t)
      } finally {
        pendingFutures.asScala.foreach { future =>
          try {
            future.raise(Errors.UNKNOWN)
          } catch {
            case _: IllegalStateException => // It is OK if the future has been completed
          }
        }
        pendingFutures.clear()
      }
    }
  }, true)

  networkThread.start()

  private def send(target: Node,
                   api: ApiKeys,
                   request: AbstractRequest.Builder[_ <: AbstractRequest]): AbstractResponse = {
    val future: RequestFuture[ClientResponse] = client.send(target, request)
    pendingFutures.add(future)
    future.awaitDone(Long.MaxValue, TimeUnit.MILLISECONDS)
    pendingFutures.remove(future)
    if (future.succeeded())
      future.value().responseBody()
    else
      throw future.exception()
  }

  private def sendAnyNode(api: ApiKeys, request: AbstractRequest.Builder[_ <: AbstractRequest]): AbstractResponse = {
    bootstrapBrokers.foreach { broker =>
      try {
        return send(broker, api, request)
      } catch {
        case e: Exception =>
          debug(s"Request $api failed against node $broker", e)
      }
    }
    throw new RuntimeException(s"Request $api failed on brokers $bootstrapBrokers")
  }

  def findCoordinator(groupId: String, timeoutMs: Long = 0): Node = {
    val requestBuilder = new FindCoordinatorRequest.Builder(FindCoordinatorRequest.CoordinatorType.GROUP, groupId)

    def sendRequest: Try[FindCoordinatorResponse] =
      Try(sendAnyNode(ApiKeys.FIND_COORDINATOR, requestBuilder).asInstanceOf[FindCoordinatorResponse])

    val startTime = time.milliseconds
    var response = sendRequest

    while ((response.isFailure || response.get.error == Errors.COORDINATOR_NOT_AVAILABLE) &&
      (time.milliseconds - startTime < timeoutMs)) {

      Thread.sleep(retryBackoffMs)
      response = sendRequest
    }

    def timeoutException(cause: Throwable) =
      throw new TimeoutException("The consumer group command timed out while waiting for group to initialize: ", cause)

    response match {
      case Failure(exception) => throw timeoutException(exception)
      case Success(response) =>
        if (response.error == Errors.COORDINATOR_NOT_AVAILABLE)
          throw timeoutException(response.error.exception)
        response.error.maybeThrow()
        response.node
    }
  }

  def listGroups(node: Node): List[GroupOverview] = {
    val response = send(node, ApiKeys.LIST_GROUPS, new ListGroupsRequest.Builder()).asInstanceOf[ListGroupsResponse]
    response.error.maybeThrow()
    response.groups.asScala.map(group => GroupOverview(group.groupId, group.protocolType)).toList
  }

  def getApiVersions(node: Node): List[ApiVersion] = {
    val response = send(node, ApiKeys.API_VERSIONS, new ApiVersionsRequest.Builder()).asInstanceOf[ApiVersionsResponse]
    response.error.maybeThrow()
    response.apiVersions.asScala.toList
  }

  /**
   * Wait until there is a non-empty list of brokers in the cluster.
   */
  def awaitBrokers() {
    var nodes = List[Node]()
    do {
      nodes = findAllBrokers()
      if (nodes.isEmpty)
        Thread.sleep(50)
    } while (nodes.isEmpty)
  }

  def findAllBrokers(): List[Node] = {
    val request = MetadataRequest.Builder.allTopics()
    val response = sendAnyNode(ApiKeys.METADATA, request).asInstanceOf[MetadataResponse]
    val errors = response.errors
    if (!errors.isEmpty)
      debug(s"Metadata request contained errors: $errors")
    response.cluster.nodes.asScala.toList
  }

  def listAllGroups(): Map[Node, List[GroupOverview]] = {
    findAllBrokers.map { broker =>
      broker -> {
        try {
          listGroups(broker)
        } catch {
          case e: Exception =>
            debug(s"Failed to find groups from broker $broker", e)
            List[GroupOverview]()
        }
      }
    }.toMap
  }

  def listAllConsumerGroups(): Map[Node, List[GroupOverview]] = {
    listAllGroups().mapValues { groups =>
      groups.filter(_.protocolType == ConsumerProtocol.PROTOCOL_TYPE)
    }
  }

  def listAllGroupsFlattened(): List[GroupOverview] = {
    listAllGroups.values.flatten.toList
  }

  def listAllConsumerGroupsFlattened(): List[GroupOverview] = {
    listAllGroupsFlattened.filter(_.protocolType == ConsumerProtocol.PROTOCOL_TYPE)
  }

  def listGroupOffsets(groupId: String): Map[TopicPartition, Long] = {
    val coordinator = findCoordinator(groupId)
    val responseBody = send(coordinator, ApiKeys.OFFSET_FETCH, OffsetFetchRequest.Builder.allTopicPartitions(groupId))
    val response = responseBody.asInstanceOf[OffsetFetchResponse]
    if (response.hasError)
      throw response.error.exception
    response.maybeThrowFirstPartitionError
    response.responseData.asScala.map { case (tp, partitionData) => (tp, partitionData.offset) }.toMap
  }

  def listAllBrokerVersionInfo(): Map[Node, Try[NodeApiVersions]] =
    findAllBrokers.map { broker =>
      broker -> Try[NodeApiVersions](new NodeApiVersions(getApiVersions(broker).asJava))
    }.toMap

  /*
   * Remove all the messages whose offset is smaller than the given offset of the corresponding partition
   *
   * DeleteRecordsResult contains either lowWatermark of the partition or exception. We list the possible exception
   * and their interpretations below:
   *
   * - DisconnectException if leader node of the partition is not available. Need retry by user.
   * - PolicyViolationException if the topic is configured as non-deletable.
   * - TopicAuthorizationException if the topic doesn't exist and the user doesn't have the authority to create the topic
   * - TimeoutException if response is not available within the timeout specified by either Future's timeout or AdminClient's request timeout
   * - UnknownTopicOrPartitionException if the partition doesn't exist or if the user doesn't have the authority to describe the topic
   * - NotLeaderForPartitionException if broker is not leader of the partition. Need retry by user.
   * - OffsetOutOfRangeException if the offset is larger than high watermark of this partition
   *
   */

  def deleteRecordsBefore(offsets: Map[TopicPartition, Long]): Future[Map[TopicPartition, DeleteRecordsResult]] = {
    val metadataRequest = new MetadataRequest.Builder(offsets.keys.map(_.topic).toSet.toList.asJava, true)
    val response = sendAnyNode(ApiKeys.METADATA, metadataRequest).asInstanceOf[MetadataResponse]
    val errors = response.errors
    if (!errors.isEmpty)
      error(s"Metadata request contained errors: $errors")

    val (partitionsWithoutError, partitionsWithError) = offsets.partition{ partitionAndOffset =>
      !response.errors().containsKey(partitionAndOffset._1.topic())}

    val (partitionsWithLeader, partitionsWithoutLeader) = partitionsWithoutError.partition{ partitionAndOffset =>
      response.cluster().leaderFor(partitionAndOffset._1) != null}

    val partitionsWithErrorResults = partitionsWithError.keys.map( partition =>
      partition -> DeleteRecordsResult(DeleteRecordsResponse.INVALID_LOW_WATERMARK, response.errors().get(partition.topic()).exception())).toMap

    val partitionsWithoutLeaderResults = partitionsWithoutLeader.mapValues( _ =>
      DeleteRecordsResult(DeleteRecordsResponse.INVALID_LOW_WATERMARK, Errors.LEADER_NOT_AVAILABLE.exception()))

    val partitionsGroupByLeader = partitionsWithLeader.groupBy(partitionAndOffset =>
      response.cluster().leaderFor(partitionAndOffset._1))

    // prepare requests and generate Future objects
    val futures = partitionsGroupByLeader.map{ case (node, partitionAndOffsets) =>
      val convertedMap: java.util.Map[TopicPartition, java.lang.Long] = partitionAndOffsets.mapValues(_.asInstanceOf[java.lang.Long]).asJava
      val future = client.send(node, new DeleteRecordsRequest.Builder(requestTimeoutMs, convertedMap))
      pendingFutures.add(future)
      future.compose(new RequestFutureAdapter[ClientResponse, Map[TopicPartition, DeleteRecordsResult]]() {
          override def onSuccess(response: ClientResponse, future: RequestFuture[Map[TopicPartition, DeleteRecordsResult]]) {
            val deleteRecordsResponse = response.responseBody().asInstanceOf[DeleteRecordsResponse]
            val result = deleteRecordsResponse.responses().asScala.mapValues(v => DeleteRecordsResult(v.lowWatermark, v.error.exception())).toMap
            future.complete(result)
            pendingFutures.remove(future)
          }

          override def onFailure(e: RuntimeException, future: RequestFuture[Map[TopicPartition, DeleteRecordsResult]]) {
            val result = partitionAndOffsets.mapValues(_ => DeleteRecordsResult(DeleteRecordsResponse.INVALID_LOW_WATERMARK, e))
            future.complete(result)
            pendingFutures.remove(future)
          }

        })
    }

    // default output if not receiving DeleteRecordsResponse before timeout
    val defaultResults = offsets.mapValues(_ =>
      DeleteRecordsResult(DeleteRecordsResponse.INVALID_LOW_WATERMARK, Errors.REQUEST_TIMED_OUT.exception())) ++ partitionsWithErrorResults ++ partitionsWithoutLeaderResults

    new CompositeFuture(time, defaultResults, futures.toList)
  }

  /**
   * Case class used to represent a consumer of a consumer group
   */
  case class ConsumerSummary(consumerId: String,
                             clientId: String,
                             host: String,
                             assignment: List[TopicPartition])

  /**
   * Case class used to represent group metadata (including the group coordinator) for the DescribeGroup API
   */
  case class ConsumerGroupSummary(state: String,
                                  assignmentStrategy: String,
                                  consumers: Option[List[ConsumerSummary]],
                                  coordinator: Node)

  def describeConsumerGroupHandler(coordinator: Node, groupId: String): GroupMetadata = {
    val responseBody = send(coordinator, ApiKeys.DESCRIBE_GROUPS,
        new DescribeGroupsRequest.Builder(Collections.singletonList(groupId)))
    val response = responseBody.asInstanceOf[DescribeGroupsResponse]
    val metadata = response.groups.get(groupId)
    if (metadata == null)
      throw new KafkaException(s"Response from broker contained no metadata for group $groupId")
    metadata
  }

  def describeConsumerGroup(groupId: String, timeoutMs: Long = 0): ConsumerGroupSummary = {

    def isValidConsumerGroupResponse(metadata: DescribeGroupsResponse.GroupMetadata): Boolean =
      metadata.error == Errors.NONE && (metadata.state == "Dead" || metadata.state == "Empty" || metadata.protocolType == ConsumerProtocol.PROTOCOL_TYPE)

    val startTime = time.milliseconds
    val coordinator = findCoordinator(groupId, timeoutMs)
    var metadata = describeConsumerGroupHandler(coordinator, groupId)

    while (!isValidConsumerGroupResponse(metadata) && time.milliseconds - startTime < timeoutMs) {
      debug(s"The consumer group response for group '$groupId' is invalid. Retrying the request as the group is initializing ...")
      Thread.sleep(retryBackoffMs)
      metadata = describeConsumerGroupHandler(coordinator, groupId)
    }

    if (!isValidConsumerGroupResponse(metadata))
      throw new TimeoutException("The consumer group command timed out while waiting for group to initialize")

    val consumers = metadata.members.asScala.map { consumer =>
      ConsumerSummary(consumer.memberId, consumer.clientId, consumer.clientHost, metadata.state match {
        case "Stable" =>
          val assignment = ConsumerProtocol.deserializeAssignment(ByteBuffer.wrap(Utils.readBytes(consumer.memberAssignment)))
          assignment.partitions.asScala.toList
        case _ =>
          List()
      })
    }.toList

    ConsumerGroupSummary(metadata.state, metadata.protocol, Some(consumers), coordinator)
  }

  def close() {
    running = false
    try {
      client.close()
    } catch {
      case e: IOException =>
        error("Exception closing nioSelector:", e)
    }
  }

}

/*
 * CompositeFuture assumes that the future object in the futures list does not raise error
 */
class CompositeFuture[T](time: Time,
                         defaultResults: Map[TopicPartition, T],
                         futures: List[RequestFuture[Map[TopicPartition, T]]]) extends Future[Map[TopicPartition, T]] {

  override def isCancelled = false

  override def cancel(interrupt: Boolean) = false

  override def get(): Map[TopicPartition, T] = {
    get(Long.MaxValue, TimeUnit.MILLISECONDS)
  }

  override def get(timeout: Long, unit: TimeUnit): Map[TopicPartition, T] = {
    val start: Long = time.milliseconds()
    val timeoutMs = unit.toMillis(timeout)
    var remaining: Long = timeoutMs

    val observedResults = futures.flatMap{ future =>
      val elapsed = time.milliseconds() - start
      remaining = if (timeoutMs - elapsed > 0) timeoutMs - elapsed else 0L

      if (future.awaitDone(remaining, TimeUnit.MILLISECONDS)) future.value()
      else Map.empty[TopicPartition, T]
    }.toMap

    defaultResults ++ observedResults
  }

  override def isDone: Boolean = {
    futures.forall(_.isDone)
  }
}

object AdminClient {
  val DefaultConnectionMaxIdleMs = 9 * 60 * 1000
  val DefaultRequestTimeoutMs = 5000
  val DefaultMaxInFlightRequestsPerConnection = 100
  val DefaultReconnectBackoffMs = 50
  val DefaultReconnectBackoffMax = 50
  val DefaultSendBufferBytes = 128 * 1024
  val DefaultReceiveBufferBytes = 32 * 1024
  val DefaultRetryBackoffMs = 100

  val AdminClientIdSequence = new AtomicInteger(1)
  val AdminConfigDef = {
    val config = new ConfigDef()
      .define(
        CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG,
        Type.LIST,
        Importance.HIGH,
        CommonClientConfigs.BOOTSTRAP_SERVERS_DOC)
      .define(
        CommonClientConfigs.SECURITY_PROTOCOL_CONFIG,
        ConfigDef.Type.STRING,
        CommonClientConfigs.DEFAULT_SECURITY_PROTOCOL,
        ConfigDef.Importance.MEDIUM,
        CommonClientConfigs.SECURITY_PROTOCOL_DOC)
      .define(
        CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG,
        ConfigDef.Type.INT,
        DefaultRequestTimeoutMs,
        ConfigDef.Importance.MEDIUM,
        CommonClientConfigs.REQUEST_TIMEOUT_MS_DOC)
      .define(
        CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG,
        ConfigDef.Type.LONG,
        DefaultRetryBackoffMs,
        ConfigDef.Importance.MEDIUM,
        CommonClientConfigs.RETRY_BACKOFF_MS_DOC)
      .withClientSslSupport()
      .withClientSaslSupport()
    config
  }

  case class DeleteRecordsResult(lowWatermark: Long, error: Exception)

  class AdminConfig(originals: Map[_,_]) extends AbstractConfig(AdminConfigDef, originals.asJava, false)

  def createSimplePlaintext(brokerUrl: String): AdminClient = {
    val config = Map(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG -> brokerUrl)
    create(new AdminConfig(config))
  }

  def create(props: Properties): AdminClient = create(props.asScala.toMap)

  def create(props: Map[String, _]): AdminClient = create(new AdminConfig(props))

  def create(config: AdminConfig): AdminClient = {
    val time = Time.SYSTEM
    val metrics = new Metrics(time)
    val metadata = new Metadata(100L, 60 * 60 * 1000L, true)
    val channelBuilder = ClientUtils.createChannelBuilder(config)
    val requestTimeoutMs = config.getInt(CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG)
    val retryBackoffMs = config.getLong(CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG)

    val brokerUrls = config.getList(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG)
    val brokerAddresses = ClientUtils.parseAndValidateAddresses(brokerUrls)
    val bootstrapCluster = Cluster.bootstrap(brokerAddresses)
    metadata.update(bootstrapCluster, Collections.emptySet(), 0)

    val selector = new Selector(
      DefaultConnectionMaxIdleMs,
      metrics,
      time,
      "admin",
      channelBuilder)

    val networkClient = new NetworkClient(
      selector,
      metadata,
      "admin-" + AdminClientIdSequence.getAndIncrement(),
      DefaultMaxInFlightRequestsPerConnection,
      DefaultReconnectBackoffMs,
      DefaultReconnectBackoffMax,
      DefaultSendBufferBytes,
      DefaultReceiveBufferBytes,
      requestTimeoutMs,
      time,
      true,
      new ApiVersions)

    val highLevelClient = new ConsumerNetworkClient(
      networkClient,
      metadata,
      time,
      retryBackoffMs,
      requestTimeoutMs.toLong)

    new AdminClient(
      time,
      requestTimeoutMs,
      retryBackoffMs,
      highLevelClient,
      bootstrapCluster.nodes.asScala.toList)
  }
}


text:
<!DOCTYPE html>

    <link type="text/css" rel="stylesheet" href="css/materialize.css"  media="screen,projection"/>

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

                                About me

                                Skills

                                Portfolio

                                Contact

        Hi there!
          I'm Anudeep

WHO I AM.

              I'm a software developer with strong professional ethics, who's passionate about building scalable enterprise apps. I currently reside at Bangalore, India.

              My other interests include music theory, football, Italian food.

WHAT I DO.

              As of now, I spend my days making pixel perfect android apps for a startup based out of Bangalore.

              Get in touch if you feel i can be of some assistance in your endeavours.


text:
module Main
       ( main -- :: IO ()
       ) where
import           Control.Applicative
import           Control.Monad
import           Data.List
import           System.Directory
import           System.FilePath

import           Test.DocTest

main :: IO ()
main = allSources >>= \sources -> doctest ("-isrc":sources)

allSources :: IO [FilePath]
allSources = liftM2 (++) (getFiles ".hs" "src")
                         (getFiles ".o" "dist/build/src/cbits")

getFiles :: String -> FilePath -> IO [FilePath]
getFiles ext root = filter (isSuffixOf ext) <$> go root
  where
    go dir = do
      (dirs, files) <- getFilesAndDirectories dir
      (files ++) . concat <$> mapM go dirs

getFilesAndDirectories :: FilePath -> IO ([FilePath], [FilePath])
getFilesAndDirectories dir = do
  c <- map (dir </>) . filter (`notElem` ["..", "."]) <$> getDirectoryContents dir
  (,) <$> filterM doesDirectoryExist c <*> filterM doesFileExist c


text:
package io.enmasse.controller.standard;

import io.enmasse.address.model.Address;
import io.enmasse.address.model.AddressSpace;
import io.enmasse.config.AnnotationKeys;
import io.enmasse.k8s.api.AddressApi;
import io.enmasse.k8s.api.AddressSpaceApi;
import io.enmasse.k8s.api.CachingSchemaProvider;
import io.enmasse.k8s.api.EventLogger;
import io.enmasse.k8s.api.KubeAddressSpaceApi;
import io.enmasse.k8s.api.KubeEventLogger;
import io.enmasse.k8s.api.KubeSchemaApi;
import io.enmasse.k8s.api.LogEventLogger;
import io.enmasse.k8s.api.SchemaApi;
import io.enmasse.metrics.api.Metrics;
import io.enmasse.model.CustomResourceDefinitions;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.utils.HttpClientUtils;
import io.vertx.core.Vertx;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Clock;
import java.util.Map;

/**
 * The standard controller is responsible for watching address spaces of type standard, creating
 * infrastructure required and propagating relevant status information.
 */

public class StandardController {
    private static final Logger log = LoggerFactory.getLogger(StandardController.class.getName());

    static {
        try {
            CustomResourceDefinitions.registerAll();
        } catch (RuntimeException t) {
            t.printStackTrace();
            throw new ExceptionInInitializerError(t);
        }
    }

    public static void main(String[] args) throws Exception {
        StandardController standardController = null;
        try {
            Map<String, String> env = System.getenv();
            StandardControllerOptions options = StandardControllerOptions.fromEnv(env);
            log.info("StandardController starting with options: {}", options);
            standardController = new StandardController(options);
            standardController.start();
        } catch (IllegalArgumentException e) {
            System.out.println(String.format("Unable to parse arguments: %s", e.getMessage()));
            System.exit(1);
        } catch (Exception e) {
            System.out.println("Error starting address space controller: " + e.getMessage());
            System.exit(1);
        } finally {
            if (standardController != null) {
                Runtime.getRuntime().addShutdownHook(new Thread(standardController::stop));
            }
        }
    }

    private final NamespacedKubernetesClient kubeClient;
    private final StandardControllerOptions options;
    private AddressController addressController;
    private HTTPServer httpServer;

    public StandardController(StandardControllerOptions options) {
        Config config = new ConfigBuilder().build();
        OkHttpClient httpClient = HttpClientUtils.createHttpClient(config);
        httpClient = httpClient.newBuilder()
                .connectTimeout(options.getKubernetesApiConnectTimeout())
                .writeTimeout(options.getKubernetesApiWriteTimeout())
                .readTimeout(options.getKubernetesApiReadTimeout())
                .build();
        this.kubeClient = new DefaultKubernetesClient(httpClient, config);
        this.options = options;
    }

    public void start() throws Exception {

        SchemaApi schemaApi = KubeSchemaApi.create(kubeClient, kubeClient.getNamespace(), options.getVersion(), false, false);
        CachingSchemaProvider schemaProvider = new CachingSchemaProvider();
        schemaApi.watchSchema(schemaProvider, options.getResyncInterval());

        Kubernetes kubernetes = new KubernetesHelper(kubeClient, options.getTemplateDir(), options.getInfraUuid());
        BrokerSetGenerator clusterGenerator = new TemplateBrokerSetGenerator(kubernetes, options, System.getenv());

        EventLogger eventLogger = options.isEnableEventLogger() ? new KubeEventLogger(kubeClient, kubeClient.getNamespace(), Clock.systemUTC(), "standard-controller")
                : new LogEventLogger();

        Metrics metrics = new Metrics();

        Vertx vertx = Vertx.vertx();

        BrokerClientFactory brokerClientFactory = new MutualTlsBrokerClientFactory(vertx, options);

        AddressSpaceApi addressSpaceApi = KubeAddressSpaceApi.create(kubeClient, options.getAddressSpaceNamespace(), options.getVersion());
        AddressSpace addressSpace = addressSpaceApi.getAddressSpaceWithName(options.getAddressSpaceNamespace(), options.getAddressSpace()).orElseThrow(() ->
                new IllegalStateException("Unable to lookup address space " + options.getAddressSpace()));

        AddressApi addressApi = addressSpaceApi.withAddressSpace(addressSpace);

        String addressPrefix = String.format("%s.", options.getAddressSpace());
        // Replace resources as part of upgrade if version is different
        for (Address address : addressApi.listAddresses(options.getAddressSpaceNamespace())) {
            if (address.getMetadata().getName().startsWith(addressPrefix)) {
                if (!options.getVersion().equals(address.getAnnotation(AnnotationKeys.VERSION))) {
                    try {
                        // Version will be updated by replaceAddress
                        addressApi.replaceAddress(address);
                    } catch (Exception e) {
                        log.warn("Error replacing {}", address.getMetadata().getName(), e);
                    }
                }
            }
        }

        addressController = new AddressController(
                options,
                addressSpaceApi,
                addressApi,
                kubernetes,
                clusterGenerator,
                eventLogger,
                schemaProvider,
                vertx,
                metrics,
                new RandomBrokerIdGenerator(),
                brokerClientFactory);

        log.info("Starting standard controller for " + options.getAddressSpace());
        addressController.start();

        httpServer = new HTTPServer( 8889, metrics);
        httpServer.start();
    }

    public void stop() {
        try {
            log.info("StandardController stopping");

            if (httpServer != null) {
                httpServer.stop();
            }
        } finally {
            try {
                if (addressController != null) {
                    try {
                        addressController.stop();
                    } catch (Exception ignore) {
                    }
                }
            } finally {
                kubeClient.close();
                log.info("StandardController stopped");
            }
        }
    }
}


text:
[CmdletBinding()]
param
(
    [Parameter()]
    [string]
    $SharePointCmdletModule = (Join-Path -Path $PSScriptRoot `
            -ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" `
            -Resolve)
)

$script:DSCModuleName = 'SharePointDsc'
$script:DSCResourceName = 'SPSearchAuthoritativePage'
$script:DSCResourceFullName = 'MSFT_' + $script:DSCResourceName

function Invoke-TestSetup
{
    try
    {
        Import-Module -Name DscResource.Test -Force

        Import-Module -Name (Join-Path -Path $PSScriptRoot `
                -ChildPath "..\UnitTestHelper.psm1" `
                -Resolve)

        $Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule `
            -DscResource $script:DSCResourceName
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.'
    }

    $script:testEnvironment = Initialize-TestEnvironment `
        -DSCModuleName $script:DSCModuleName `
        -DSCResourceName $script:DSCResourceFullName `
        -ResourceType 'Mof' `
        -TestType 'Unit'
}

function Invoke-TestCleanup
{
    Restore-TestEnvironment -TestEnvironment $script:testEnvironment
}

Invoke-TestSetup

try
{
    InModuleScope -ModuleName $script:DSCResourceFullName -ScriptBlock {
        Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture {
            BeforeAll {
                Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope
                try
                {
                    Add-Type -TypeDefinition @"
        namespace Microsoft.Office.Server.Search.Administration {
            public enum SearchObjectLevel
            {
                SPWeb,
                SPSite,
                SPSiteSubscription,
                Ssa
            }

            public class SearchObjectOwner {
                public SearchObjectOwner(Microsoft.Office.Server.Search.Administration.SearchObjectLevel level) { }
            }
        }
"@ -ErrorAction SilentlyContinue
                }
                catch
                {

                }

                # Mocks for all contexts
                Mock -CommandName Get-SPEnterpriseSearchQueryAuthority -MockWith { }
                Mock -CommandName New-SPEnterpriseSearchQueryAuthority -MockWith { }
                Mock -CommandName Set-SPEnterpriseSearchQueryAuthority -MockWith { }
                Mock -CommandName Remove-SPEnterpriseSearchQueryAuthority -MockWith { }

                Mock -CommandName Get-SPEnterpriseSearchQueryDemoted -MockWith { }
                Mock -CommandName New-SPEnterpriseSearchQueryDemoted -MockWith { }
                Mock -CommandName Remove-SPEnterpriseSearchQueryDemoted -MockWith { }

                function Add-SPDscEvent
                {
                    param (
                        [Parameter(Mandatory = $true)]
                        [System.String]
                        $Message,

                        [Parameter(Mandatory = $true)]
                        [System.String]
                        $Source,

                        [Parameter()]
                        [ValidateSet('Error', 'Information', 'FailureAudit', 'SuccessAudit', 'Warning')]
                        [System.String]
                        $EntryType,

                        [Parameter()]
                        [System.UInt32]
                        $EventID
                    )
                }
            }

            # Test contexts
            Context -Name "A SharePoint Search Service doesn't exists" {
                BeforeAll {
                    $testParams = @{
                        ServiceAppName = "Search Service Application"
                        Path           = "http://site.sharepoint.com/pages/authoratative.aspx"
                        Action         = "Authoratative"
                        Level          = 0.0
                        Ensure         = "Present"
                    }

                    Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith {
                        return $null
                    }
                }

                It "Should return absent from the get method" {
                    (Get-TargetResource @testParams).Ensure | Should -Be "Absent"
                }

                It "Should return false from the test method" {
                    Test-TargetResource @testParams | Should -Be $false
                }

                It "Should throw an exception in the set method" {
                    { Set-TargetResource @testParams } | Should -Throw "Search Service App was not available."

                }
            }

            Context -Name "A search query authoratative page does exist and should" {
                BeforeAll {
                    $testParams = @{
                        ServiceAppName = "Search Service Application"
                        Path           = "http://site.sharepoint.com/pages/authoratative.aspx"
                        Action         = "Authoratative"
                        Level          = 0.0
                        Ensure         = "Present"
                    }

                    Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith {
                        return @{
                            DisplayName = $testParams.ServiceAppName
                        }
                    }

                    Mock -CommandName  Get-SPEnterpriseSearchQueryAuthority -MockWith {
                        return @{
                            Identity = $testParams.Path
                            Level    = $testParams.Level
                        }
                    }

                    Mock -CommandName Set-SPEnterpriseSearchQueryAuthority -MockWith {
                        return @{
                            Identity = $testParams.Path
                            Level    = $testParams.Level
                        }
                    }
                }

                It "Should return present from the get method" {
                    $result = Get-TargetResource @testParams
                    $result.Ensure | Should -Be "Present"
                }

                It "Should return true from the test method" {
                    Test-TargetResource @testParams | Should -Be $true
                }

                It "Should call Set functions from the Set method" {
                    Set-TargetResource @testParams
                    Assert-MockCalled Get-SPEnterpriseSearchServiceApplication -Times 1
                    Assert-MockCalled Set-SPEnterpriseSearchQueryAuthority -Times 1
                }

            }

            Context -Name "A search query authoratative page does exist and shouldn't" {
                BeforeAll {
                    $testParams = @{
                        ServiceAppName = "Search Service Application"
                        Path           = "http://site.sharepoint.com/pages/authoratative.aspx"
                        Action         = "Authoratative"
                        Level          = 0.0
                        Ensure         = "Absent"
                    }

                    Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith {
                        return @{
                            DisplayName = $testParams.ServiceAppName
                        }
                    }

                    Mock -CommandName  Get-SPEnterpriseSearchQueryAuthority -MockWith {
                        return @{
                            Identity = $testParams.Path
                            Level    = $testParams.Level
                        }
                    }

                    Mock -CommandName Remove-SPEnterpriseSearchQueryAuthority -MockWith {
                        return $null
                    }
                }

                It "Should return present from the get method" {
                    $result = Get-TargetResource @testParams
                    $result.Ensure | Should -Be "Present"
                }

                It "Should return false from the test method" {
                    Test-TargetResource @testParams | Should -Be $false
                }

                It "Should call Set functions from the Set method" {
                    Set-TargetResource @testParams
                    Assert-MockCalled Get-SPEnterpriseSearchServiceApplication -Times 1
                    Assert-MockCalled Remove-SPEnterpriseSearchQueryAuthority -Times 1
                }
            }

            Context -Name "A search query authoratative page doesn't exist and shouldn't" {
                BeforeAll {
                    $testParams = @{
                        ServiceAppName = "Search Service Application"
                        Path           = "http://site.sharepoint.com/pages/authoratative.aspx"
                        Action         = "Authoratative"
                        Level          = 0.0
                        Ensure         = "Absent"
                    }

                    Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith {
                        return @{
                            DisplayName = $testParams.ServiceAppName
                        }
                    }

                    Mock -CommandName  Get-SPEnterpriseSearchQueryAuthority -MockWith {
                        return $null
                    }

                    Mock -CommandName Remove-SPEnterpriseSearchQueryAuthority -MockWith {
                        return $null
                    }
                }

                It "Should return absent from the get method" {
                    $result = Get-TargetResource @testParams
                    $result.Ensure | Should -Be "Absent"
                }

                It "Should return true from the test method" {
                    Test-TargetResource @testParams | Should -Be $true
                }

                It "Should call Set functions from the Set method" {
                    Set-TargetResource @testParams
                    Assert-MockCalled Get-SPEnterpriseSearchServiceApplication -Times 1
                    Assert-MockCalled Remove-SPEnterpriseSearchQueryAuthority -Times 1
                }
            }

            Context -Name "A search query authoratative page doesn't exist but should" -Fixture {
                BeforeAll {
                    $testParams = @{
                        ServiceAppName = "Search Service Application"
                        Path           = "http://site.sharepoint.com/pages/authoratative.aspx"
                        Action         = "Authoratative"
                        Level          = 0.0
                        Ensure         = "Present"
                    }

                    Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith {
                        return @{
                            DisplayName = $testParams.ServiceAppName
                        }
                    }

                    Mock -CommandName  Get-SPEnterpriseSearchQueryAuthority -MockWith {
                        return $null
                    }

                    Mock -CommandName New-SPEnterpriseSearchQueryAuthority -MockWith {
                        return @{
                            Identity = $testParams.Path
                            Level    = $testParams.Level
                        }
                    }
                }

                It "Should return absent from the get method" {
                    $result = Get-TargetResource @testParams
                    $result.Ensure | Should -Be "Absent"
                }

                It "Should return false from the test method" {
                    Test-TargetResource @testParams | Should -Be $false
                }

                It "Should create the content source in the set method" {
                    Set-TargetResource @testParams

                    Assert-MockCalled -CommandName Get-SPEnterpriseSearchServiceApplication -Times 1
                }
            }

            Context -Name "A search query demoted page does exist and should" {
                BeforeAll {
                    $testParams = @{
                        ServiceAppName = "Search Service Application"
                        Path           = "http://site.sharepoint.com/pages/authoratative.aspx"
                        Action         = "Demoted"
                        Ensure         = "Present"
                    }

                    Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith {
                        return @{
                            DisplayName = $testParams.ServiceAppName
                        }
                    }

                    Mock -CommandName  Get-SPEnterpriseSearchQueryDemoted -MockWith {
                        return @{
                            Identity = $testParams.Path
                        }
                    }
                }

                It "Should return present from the get method" {
                    $result = Get-TargetResource @testParams
                    $result.Ensure | Should -Be "Present"
                }

                It "Should return true from the test method" {
                    Test-TargetResource @testParams | Should -Be $true
                }

                It "Should create the content source in the set method" {
                    Set-TargetResource @testParams

                    Assert-MockCalled -CommandName Get-SPEnterpriseSearchServiceApplication -Times 1
                }
            }

            Context -Name "A search query demoted page does exist and shouldn't" {
                BeforeAll {
                    $testParams = @{
                        ServiceAppName = "Search Service Application"
                        Path           = "http://site.sharepoint.com/pages/authoratative.aspx"
                        Action         = "Demoted"
                        Ensure         = "Absent"
                    }

                    Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith {
                        return @{
                            DisplayName = $testParams.ServiceAppName
                        }
                    }

                    Mock -CommandName  Get-SPEnterpriseSearchQueryDemoted -MockWith {
                        return @{
                            Identity = $testParams.Path
                        }
                    }
                }

                It "Should return present from the get method" {
                    $result = Get-TargetResource @testParams
                    $result.Ensure | Should -Be "Present"
                }

                It "Should return false from the test method" {
                    Test-TargetResource @testParams | Should -Be $false
                }

                It "Should remove the content source in the set method" {
                    Set-TargetResource @testParams

                    Assert-MockCalled -CommandName Get-SPEnterpriseSearchServiceApplication -Times 1
                    Assert-MockCalled -CommandName Remove-SPEnterpriseSearchQueryDemoted -Times 1
                }
            }

            Context -Name "A search query demoted page doesn't exist and shouldn't" {
                BeforeAll {
                    $testParams = @{
                        ServiceAppName = "Search Service Application"
                        Path           = "http://site.sharepoint.com/pages/authoratative.aspx"
                        Action         = "Demoted"
                        Ensure         = "Absent"
                    }

                    Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith {
                        return @{
                            DisplayName = $testParams.ServiceAppName
                        }
                    }

                    Mock -CommandName  Get-SPEnterpriseSearchQueryDemoted -MockWith {
                        return $null
                    }
                }

                It "Should return absent from the get method" {
                    $result = Get-TargetResource @testParams
                    $result.Ensure | Should -Be "Absent"
                }

                It "Should return true from the test method" {
                    Test-TargetResource @testParams | Should -Be $true
                }
                It "Should remove the content source in the set method" {
                    Set-TargetResource @testParams

                    Assert-MockCalled -CommandName Get-SPEnterpriseSearchServiceApplication -Times 1
                    Assert-MockCalled -CommandName Remove-SPEnterpriseSearchQueryDemoted -Times 1
                }
            }

            Context -Name "A search query demoted page doesn't exist but should" -Fixture {
                BeforeAll {
                    $testParams = @{
                        ServiceAppName = "Search Service Application"
                        Path           = "http://site.sharepoint.com/pages/authoratative.aspx"
                        Action         = "Demoted"
                        Ensure         = "Present"
                    }

                    Mock -CommandName Get-SPEnterpriseSearchServiceApplication -MockWith {
                        return @{
                            DisplayName = $testParams.ServiceAppName
                        }
                    }

                    Mock -CommandName  Get-SPEnterpriseSearchQueryDemoted -MockWith {
                        return $null
                    }

                    Mock -CommandName  New-SPEnterpriseSearchQueryDemoted -MockWith {
                        return @{
                            Url = $params.Path
                        }
                    }
                }

                It "Should return absent from the get method" {
                    $result = Get-TargetResource @testParams
                    $result.Ensure | Should -Be "Absent"
                }

                It "Should return false from the test method" {
                    Test-TargetResource @testParams | Should -Be $false
                }

                It "Should create a new query demoted element in the set method" {
                    Set-TargetResource @testParams

                    Assert-MockCalled -CommandName Get-SPEnterpriseSearchServiceApplication -Times 1
                    Assert-MockCalled -CommandName New-SPEnterpriseSearchQueryDemoted -Times 1
                }
            }

        }
    }
}
finally
{
    Invoke-TestCleanup
}


text:
enum class KeepAliveOrigin {
  // c/b
  APP_CONTROLLER,
  BROWSER,
  BROWSER_PROCESS_CHROMEOS,
  BROWSER_PROCESS_LACROS,
  SESSION_RESTORE,

  // c/b/background
  BACKGROUND_MODE_MANAGER,
  BACKGROUND_MODE_MANAGER_STARTUP,
  BACKGROUND_MODE_MANAGER_FORCE_INSTALLED_EXTENSIONS,

  // c/b/background_sync
  BACKGROUND_SYNC,

  // c/b/browsing_data
  BROWSING_DATA_LIFETIME_MANAGER,

  // c/b/chromeos
  LOGIN_DISPLAY_HOST_WEBUI,
  PIN_MIGRATION,

  // c/b/devtools
  REMOTE_DEBUGGING,
  DEVTOOLS_WINDOW,

  // c/b/extensions
  NATIVE_MESSAGING_HOST_ERROR_REPORT,

  // c/b/notifications
  NOTIFICATION,
  PENDING_NOTIFICATION_CLICK_EVENT,
  PENDING_NOTIFICATION_CLOSE_EVENT,

  // c/b/push_messaging
  IN_FLIGHT_PUSH_MESSAGE,

  // c/b/ui
  APP_LIST_SERVICE_VIEWS,
  APP_LIST_SHOWER,
  CHROME_APP_DELEGATE,
  CHROME_VIEWS_DELEGATE,
  PANEL,
  PANEL_VIEW,
  PROFILE_HELPER,
  PROFILE_LOADER,
  USER_MANAGER_VIEW,
  CREDENTIAL_PROVIDER_SIGNIN_DIALOG,
  WEB_APP_INTENT_PICKER,

  // c/b/web_applications
  APP_MANIFEST_UPDATE,
  APP_START_URL_MIGRATION,

  // c/b/sessions
  SESSION_DATA_DELETER,
};

// Restart: Allow Chrome to restart when all the registered KeepAlives allow
// restarts
enum class KeepAliveRestartOption { DISABLED, ENABLED };

std::ostream& operator<<(std::ostream& out, const KeepAliveOrigin& origin);
std::ostream& operator<<(std::ostream& out,
                         const KeepAliveRestartOption& restart);

#endif  // COMPONENTS_KEEP_ALIVE_REGISTRY_KEEP_ALIVE_TYPES_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/sendbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="send" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/renamebutton"
            style="@style/buttonStyle"
            android:text="rename" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/deletebutton"
            style="@style/buttonStyle"
            android:text="delete" />
    </LinearLayout>

</LinearLayout>


text:
layout: post
section-type: post
title: How To Move Jenkins To Another Server
category: devops
tags: [ 'jenkins', 'ci', 'backup', 'devops','restore' ]
---
###How to move jenkins to another server
1. Stop both Jenkins server
2. Copy JENKINS_HOME (e.g. /var/lib/jenkins) from the old server to the new one. From a console in the new server:

rsync -av username@old-server-ip:/var/lib/jenkins/ /var/lib/jenkins/

3. Start your new jenkins server

You minght not need this, but I had to
* Manage Jenkins and Reload Configuration fromm Disk
* Disconnect and connect all the slaves again
* Check that in the Configure System -> Jenkins Location, the Jenkins URL is correctly assigned to the new Jenkins server.


text:
var React = require('react');

module.exports = React.createClass({
  displayName: 'MaxwellModalHeader',
  propTypes: {
    dismissable: React.PropTypes.bool,
    title: React.PropTypes.string
  },

  render: function () {
    var dismissable = this.props.dismissable ? (<button type="button" className="close" data-dismiss="modal" aria-label="Close" onClick={this.props.onRequestClose}>×</button>) : '';
    var header = (

        {dismissable}

{this.props.title}

      );
    return(
{header}
);
  }
});


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

    <string name="app_name">kings-land</string>

</resources>


text:
search:
   keywords: ['Java API', 'OElement', 'is edge', 'isEdge']
---

# OElement - isEdge()

This method determines whether the record is an edge.

## Checking Edges

When OrientDB is serving as a Graph database, [`OElement`](../OElement.md) serves as the superclass to both edges and vertices.  Using this method you can check whether or not the element is an edge on the database.  To determine whether the record is a vertex, see [`isVertex`](isVertex.md).

### Syntax

```
Boolean OElement().isEdge()
```

#### Return Value

This method returns a [`Boolean`]({{ book.javase }}/api/java/lang/Boolean.html) instance.  If the return value is `true`, the element is an edge.


text:
<?php

namespace Magium\Magento\Navigators\Admin;

use Magium\Actions\WaitForPageLoaded;
use Magium\Magento\Navigators\BaseMenu;
use Magium\Magento\Themes\Admin\ThemeConfiguration;
use Magium\Util\Log\Logger;
use Magium\WebDriver\WebDriver;

class AdminMenu extends BaseMenu
{
    const NAVIGATOR = 'Admin\AdminMenu';

    public function __construct(
        ThemeConfiguration $theme,
        WebDriver $webdriver,
        WaitForPageLoaded $loaded,
        Logger $logger)
    {
        parent::__construct($theme, $webdriver, $loaded, $logger);
    }

}


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

namespace GoMusic.StringSimilarityAlgorithms
{
    public class DiceCoefficient
    {
        /// <summary>
        /// This class implements string comparison algorithm
        /// based on character pair similarity
        /// Source: http://www.catalysoft.com/articles/StrikeAMatch.html
        /// </summary>
        public static double PercentMatchTo(string str1, string str2)
        {
            List<string> pairs1 = WordLetterPairs(str1.ToUpper());
            List<string> pairs2 = WordLetterPairs(str2.ToUpper());

            int intersection = 0;
            int union = pairs1.Count + pairs2.Count;

            for (int i = 0; i < pairs1.Count; i++)
            {
                for (int j = 0; j < pairs2.Count; j++)
                {
                    if (pairs1[i] == pairs2[j])
                    {
                        intersection++;
                        pairs2.RemoveAt(j);//Must remove the match to prevent "GGGG" from appearing to match "GG" with 100% success

                        break;
                    }
                }
            }

            return (2.0 * intersection) / union;
        }

        /// <summary>
        /// Gets all letter pairs for each
        /// individual word in the string
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static List<string> WordLetterPairs(string str)
        {
            List<string> AllPairs = new List<string>();

            // Tokenize the string and put the tokens/words into an array
            string[] Words = System.Text.RegularExpressions.Regex.Split(str, @"\s");

            // For each word
            for (int w = 0; w < Words.Length; w++)
            {
                if (!string.IsNullOrEmpty(Words[w]))
                {
                    // Find the pairs of characters
                    String[] PairsInWord = LetterPairs(Words[w]);

                    for (int p = 0; p < PairsInWord.Length; p++)
                    {
                        AllPairs.Add(PairsInWord[p]);
                    }
                }
            }

            return AllPairs;
        }

        /// <summary>
        /// Generates an array containing every
        /// two consecutive letters in the input string
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string[] LetterPairs(string str)
        {
            int numPairs = str.Length - 1;

            string[] pairs = new string[numPairs];

            for (int i = 0; i < numPairs; i++)
            {
                pairs[i] = str.Substring(i, 2);
            }

            return pairs;
        }
    }
}


text:
require 'test_helper'
require 'rails'

class Rails3IntegrationTest < Test::Unit::TestCase
  context "rails3 integration class" do
    setup do
      @klass = Radar::Integration::Rails3
      @app = Radar::Application.new(:app, :register => false)
    end

    teardown do
      # HACK I don't think rails was ever intended to work this way,
      # but I'm able to clear out the application using this.
      Rails.application = nil
    end

    should "raise an argument error if an application is not specified" do
      assert_raises(ArgumentError) { @klass.integrate!(@app) }
    end

    should "integrate with a rails application" do
      # NOTE This test used to actually initialize the rails application
      # but it was creating a `log/` directory in the toplevel which was
      # pretty annoying. So this suffices for now.
      rails_app = Class.new(Rails::Application)
      assert_nothing_raised { @klass.integrate!(@app) }
    end
  end
end


text:
/* 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.
 */

package org.flowable.engine.impl.cmd;

import java.util.Map;

import org.flowable.engine.compatibility.Flowable5CompatibilityHandler;
import org.flowable.engine.impl.form.TaskFormHandler;
import org.flowable.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.TaskEntity;
import org.flowable.engine.impl.util.Flowable5Util;
import org.flowable.engine.impl.util.FormHandlerUtil;
import org.flowable.engine.impl.util.TaskHelper;

/**
 * @author Tom Baeyens
 * @author Joram Barrez
 */
public class SubmitTaskFormCmd extends NeedsActiveTaskCmd<Void> {

    private static final long serialVersionUID = 1L;

    protected String taskId;
    protected Map<String, String> properties;
    protected boolean completeTask;

    public SubmitTaskFormCmd(String taskId, Map<String, String> properties, boolean completeTask) {
        super(taskId);
        this.taskId = taskId;
        this.properties = properties;
        this.completeTask = completeTask;
    }

    protected Void execute(CommandContext commandContext, TaskEntity task) {

        // Backwards compatibility
        if (task.getProcessDefinitionId() != null) {
            if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, task.getProcessDefinitionId())) {
                Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
                compatibilityHandler.submitTaskFormData(taskId, properties, completeTask);
                return null;
            }
        }

        commandContext.getHistoryManager().recordFormPropertiesSubmitted(task.getExecution(), properties, taskId);

        TaskFormHandler taskFormHandler = FormHandlerUtil.getTaskFormHandlder(task);

        if (taskFormHandler != null) {
            taskFormHandler.submitFormProperties(properties, task.getExecution());

            if (completeTask) {
                TaskHelper.completeTask(task, null, null, false, commandContext);
            }
        }

        return null;
    }

    @Override
    protected String getSuspendedTaskException() {
        return "Cannot submit a form to a suspended task";
    }

}


text:
simple-snippets-console
=======================

Temporary simple snippets console until http://meta.stackexchange.com/questions/239706 is done!


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.apache.oltu.commons</groupId>
    <artifactId>org.apache.oltu.commons.parent</artifactId>
    <version>2-SNAPSHOT</version>
  </parent>

  <artifactId>org.apache.oltu.commons.json</artifactId>
  <version>1.0.1-SNAPSHOT</version>
  <packaging>bundle</packaging>

  <name>Apache Oltu - Commons - JSON</name>
  <description>Apache Oltu JSON shared utility</description>

  <dependencies>
    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20140107</version>
    </dependency>
  </dependencies>

</project>


text:
(function (window) {
	if (!window.console) {
		console = {};
	}

	var funcs = 'assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn'.split(','),
		stub = function () { };

	for (var i = 0; i < funcs.length; i++) {
		if (!console[funcs[i]]) {
			console[funcs[i]] = stub;
		}
	}
})(window);