<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 * @author marklundin / http://mark-lundin.com/
 * @author alteredq / http://alteredqualia.com/
 * @author tschw
 */

THREE.AnaglyphEffect = function ( renderer, width, height ) {

	// Matrices generated with angler.js https://github.com/tschw/angler.js/
	// (in column-major element order, as accepted by WebGL)

	this.colorMatrixLeft = new THREE.Matrix3().fromArray( [

			1.0671679973602295, 	-0.0016435992438346148,		 0.0001777536963345483, // r out
			-0.028107794001698494,	-0.00019593400065787137,	-0.0002875397040043026, // g out
			-0.04279090091586113,	 0.000015809757314855233,	-0.00024287120322696865 // b out

	] );

	//		red						green 						blue  						in

	this.colorMatrixRight = new THREE.Matrix3().fromArray( [

			-0.0355340838432312,	-0.06440307199954987,		 0.018319187685847282,	// r out
			-0.10269022732973099,	 0.8079727292060852,		-0.04835830628871918,	// g out
			0.0001224992738571018,	-0.009558862075209618,		 0.567823588848114		// b out

	] );

	var _camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );

	var _scene = new THREE.Scene();

	var _stereo = new THREE.StereoCamera();

	var _params = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };

	if ( width === undefined ) width = 512;
	if ( height === undefined ) height = 512;

	var _renderTargetL = new THREE.WebGLRenderTarget( width, height, _params );
	var _renderTargetR = new THREE.WebGLRenderTarget( width, height, _params );

	var _material = new THREE.ShaderMaterial( {

		uniforms: {

			"mapLeft": { value: _renderTargetL.texture },
			"mapRight": { value: _renderTargetR.texture },

			"colorMatrixLeft": { value: this.colorMatrixLeft },
			"colorMatrixRight": { value: this.colorMatrixRight }

		},

		vertexShader: [

			"varying vec2 vUv;",

			"void main() {",

			"	vUv = vec2( uv.x, uv.y );",
			"	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

			"}"

		].join( "\n" ),

		fragmentShader: [

			"uniform sampler2D mapLeft;",
			"uniform sampler2D mapRight;",
			"varying vec2 vUv;",

			"uniform mat3 colorMatrixLeft;",
			"uniform mat3 colorMatrixRight;",

			// These functions implement sRGB linearization and gamma correction

			"float lin( float c ) {",
			"	return c <= 0.04045 ? c * 0.0773993808 :",
			"			pow( c * 0.9478672986 + 0.0521327014, 2.4 );",
			"}",

			"vec4 lin( vec4 c ) {",
			"	return vec4( lin( c.r ), lin( c.g ), lin( c.b ), c.a );",
			"}",

			"float dev( float c ) {",
			"	return c <= 0.0031308 ? c * 12.92",
			"			: pow( c, 0.41666 ) * 1.055 - 0.055;",
			"}",

			"void main() {",

			"	vec2 uv = vUv;",

			"	vec4 colorL = lin( texture2D( mapLeft, uv ) );",
			"	vec4 colorR = lin( texture2D( mapRight, uv ) );",

			"	vec3 color = clamp(",
			"			colorMatrixLeft * colorL.rgb +",
			"			colorMatrixRight * colorR.rgb, 0., 1. );",

			"	gl_FragColor = vec4(",
			"			dev( color.r ), dev( color.g ), dev( color.b ),",
			"			max( colorL.a, colorR.a ) );",

			"}"

		].join( "\n" )

	} );

	var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), _material );
	_scene.add( mesh );

	this.setSize = function ( width, height ) {

		renderer.setSize( width, height );

		var pixelRatio = renderer.getPixelRatio();

		_renderTargetL.setSize( width * pixelRatio, height * pixelRatio );
		_renderTargetR.setSize( width * pixelRatio, height * pixelRatio );

	};

	this.render = function ( scene, camera ) {

		scene.updateMatrixWorld();

		if ( camera.parent === null ) camera.updateMatrixWorld();

		_stereo.update( camera );

		renderer.render( scene, _stereo.cameraL, _renderTargetL, true );
		renderer.render( scene, _stereo.cameraR, _renderTargetR, true );
		renderer.render( _scene, _camera );

	};

	this.dispose = function() {

		if ( _renderTargetL ) _renderTargetL.dispose();
		if ( _renderTargetR ) _renderTargetR.dispose();

	};

};
<commit_msg>dispose of all objects<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 * @author marklundin / http://mark-lundin.com/
 * @author alteredq / http://alteredqualia.com/
 * @author tschw
 */

THREE.AnaglyphEffect = function ( renderer, width, height ) {

	// Matrices generated with angler.js https://github.com/tschw/angler.js/
	// (in column-major element order, as accepted by WebGL)

	this.colorMatrixLeft = new THREE.Matrix3().fromArray( [

			1.0671679973602295, 	-0.0016435992438346148,		 0.0001777536963345483, // r out
			-0.028107794001698494,	-0.00019593400065787137,	-0.0002875397040043026, // g out
			-0.04279090091586113,	 0.000015809757314855233,	-0.00024287120322696865 // b out

	] );

	//		red						green 						blue  						in

	this.colorMatrixRight = new THREE.Matrix3().fromArray( [

			-0.0355340838432312,	-0.06440307199954987,		 0.018319187685847282,	// r out
			-0.10269022732973099,	 0.8079727292060852,		-0.04835830628871918,	// g out
			0.0001224992738571018,	-0.009558862075209618,		 0.567823588848114		// b out

	] );

	var _camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );

	var _scene = new THREE.Scene();

	var _stereo = new THREE.StereoCamera();

	var _params = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };

	if ( width === undefined ) width = 512;
	if ( height === undefined ) height = 512;

	var _renderTargetL = new THREE.WebGLRenderTarget( width, height, _params );
	var _renderTargetR = new THREE.WebGLRenderTarget( width, height, _params );

	var _material = new THREE.ShaderMaterial( {

		uniforms: {

			"mapLeft": { value: _renderTargetL.texture },
			"mapRight": { value: _renderTargetR.texture },

			"colorMatrixLeft": { value: this.colorMatrixLeft },
			"colorMatrixRight": { value: this.colorMatrixRight }

		},

		vertexShader: [

			"varying vec2 vUv;",

			"void main() {",

			"	vUv = vec2( uv.x, uv.y );",
			"	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

			"}"

		].join( "\n" ),

		fragmentShader: [

			"uniform sampler2D mapLeft;",
			"uniform sampler2D mapRight;",
			"varying vec2 vUv;",

			"uniform mat3 colorMatrixLeft;",
			"uniform mat3 colorMatrixRight;",

			// These functions implement sRGB linearization and gamma correction

			"float lin( float c ) {",
			"	return c <= 0.04045 ? c * 0.0773993808 :",
			"			pow( c * 0.9478672986 + 0.0521327014, 2.4 );",
			"}",

			"vec4 lin( vec4 c ) {",
			"	return vec4( lin( c.r ), lin( c.g ), lin( c.b ), c.a );",
			"}",

			"float dev( float c ) {",
			"	return c <= 0.0031308 ? c * 12.92",
			"			: pow( c, 0.41666 ) * 1.055 - 0.055;",
			"}",

			"void main() {",

			"	vec2 uv = vUv;",

			"	vec4 colorL = lin( texture2D( mapLeft, uv ) );",
			"	vec4 colorR = lin( texture2D( mapRight, uv ) );",

			"	vec3 color = clamp(",
			"			colorMatrixLeft * colorL.rgb +",
			"			colorMatrixRight * colorR.rgb, 0., 1. );",

			"	gl_FragColor = vec4(",
			"			dev( color.r ), dev( color.g ), dev( color.b ),",
			"			max( colorL.a, colorR.a ) );",

			"}"

		].join( "\n" )

	} );

	var _mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), _material );
	_scene.add( _mesh );

	this.setSize = function ( width, height ) {

		renderer.setSize( width, height );

		var pixelRatio = renderer.getPixelRatio();

		_renderTargetL.setSize( width * pixelRatio, height * pixelRatio );
		_renderTargetR.setSize( width * pixelRatio, height * pixelRatio );

	};

	this.render = function ( scene, camera ) {

		scene.updateMatrixWorld();

		if ( camera.parent === null ) camera.updateMatrixWorld();

		_stereo.update( camera );

		renderer.render( scene, _stereo.cameraL, _renderTargetL, true );
		renderer.render( scene, _stereo.cameraR, _renderTargetR, true );
		renderer.render( _scene, _camera );

	};

	this.dispose = function () {

		if ( _renderTargetL ) _renderTargetL.dispose();
		if ( _renderTargetR ) _renderTargetR.dispose();
		if ( _mesh ) _mesh.geometry.dispose();
		if ( _material ) _material.dispose();

	};

};
<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 *`git pull` from the repo and branch that a PR originates from.
 * Copyright 2019 Matthew Brookes. License: MIT
 */

var https = require('https');
var execSync = require('child_process').execSync;
var fs = require('fs');

var version = 'git-pull-request 2.0.1';
var use = '\n ' + version + '\n\n gpr [-i | -l [-r] | -p | -f | -b [<name>] | -n | -d | -D | -v | -h] <pr#>';

var hint = ' By default, `gpr <pr#>` will fetch the remote branch for <pr#> and checkout on a detached HEAD.';

var usage = use + '\n\n' + hint + '\n\n gpr [-h | --help] for detailed usage.';
var help = use +

'\n\n [-i | info] <pr#>               Show the PR title and requestor for <pr#>.\n\
 [-l | ls | list] [-r | remote]  List local gpr branches. / List 30 most recent open PRs.\n\
\n\
 [-u | |update | pull] <pr#>     Pull the remote branch for <pr#> to the current branch.\n\
 [-f | force] <pr#>              Force overwrite the local branch and checkout on a detached HEAD.\n\
 [-b | branch] [<name>] <pr#>    Create new branch [name] from master and pull. Defaults to \'gpr/<pr#>\'.\n\
 [-n | named] <user:branch>      Fetch from the named ref and checkout on a detached HEAD.\n\
\n\
 [-p | push] <user:branch>       Push the current branch or detached HEAD to the remote branch.\n\
 [-P | Push] <<user:branch>      Force push the current branch or detached HEAD to the remote branch.\n\
\n\
 [-d | delete] <pr#>             Delete the gpr/<pr#> branch.\n\
 [-D | Delete] <pr#>             Force delete the gpr/<pr#> branch.\n\
\n\
 [-v | version]                  Show git-pull-request version.\n\
 [-h | help]                     This help.\n\
\n\
 <pr#>                           PR number to apply the command to.\n\n' + hint;

// Read the command-line args
var args = process.argv;

if (args.length < 3) {
  exit(usage);
}

// Exit with a message
function exit(error) {
  console.error(error,'\n');
  process.exit();
};

// Exec with echo
function execho(command) {
  console.log(command);
  try {
    console.log(execSync(command, {encoding: 'utf8'}));
  } catch (error) {
   console.error(error.output[1]);
  }
}

try {
  var npmPrefix = execSync('npm prefix', {cwd: process.cwd(), encoding: 'utf8'}).replace(/\s+/g, '');
} catch (error) {}

// Read the package.json and extract the repo name
if (fs.existsSync(npmPrefix + '/package.json')) {
  var packageFile = JSON.parse(fs.readFileSync(npmPrefix + '/package.json', 'utf8'));

  // repo: [ 'https:', '', 'github.com', 'mui-org', 'material-ui.git' ],
  var repo = packageFile.repository.url.split('/');

  // repoName: 'material-ui'
  var repoName = repo[4].slice(0, -4);

  // path: '/repos/mui-org/material-ui/pulls'
  var path = '/repos/' + repo[3]+ '/' + repoName + '/pulls';

  // If there's no package.json, try .git config upstream / origin
} else {
  try {
    var gitPrefix = execSync('git rev-parse --show-toplevel', {cwd: process.cwd(), encoding: 'utf8'}).replace(/\s+/g, '');
  } catch (error) {
    exit(error.output[1]);
  }

  if (fs.existsSync(gitPrefix + '/.git/config')) {
    var gitConfig = fs.readFileSync(gitPrefix + '/.git/config', 'utf8');

    // repo: [ 'https:', '', 'github.com', 'mui-org', 'material-ui.git' ],
    var repo = gitConfig.match(/\[remote "upstream"\][\r\n|\r|\n]\s*url\s=\s(.*)/);

    if (!repo) {
      repo = gitConfig.match(/\[remote "origin"\][\r\n|\r|\n]\s*url\s=\s(.*)/);
      if (!repo) {
        exit('No "upstream" or "origin" remote found in .git/config')
      }
    }
    repo = repo[1].split('/');

    // repoName: 'material-ui'
    var repoName = repo[4].slice(0, -4);

    // path: '/repos/mui-org/material-ui/pulls'
    var path = '/repos/' + repo[3]+ '/' + repoName + '/pulls';
    console.log("git without package")
  } else {
    exit('No package.json or .git/config found in any ancestor directory')
  }
}

// Process args that don't require the API, or setup those that do
switch(args[2]) {
  case 'help': case '--help': case '-h':
    exit(help);

  case 'version': case '--version': case '-v':
    exit('\n' + version);

  case 'list': case 'ls': case '-l':
    if (args[3] === '-r' || args[3] === 'remote' || args[3] === 'pr' || args[3] === 'pr') {
        break;
    }
    execho('git branch --list gpr/*');
    process.exit();

  case '-n': case 'named':
    if (args.length < 4) {
      exit(usage);
    }

    ref = args[3].split(':');

    if (ref.length !== 2) {
      exit(usage);
    }

    execho('git fetch ' + 'https://github.com/' + ref[0] + '/' + repoName + ' \'' + ref[1] + '\'');
    execho('git checkout FETCH_HEAD');
    process.exit();

  case '-p': case 'push':
    if (args.length < 4) {
      exit(usage);
    }

    ref = args[3].split(':');

    if (ref.length !== 2) {
      exit(usage);
    }

    execho('git push ' + 'https://github.com/' + ref[0] + '/' + repoName + ' \'' + 'HEAD:' + ref[1] + '\'');
    process.exit();

  case '-P': case 'Push':
    if (args.length < 4) {
      exit(usage);
    }

    ref = args[3].split(':');

    if (ref.length !== 2) {
      exit(usage);
    };

    execho('git push -f ' + 'https://github.com/' + ref[0] + '/' + repoName + ' \'' + 'HEAD:' + ref[1] + '\'');
    process.exit();

  default:
    var prNumber = args[args.length - 1];
    if (~~prNumber === 0) { exit(usage + '\n\n <pr> must be a number.'); }
    path += '/' + prNumber;
}

// https options
var options = {
  hostname: 'api.github.com',
  port: 443,
  path: path,
  headers: {
    'User-Agent': version
  },
};

// Read from the API
https.get(options, function(result) {
  var body = '';

  // Read the data
  result.on('data', function(chunk) {
    body += chunk;
  });

  // Parse the result
  result.on('end', function() {
    var response = JSON.parse(body);

    // If we're not getting the PR list [array], expect a response.head
    if (typeof response[0] === 'undefined') {
      if (typeof response.head === 'undefined') {
        if (typeof prNumber !== 'undefined') {
          exit('\n Couldn\'t find PR #' + prNumber);
        } else {
          exit('\n Couldn\'t read data.');
        }
      }

      if (response.head.repo == null) {
        exit('\n Couldn\'t find source repo. It may have been deleted.');
      }
      var remote = response.head.repo.clone_url + ' \'' + response.head.ref + '\'';
    }

    // Colors
    var reset = '\x1b[0m', red = '\x1b[31m#', green = '\x1b[32m', yellow = '\x1b[33m',
      blue = "\x1b[34m", magenta = "\x1b[35m", cyan = '\x1b[36m';

    function displayPr(pr) {
      // Color [bracketed] string
      pr.title = pr.title.replace('[', cyan + '[');
      pr.title = pr.title.replace(']', ']' + reset);
      console.log(red + pr.number + reset, pr.title, green + '(@' + pr.user.login + ')' + reset);
    };

    // Process args
    switch(args[2]) {
      case 'info': case '-i':
        console.log();
        displayPr(response);
        console.log();
        break;

      case 'list': case 'ls': case '-l':
        console.log();
        response.forEach( function(pr) {
          displayPr(pr);
        });
        console.log();
        break;

      case 'update': case 'pull': case '-u':
        execho('git pull ' + remote);
        break;

      case 'delete': case '-d':
        execho('git checkout master');
        execho('git branch -d gpr/' + prNumber + ' master');
        break;

      case 'Delete': case '-D':
        execho('git checkout master');
        execho('git branch -D gpr/' + prNumber);
        break;

      case 'branch': case '-b':
        if (args.length === 5) {
          var branch = args[3]
        } else {
          var branch = 'gpr/' + prNumber;
        }
        execho('git checkout -B ' + branch + ' master');
        execho('pull ' + remote);
        break;

      case 'force': case '-f':
        execho('git fetch -f ' + remote);
        execho('git checkout FETCH_HEAD');
        break;

      default:
        execho('git fetch ' + remote);
        execho('git checkout FETCH_HEAD');
    }
  });

}).on('error', function(error) {
  console.log("Error: ", error);
});
<commit_msg>Replace escaped single quotes with double quotes<commit_after>#!/usr/bin/env node
/**
 *`git pull` from the repo and branch that a PR originates from.
 * Copyright 2019 Matthew Brookes. License: MIT
 */

var https = require('https');
var execSync = require('child_process').execSync;
var fs = require('fs');

var version = 'git-pull-request 2.0.1';
var use = '\n ' + version + '\n\n gpr [-i | -l [-r] | -p | -f | -b [<name>] | -n | -d | -D | -v | -h] <pr#>';

var hint = ' By default, `gpr <pr#>` will fetch the remote branch for <pr#> and checkout on a detached HEAD.';

var usage = use + '\n\n' + hint + '\n\n gpr [-h | --help] for detailed usage.';
var help = use +

'\n\n [-i | info] <pr#>               Show the PR title and requestor for <pr#>.\n\
 [-l | ls | list] [-r | remote]  List local gpr branches. / List 30 most recent open PRs.\n\
\n\
 [-u | |update | pull] <pr#>     Pull the remote branch for <pr#> to the current branch.\n\
 [-f | force] <pr#>              Force overwrite the local branch and checkout on a detached HEAD.\n\
 [-b | branch] [<name>] <pr#>    Create new branch [name] from master and pull. Defaults to \'gpr/<pr#>\'.\n\
 [-n | named] <user:branch>      Fetch from the named ref and checkout on a detached HEAD.\n\
\n\
 [-p | push] <user:branch>       Push the current branch or detached HEAD to the remote branch.\n\
 [-P | Push] <<user:branch>      Force push the current branch or detached HEAD to the remote branch.\n\
\n\
 [-d | delete] <pr#>             Delete the gpr/<pr#> branch.\n\
 [-D | Delete] <pr#>             Force delete the gpr/<pr#> branch.\n\
\n\
 [-v | version]                  Show git-pull-request version.\n\
 [-h | help]                     This help.\n\
\n\
 <pr#>                           PR number to apply the command to.\n\n' + hint;

// Read the command-line args
var args = process.argv;

if (args.length < 3) {
  exit(usage);
}

// Exit with a message
function exit(error) {
  console.error(error,'\n');
  process.exit();
};

// Exec with echo
function execho(command) {
  console.log(command);
  try {
    console.log(execSync(command, {encoding: 'utf8'}));
  } catch (error) {
   console.error(error.output[1]);
  }
}

try {
  var npmPrefix = execSync('npm prefix', {cwd: process.cwd(), encoding: 'utf8'}).replace(/\s+/g, '');
} catch (error) {}

// Read the package.json and extract the repo name
if (fs.existsSync(npmPrefix + '/package.json')) {
  var packageFile = JSON.parse(fs.readFileSync(npmPrefix + '/package.json', 'utf8'));

  // repo: [ 'https:', '', 'github.com', 'mui-org', 'material-ui.git' ],
  var repo = packageFile.repository.url.split('/');

  // repoName: 'material-ui'
  var repoName = repo[4].slice(0, -4);

  // path: '/repos/mui-org/material-ui/pulls'
  var path = '/repos/' + repo[3]+ '/' + repoName + '/pulls';

  // If there's no package.json, try .git config upstream / origin
} else {
  try {
    var gitPrefix = execSync('git rev-parse --show-toplevel', {cwd: process.cwd(), encoding: 'utf8'}).replace(/\s+/g, '');
  } catch (error) {
    exit(error.output[1]);
  }

  if (fs.existsSync(gitPrefix + '/.git/config')) {
    var gitConfig = fs.readFileSync(gitPrefix + '/.git/config', 'utf8');

    // repo: [ 'https:', '', 'github.com', 'mui-org', 'material-ui.git' ],
    var repo = gitConfig.match(/\[remote "upstream"\][\r\n|\r|\n]\s*url\s=\s(.*)/);

    if (!repo) {
      repo = gitConfig.match(/\[remote "origin"\][\r\n|\r|\n]\s*url\s=\s(.*)/);
      if (!repo) {
        exit('No "upstream" or "origin" remote found in .git/config')
      }
    }
    repo = repo[1].split('/');

    // repoName: 'material-ui'
    var repoName = repo[4].slice(0, -4);

    // path: '/repos/mui-org/material-ui/pulls'
    var path = '/repos/' + repo[3]+ '/' + repoName + '/pulls';
    console.log("git without package")
  } else {
    exit('No package.json or .git/config found in any ancestor directory')
  }
}

// Process args that don't require the API, or setup those that do
switch(args[2]) {
  case 'help': case '--help': case '-h':
    exit(help);

  case 'version': case '--version': case '-v':
    exit('\n' + version);

  case 'list': case 'ls': case '-l':
    if (args[3] === '-r' || args[3] === 'remote' || args[3] === 'pr' || args[3] === 'pr') {
        break;
    }
    execho('git branch --list gpr/*');
    process.exit();

  case '-n': case 'named':
    if (args.length < 4) {
      exit(usage);
    }

    ref = args[3].split(':');

    if (ref.length !== 2) {
      exit(usage);
    }

    execho('git fetch ' + 'https://github.com/' + ref[0] + '/' + repoName + ' "' + ref[1] + '"');
    execho('git checkout FETCH_HEAD');
    process.exit();

  case '-p': case 'push':
    if (args.length < 4) {
      exit(usage);
    }

    ref = args[3].split(':');

    if (ref.length !== 2) {
      exit(usage);
    }

    execho('git push ' + 'https://github.com/' + ref[0] + '/' + repoName + ' "' + 'HEAD:' + ref[1] + '"');
    process.exit();

  case '-P': case 'Push':
    if (args.length < 4) {
      exit(usage);
    }

    ref = args[3].split(':');

    if (ref.length !== 2) {
      exit(usage);
    };

    execho('git push -f ' + 'https://github.com/' + ref[0] + '/' + repoName + ' "' + 'HEAD:' + ref[1] + '"');
    process.exit();

  default:
    var prNumber = args[args.length - 1];
    if (~~prNumber === 0) { exit(usage + '\n\n <pr> must be a number.'); }
    path += '/' + prNumber;
}

// https options
var options = {
  hostname: 'api.github.com',
  port: 443,
  path: path,
  headers: {
    'User-Agent': version
  },
};

// Read from the API
https.get(options, function(result) {
  var body = '';

  // Read the data
  result.on('data', function(chunk) {
    body += chunk;
  });

  // Parse the result
  result.on('end', function() {
    var response = JSON.parse(body);

    // If we're not getting the PR list [array], expect a response.head
    if (typeof response[0] === 'undefined') {
      if (typeof response.head === 'undefined') {
        if (typeof prNumber !== 'undefined') {
          exit('\n Couldn\'t find PR #' + prNumber);
        } else {
          exit('\n Couldn\'t read data.');
        }
      }

      if (response.head.repo == null) {
        exit('\n Couldn\'t find source repo. It may have been deleted.');
      }
      var remote = response.head.repo.clone_url + ' "' + response.head.ref + '"';
    }

    // Colors
    var reset = '\x1b[0m', red = '\x1b[31m#', green = '\x1b[32m', yellow = '\x1b[33m',
      blue = "\x1b[34m", magenta = "\x1b[35m", cyan = '\x1b[36m';

    function displayPr(pr) {
      // Color [bracketed] string
      pr.title = pr.title.replace('[', cyan + '[');
      pr.title = pr.title.replace(']', ']' + reset);
      console.log(red + pr.number + reset, pr.title, green + '(@' + pr.user.login + ')' + reset);
    };

    // Process args
    switch(args[2]) {
      case 'info': case '-i':
        console.log();
        displayPr(response);
        console.log();
        break;

      case 'list': case 'ls': case '-l':
        console.log();
        response.forEach( function(pr) {
          displayPr(pr);
        });
        console.log();
        break;

      case 'update': case 'pull': case '-u':
        execho('git pull ' + remote);
        break;

      case 'delete': case '-d':
        execho('git checkout master');
        execho('git branch -d gpr/' + prNumber + ' master');
        break;

      case 'Delete': case '-D':
        execho('git checkout master');
        execho('git branch -D gpr/' + prNumber);
        break;

      case 'branch': case '-b':
        if (args.length === 5) {
          var branch = args[3]
        } else {
          var branch = 'gpr/' + prNumber;
        }
        execho('git checkout -B ' + branch + ' master');
        execho('pull ' + remote);
        break;

      case 'force': case '-f':
        execho('git fetch -f ' + remote);
        execho('git checkout FETCH_HEAD');
        break;

      default:
        execho('git fetch ' + remote);
        execho('git checkout FETCH_HEAD');
    }
  });

}).on('error', function(error) {
  console.log("Error: ", error);
});
<|endoftext|>


<commit_before>/**
 * 匹配route
 * 两种匹配方法： 1、用filter得到全部匹配； 2、for循环得到一个匹配就终止；
 * 目前按第二种方式
 */
function getParam(pathInfo, paramKeys) {
  // 得到参数
  // https://github.com/expressjs/express/blob/master/lib/router/layer.js
  const param = {};

  for (let j = 1; j < pathInfo.length; j++) {
    const key = paramKeys[j - 1];
    const prop = key.name;
    const val = decodeURIComponent(pathInfo[j]);

    if (val !== 'undefined') {
      param[prop] = val;
    }
  }

  return param;
}

function match(pathname, routers) {
  for (let i = 0, l = routers.length, router, pathInfo; i < l; i++) {
    router = routers[i];
    pathInfo = router.pathRegx.exec(pathname);

    if (pathInfo) {
      const param = getParam(pathInfo, router.paramKeys);
      return { router, param };
    }
  }

  return {};
}

function matchRouter(req, res, next) {
  const pathname = req.pathname;
  const routers = req.app.get('routers');
  const { router, param = {} } = match(pathname, routers);

  req.param = param;

  // 未匹配到路由
  if (!router) {
    return next();
  }

  const method = req.method.toLowerCase();
  const supportRouter = router[method];

  if (!supportRouter) {
    throw new Error(`405 ${method} Method Not Allowed`);
  }

  req.router = supportRouter;
  // 合并参数
  Object.assign(req.query, param);
  // 若未使用body-parser，req.body为undefined
  if (req.body) {
    Object.assign(req.body, param);
  }

  return next();
}

module.exports = matchRouter;
<commit_msg>update 405 response<commit_after>/**
 * 匹配route
 * 两种匹配方法： 1、用filter得到全部匹配； 2、for循环得到一个匹配就终止；
 * 目前按第二种方式
 */
function getParam(pathInfo, paramKeys) {
  // 得到参数
  // https://github.com/expressjs/express/blob/master/lib/router/layer.js
  const param = {};

  for (let j = 1; j < pathInfo.length; j++) {
    const key = paramKeys[j - 1];
    const prop = key.name;
    const val = decodeURIComponent(pathInfo[j]);

    if (val !== 'undefined') {
      param[prop] = val;
    }
  }

  return param;
}

function match(pathname, routers) {
  for (let i = 0, l = routers.length, router, pathInfo; i < l; i++) {
    router = routers[i];
    pathInfo = router.pathRegx.exec(pathname);

    if (pathInfo) {
      const param = getParam(pathInfo, router.paramKeys);
      return { router, param };
    }
  }

  return {};
}

function matchRouter(req, res, next) {
  const pathname = req.pathname;
  const routers = req.app.get('routers');
  const { router, param = {} } = match(pathname, routers);

  req.param = param;

  // 未匹配到路由
  if (!router) {
    return next();
  }

  const method = req.method.toLowerCase();
  const supportRouter = router[method];

  if (!supportRouter) {
    return res.status(405).send(`405 ${method.toUpperCase()} Method Not Allowed`);
  }

  req.router = supportRouter;
  // 合并参数
  Object.assign(req.query, param);
  // 若未使用body-parser，req.body为undefined
  if (req.body) {
    Object.assign(req.body, param);
  }

  return next();
}

module.exports = matchRouter;
<|endoftext|>


<commit_before>op.Editor = {
	language : 'en',
	$ready : function() {
		hui.ui.tellContainers('pageLoaded',op.page.id);
		if (hui.location.hasHash('edit')) {
			if (templateController!==undefined) {
				templateController.edit();
			}
		}
	},
	getToolbarController : function() {
		try {
			return window.parent.controller;
		} catch (e) {
			hui.log('Unable to find toolbar controller');
		}
	},
	$partChanged : function() {
		this.signalChange();
	},
	signalChange : function() {
		hui.ui.tellContainers('pageChanged',op.page.id);
	},

	editProperties : function(language) {
		this.language = language;
		if (!this.propertiesWindow) {
			var originalLanguage = hui.ui.language;
			hui.ui.language = language;
			var win = this.propertiesWindow = hui.ui.Window.create({width:300,title:'Info',icon:'common/info',padding:10});
			var form = this.propertiesFormula = hui.ui.Formula.create();
			var group = form.buildGroup({above:true},[
				{type:'TextField',label:{en:'Title:',da:'Titel:'},options:{key:'title'}},
				{type:'TextField',label:{en:'Description:',da:'Beskrivelse:'},options:{key:'description',multiline:true}},
				{type:'TextField',label:{en:'Keywords:',da:'Nøgelord:'},options:{key:'keywords'}},
				{type:'TextField',label:{en:'Path:',da:'Sti:'},options:{key:'path'}},
				{type:'DropDown',label:{en:'Language:',da:'Sprog:'},options:{
					key : 'language',
					url : '../../Model/LanguageItems.php'
				}}
			]);
			var buttons = group.createButtons();
			var more = hui.ui.Button.create({text:{en:'More...',da:'Mere...'}});
			more.click(this.moreProperties.bind(this));
			buttons.add(more);

			var update = hui.ui.Button.create({text:{en:'Update',da:'Opdater'},highlighted:true});
			update.click(this.saveProperties.bind(this));
			buttons.add(update);
			win.add(form);
			hui.ui.language = originalLanguage;
		}
		hui.ui.request({
			url : 'data/LoadPageProperties.php',
			parameters : {id:op.page.id},
			message : {start:language=='da' ? 'Henter info...' : 'Loading info...',delay:300},
			onJSON : function(obj) {
				this.propertiesFormula.setValues(obj);
				this.propertiesWindow.show();
			}.bind(this)
		})
	},
	saveProperties : function() {
		var values = this.propertiesFormula.getValues();
		values.id = op.page.id;
		this.propertiesFormula.reset();
		this.propertiesWindow.hide();
		hui.ui.request({
			url : 'data/SavePageProperties.php',
			parameters : values,
			message : {start:this.language=='da' ? 'Gemmer info...' : 'Saving info...',delay:300},
			onSuccess : function() {
				hui.ui.showMessage({text:this.language=='da' ? 'Informationen er gemt' : 'The information is saved',icon:'common/success',duration:2000});
			}.bind(this)
		});
	},
	moreProperties : function() {
		if (!window.parent) {
			hui.log('The window has no parent! '+window.location);
			return;
		}
		window.parent.location='../../../Tools/Sites/?pageInfo='+op.page.id;
	},

	editDesign : function() {
		if (!this.designWindow) {
			hui.ui.request({
				url : 'data/LoadDesignInfo.php',
				parameters : {id:op.page.id},
				message : {start:'Henter design info...',delay:300},
				onJSON : function(parameters) {
					if (parameters.length>0) {
						this._buildDesignForm(parameters);
						this.designWindow.show();
					} else {
						hui.ui.showMessage({text:'Dette design har ingen indstillinger',duration:3000})
					}
				}.bind(this)
			})
		} else {
			this.designWindow.show();
		}
	},

	_buildDesignForm : function(parameters) {
		var win = this.designWindow = hui.ui.Window.create({width:300,title:'Design',icon:'common/info',padding:10});
		var form = this.designFormula = hui.ui.Formula.create();
		form.listen({
			$submit : function() {
				var values = form.getValues();
				hui.ui.request({
					url : 'data/SaveDesignParameters.php',
					parameters : {id:op.page.id,parameters:hui.string.toJSON(values)},
					onSuccess : function() {
						hui.ui.showMessage({text:'Indstillingerne er gemt', duration:3000});
						document.location.reload();
					}
				})
			}
		})
		this.designGroup = this.designFormula.createGroup();

		var group = this.designFormula.createGroup();
		var buttons = group.createButtons();
		var btn = hui.ui.Button.create({text:'Opdater',submit:true});
		buttons.add(btn);

		win.add(form);

		for (var i=0; i < parameters.length; i++) {
			var parm = parameters[i];
			if (parm.type=='text' || parm.type=='color') {
				var field = hui.ui.TextField.create({key:parm.key,label:parm.label,value:parm.value});
				this.designGroup.add(field);
			}
			if (parm.type=='selection') {
				parm.options.unshift({});
				var field = hui.ui.DropDown.create({key:parm.key,label:parm.label,value:parm.value,items:parm.options});
				this.designGroup.add(field);
			}
			if (parm.type=='image') {
				var field = hui.ui.DropDown.create({key:parm.key,label:parm.label,value:parm.value,url:'../../Model/Items.php?type=image&includeEmpty=true'});
				this.designGroup.add(field);
			}
		};
	}
}

hui.ui.listen(op.Editor);<commit_msg>Better color design settings<commit_after>op.Editor = {
	language : 'en',
	$ready : function() {
		hui.ui.tellContainers('pageLoaded',op.page.id);
		if (hui.location.hasHash('edit')) {
			if (templateController!==undefined) {
				templateController.edit();
			}
		}
	},
	getToolbarController : function() {
		try {
			return window.parent.controller;
		} catch (e) {
			hui.log('Unable to find toolbar controller');
		}
	},
	$partChanged : function() {
		this.signalChange();
	},
	signalChange : function() {
		hui.ui.tellContainers('pageChanged',op.page.id);
	},

	editProperties : function(language) {
		this.language = language;
		if (!this.propertiesWindow) {
			var originalLanguage = hui.ui.language;
			hui.ui.language = language;
			var win = this.propertiesWindow = hui.ui.Window.create({width:300,title:'Info',icon:'common/info',padding:10});
			var form = this.propertiesFormula = hui.ui.Formula.create();
			var group = form.buildGroup({above:true},[
				{type:'TextField',label:{en:'Title:',da:'Titel:'},options:{key:'title'}},
				{type:'TextField',label:{en:'Description:',da:'Beskrivelse:'},options:{key:'description',multiline:true}},
				{type:'TextField',label:{en:'Keywords:',da:'Nøgelord:'},options:{key:'keywords'}},
				{type:'TextField',label:{en:'Path:',da:'Sti:'},options:{key:'path'}},
				{type:'DropDown',label:{en:'Language:',da:'Sprog:'},options:{
					key : 'language',
					url : '../../Model/LanguageItems.php'
				}}
			]);
			var buttons = group.createButtons();
			var more = hui.ui.Button.create({text:{en:'More...',da:'Mere...'}});
			more.click(this.moreProperties.bind(this));
			buttons.add(more);

			var update = hui.ui.Button.create({text:{en:'Update',da:'Opdater'},highlighted:true});
			update.click(this.saveProperties.bind(this));
			buttons.add(update);
			win.add(form);
			hui.ui.language = originalLanguage;
		}
		hui.ui.request({
			url : 'data/LoadPageProperties.php',
			parameters : {id:op.page.id},
			message : {start:language=='da' ? 'Henter info...' : 'Loading info...',delay:300},
			onJSON : function(obj) {
				this.propertiesFormula.setValues(obj);
				this.propertiesWindow.show();
			}.bind(this)
		})
	},
	saveProperties : function() {
		var values = this.propertiesFormula.getValues();
		values.id = op.page.id;
		this.propertiesFormula.reset();
		this.propertiesWindow.hide();
		hui.ui.request({
			url : 'data/SavePageProperties.php',
			parameters : values,
			message : {start:this.language=='da' ? 'Gemmer info...' : 'Saving info...',delay:300},
			onSuccess : function() {
				hui.ui.showMessage({text:this.language=='da' ? 'Informationen er gemt' : 'The information is saved',icon:'common/success',duration:2000});
			}.bind(this)
		});
	},
	moreProperties : function() {
		if (!window.parent) {
			hui.log('The window has no parent! '+window.location);
			return;
		}
		window.parent.location='../../../Tools/Sites/?pageInfo='+op.page.id;
	},

	editDesign : function() {
		if (!this.designWindow) {
			hui.ui.request({
				url : 'data/LoadDesignInfo.php',
				parameters : {id:op.page.id},
				message : {start:'Henter design info...',delay:300},
				onJSON : function(parameters) {
					if (parameters.length>0) {
						this._buildDesignForm(parameters);
						this.designWindow.show();
					} else {
						hui.ui.showMessage({text:'Dette design har ingen indstillinger',duration:3000})
					}
				}.bind(this)
			})
		} else {
			this.designWindow.show();
		}
	},

	_buildDesignForm : function(parameters) {
		var win = this.designWindow = hui.ui.Window.create({width:300,title:'Design',icon:'common/info',padding:10});
		var form = this.designFormula = hui.ui.Formula.create();
		form.listen({
			$submit : function() {
				var values = form.getValues();
				hui.ui.request({
					url : 'data/SaveDesignParameters.php',
					parameters : {id:op.page.id,parameters:hui.string.toJSON(values)},
					onSuccess : function() {
						hui.ui.showMessage({text:'Indstillingerne er gemt', duration:3000});
						document.location.reload();
					}
				})
			}
		})
		this.designGroup = this.designFormula.createGroup();

		var group = this.designFormula.createGroup();
		var buttons = group.createButtons();
		var btn = hui.ui.Button.create({text:'Opdater',submit:true});
		buttons.add(btn);

		win.add(form);

		for (var i=0; i < parameters.length; i++) {
			var parm = parameters[i];
			if (parm.type=='text') {
				var field = hui.ui.TextField.create({key:parm.key,label:parm.label,value:parm.value});
				this.designGroup.add(field);
			}
			else if (parm.type=='color') {
				var field = hui.ui.ColorInput.create({key:parm.key,value:parm.value});
				this.designGroup.add(field,parm.label);
            }
			else if (parm.type=='selection') {
				parm.options.unshift({});
				var field = hui.ui.DropDown.create({key:parm.key,label:parm.label,value:parm.value,items:parm.options});
				this.designGroup.add(field);
			}
			else if (parm.type=='image') {
				var field = hui.ui.DropDown.create({
                    key : parm.key,
                    label : parm.label,
                    value : parm.value,
                    url : '../../Model/Items.php?type=image&includeEmpty=true'
                });
				this.designGroup.add(field);
			}
		};
	}
}

hui.ui.listen(op.Editor);<|endoftext|>


<commit_before>'use strict';

var promisify = require('./promisify');

function promisifyAll(object, promisifiedObject) {
    var k;

    promisifiedObject = promisifiedObject || {};

    for (k in object) {
        if (typeof object[k] === 'function') {
            promisifiedObject[k] = promisify(object[k], object);

            if (Object.keys(object[k]).length) {
                promisifiedObject[k] = promisifyAll(object[k], promisifiedObject[k]);
            }
        }
    }

    return promisifiedObject;
}

/*
 * Promisifies all the enumerable own functions of an object,
 * returning a new object, or assigning methods to the `targetObject`.
 */
module.exports = promisifyAll;
<commit_msg>update promise/promisfyAll — lint, es6<commit_after>'use strict'

var promisify = require('./promisify')

function promisifyAll (object, promisifiedObject) {
  var k

  promisifiedObject = promisifiedObject || {}

  for (k in object) {
    if (typeof object[k] === 'function') {
      promisifiedObject[k] = promisify(object[k], object)

      if (Object.keys(object[k]).length) {
        promisifiedObject[k] = promisifyAll(object[k], promisifiedObject[k])
      }
    }
  }

  return promisifiedObject
}

/*
  Promisifies all the enumerable own functions of an object,
  returning a new object, or assigning methods to the `targetObject`.

*/

module.exports = promisifyAll
<|endoftext|>


<commit_before>/**
 * @class Ext.ux.grid.column.ActionButtonColumn
 * @extends Ext.grid.column.Column
 * @version 0.2
 * @author Lucian Lature (lucian.lature@gmail.com)

 *
A Grid header type which renders a button, or a series of buttons in a grid cell, and offers a scoped click
 * handler for each button.

 *
 * {@img Ext.ux.grid.column.ActionButtonColumn/Ext.ux.grid.column.ActionButtonColumn.png Ext.ux.grid.column.ActionButtonColumn grid column}
 *
 * ## Code
 *     Ext.create('Ext.data.Store', {
 *         storeId:'employeeStore',
 *         fields:['firstname', 'lastname', 'senority', 'dep', 'hired', 'iconEdit', 'iconFire', 'hideEdit', 'hideFire'],
 *         data:[
 *             {firstname:"Michael", lastname:"Scott", hideEdit: true, iconFire: 'fire2'},
 *             {firstname:"Dwight", lastname:"Schrute"},
 *             {firstname:"Jim", lastname:"Halpert", hideFire: true, iconEdit: 'edit2'},
 *             {firstname:"Kevin", lastname:"Malone"},
 *             {firstname:"Angela", lastname:"Martin"}
 *         ]
 *     });
 *
 *     Ext.create('Ext.grid.Panel', {
 *         title: 'Action Button Column Demo',
 *         store: Ext.data.StoreManager.lookup('employeeStore'),
 *         columns: [
 *             {text: 'First Name',  dataIndex:'firstname'},
 *             {text: 'Last Name',  dataIndex:'lastname'},
 *             {
 *                 xtype:'actionbuttoncolumn',
 *                 width:200,
 *                 header: 'Actions',
 *                 items: [{
 *                     text: 'Edit',
 *                     iconIndex: 'iconFire',
 *                     handler: function(grid, rowIndex, colIndex) {
 *                         var rec = grid.getStore().getAt(rowIndex);
 *                         alert("Edit " + rec.get('firstname'));
 *                     }
 *                 },{
 *                     text: 'Fire',
 *                     hideIndex: 'hideEdit',
 *                     handler: function(grid, rowIndex, colIndex) {
 *                         var rec = grid.getStore().getAt(rowIndex);
 *                         alert("Fire " + rec.get('firstname'));
 *                     }
 *                 }]
 *             }
 *         ],
 *         width: 450,
 *         renderTo: Ext.getBody()
 *     });
 *
The action button column can be at any index in the columns array, and a grid can have any number of
 * action columns.

 * @xtype actionbuttoncolumn
 */
Ext.define('Ext.ux.grid.column.ActionButtonColumn', {

	extend: 'Ext.grid.column.Column',
    alias: ['widget.actionbuttoncolumn'],
    alternateClassName: 'Ext.grid.ActionButtonColumn',

    /**
     * @cfg {Function} handler A function called when the button is clicked.
     * The handler is passed the following parameters:

     *
view : TableView
The owning TableView.

     *
rowIndex : Number
The row index clicked on.

     *
colIndex : Number
The column index clicked on.

     *

     */

    /**
     * @cfg {Array} items An Array which may contain multiple button definitions, each element of which may contain:
     *

     *
text : String
The button text to be used as innerHTML (html tags are accepted).

     *
iconIndex : String
Optional, however either iconIndex or iconCls must be configured. Field name of the field of the grid store record that contains css class of the button to show. If configured, shown icons can vary depending of the value of this field.

     *
hideIndex : String
Optional. Field name of the field of the grid store record that contains hide flag (falsie [null, '', 0, false, undefined] to show, anything else to hide).

     *
handler : Function
A function called when the button is clicked.

     *

     */
    header: ' ',

    sortable: false,
    btns: [],
    constructor: function(config) {

        var me = this,
            cfg = Ext.apply({}, config),
            items = cfg.items || [me],
            l = items.length,
            i,
            item;

        // This is a Container. Delete the items config to be reinstated after construction.
        delete cfg.items;
        me.callParent([cfg]);

        // Items is an array property of ActionButtonColumns
        me.items = items;

        //btns is a list of buttons generated by this column type so that we can clean up after ourselves
        me.btns = new Ext.util.MixedCollection();

		// Renderer closure iterates through items creating a button element for each and tagging with an identifying
        me.renderer = function(v, meta, rec, rowIndex, colIndex, store, view) {

			//  Allow a configured renderer to create initial value (And set the other values in the "metadata" argument!)
            v = Ext.isFunction(cfg.renderer) ? cfg.renderer.apply(this, arguments)||'' : '';

            meta.tdCls += ' ' + Ext.baseCSSPrefix + 'action-col-cell';

            for (i = 0; i < l; i++) {

                item = items[i];

                var nid = Ext.id();
                var cls = Ext.baseCSSPrefix + 'action-col-button ' + Ext.baseCSSPrefix + 'action-col-button-' + String(i)+(item.cls ? ' '+item.cls : '');
				var iconCls = item.iconIndex ? rec.data[item.iconIndex] : (item.iconCls ? item.iconCls : '');
				var fun = Ext.bind(item.handler, me, [view, rowIndex, colIndex]);
				var hide = rec.data[item.hideIndex];
                Ext.Function.defer(me.createGridButton, 100, me, [item.text, nid, rec, cls, fun, hide, iconCls]);

                v += '

';
            }
            return v;
        };
    },

    createGridButton: function(value, id, record, cls, fn, hide, iconCls) {
         var btn = new Ext.Button({
            text: value,
            cls: cls,
            iconCls: iconCls,
            hidden: hide,
	    handler: fn
        }).render(Ext.getBody(), id);
        this.btns.add(btn);
        Ext.get(id).remove();
    },

    destroy: function() {
        delete this.items;
        delete this.renderer;
        this.btns.each(function(btn){
           btn.destroy();
        });
        return this.callParent(arguments);
    },

    cascade: function(fn, scope) {
        fn.call(scope||this, this);
    },

    // Private override because this cannot function as a Container, and it has an items property which is an Array, NOT a MixedCollection.
    getRefItems: function() {
        return [];
    }
});<commit_msg>enable context switching for the handler. also enabled the ability to not have a handler passed without issue.<commit_after>/**
 * @class Ext.ux.grid.column.ActionButtonColumn
 * @extends Ext.grid.column.Column
 * @version 0.2
 * @author Lucian Lature (lucian.lature@gmail.com)

 *
A Grid header type which renders a button, or a series of buttons in a grid cell, and offers a scoped click
 * handler for each button.

 *
 * {@img Ext.ux.grid.column.ActionButtonColumn/Ext.ux.grid.column.ActionButtonColumn.png Ext.ux.grid.column.ActionButtonColumn grid column}
 *
 * ## Code
 *     Ext.create('Ext.data.Store', {
 *         storeId:'employeeStore',
 *         fields:['firstname', 'lastname', 'senority', 'dep', 'hired'],
 *         data:[
 *             {firstname:"Michael", lastname:"Scott", hideEdit: true, iconFire: 'fire2'},
 *             {firstname:"Dwight", lastname:"Schrute"},
 *             {firstname:"Jim", lastname:"Halpert", hideFire: true, iconEdit: 'edit2'},
 *             {firstname:"Kevin", lastname:"Malone"},
 *             {firstname:"Angela", lastname:"Martin"}
 *         ]
 *     });
 *
 *     Ext.create('Ext.grid.Panel', {
 *         title: 'Action Button Column Demo',
 *         store: Ext.data.StoreManager.lookup('employeeStore'),
 *         columns: [
 *             {text: 'First Name',  dataIndex:'firstname'},
 *             {text: 'Last Name',  dataIndex:'lastname'},
 *             {
 *                 xtype:'actionbuttoncolumn',
 *                 width:200,
 *                 header: 'Actions',
 *                 items: [{
 *                     text: 'Edit',
 *                     iconIndex: 'iconFire',
 *                     handler: function(grid, rowIndex, colIndex) {
 *                         var rec = grid.getStore().getAt(rowIndex);
 *                         alert("Edit " + rec.get('firstname'));
 *                     }
 *                 },{
 *                     text: 'Fire',
 *                     hideIndex: 'hideEdit',
 *                     handler: function(grid, rowIndex, colIndex) {
 *                         var rec = grid.getStore().getAt(rowIndex);
 *                         alert("Fire " + rec.get('firstname'));
 *                     }
 *                 }]
 *             }
 *         ],
 *         width: 450,
 *         renderTo: Ext.getBody()
 *     });
 *
The action button column can be at any index in the columns array, and a grid can have any number of
 * action columns.

 * @xtype actionbuttoncolumn
 */
Ext.define('Ext.ux.grid.column.ActionButtonColumn', {

    extend: 'Ext.grid.column.Column',
    alias: ['widget.actionbuttoncolumn'],
    alternateClassName: 'Ext.grid.ActionButtonColumn',

    /**
     * @cfg {Function} handler A function called when the button is clicked.
     * The handler is passed the following parameters:

     *
view : TableView
The owning TableView.

     *
rowIndex : Number
The row index clicked on.

     *
colIndex : Number
The column index clicked on.

     *

     */

    /**
     * @cfg {Array} items An Array which may contain multiple button definitions, each element of which may contain:
     *

     *
text : String
The button text to be used as innerHTML (html tags are accepted).

     *
iconIndex : String
Optional, however either iconIndex or iconCls must be configured. Field name of the field of the grid store record that contains css class of the button to show. If configured, shown icons can vary depending of the value of this field.

     *
hideIndex : String
Optional. Field name of the field of the grid store record that contains hide flag (falsie [null, '', 0, false, undefined] to show, anything else to hide).

     *
handler : Function
A function called when the button is clicked.

     *

     */
    header: ' ',

    sortable: false,
    btns: [],
    constructor: function(config) {

        var me = this,
            cfg = Ext.apply({}, config),
            items = cfg.items || [me],
            l = items.length,
            i,
            item;
            me.btns = new Ext.util.MixedCollection();
        // This is a Container. Delete the items config to be reinstated after construction.
        delete cfg.items;
        me.callParent([cfg]);

        // Items is an array property of ActionButtonColumns
        me.items = items;

        // Renderer closure iterates through items creating a button element for each and tagging with an identifying
        me.renderer = function(v, meta, rec, rowIndex, colIndex, store, view) {

            //  Allow a configured renderer to create initial value (And set the other values in the "metadata" argument!)
            v = Ext.isFunction(cfg.renderer) ? cfg.renderer.apply(this, arguments)||'' : '';

            meta.tdCls += ' ' + Ext.baseCSSPrefix + 'action-col-cell';

            for (i = 0; i < l; i++) {

                item = items[i];

                var nid = Ext.id();
                var cls = Ext.baseCSSPrefix + 'action-col-button ' + Ext.baseCSSPrefix + 'action-col-button-' + String(i)+(item.cls ? ' '+item.cls : '');
                var iconCls = item.iconIndex ? rec.data[item.iconIndex] : (item.iconCls ? item.iconCls : '');
                var fun = Ext.emptyFn;
                if (item.handler) {
                    var context = me;
                    if (item.context) {
                        context = item.context;
                    }
                    var fun = Ext.bind(item.handler, context, [view, rowIndex, colIndex]);
                }
                var hide = rec.data[item.hideIndex];

                Ext.Function.defer(me.createGridButton, 100, me, [item.text, nid, rec, cls, fun, hide, iconCls]);

                v += '

';
            }
            return v;
        };
    },

    createGridButton: function(value, id, record, cls, fn, hide, iconCls) {
        var btn = new Ext.Button({
            text: value,
            cls: cls,
            iconCls: iconCls,
            hidden: hide,
            handler: fn
        }).render(Ext.getBody(), id);
        this.btns.add(btn);
        Ext.get(id).remove();
    },

    destroy: function() {
        delete this.items;
        delete this.renderer;
        this.btns.each(function(btn){
           btn.destroy();
        });
        return this.callParent(arguments);
    },

    cascade: function(fn, scope) {
        fn.call(scope||this, this);
    },

    // Private override because this cannot function as a Container, and it has an items property which is an Array,
    // NOT a MixedCollection.
    getRefItems: function() {
        return [];
    }
});<|endoftext|>


<commit_before>
function filterMachines(f) {
	$('.machines-buttons .quick-button').removeClass('active');
	$('.machines-buttons .btn-'+f).addClass('active');
	if (f === 'all') f = '*';
	else f = '.'+f;
	$('#machines-loader').isotope( { filter: f } );
}

var cloudlyVMSmanager  = {
    template: '',
    actualMachines: '',
    colors : {
		'#36a9e1':'lightBlue',
		'#78cd51':'green',
		'#333366':'darkGreen',
		'#eae874':'yellow',
		'#fa603d':'lightOrange',
		'#ff5454':'red',
		'#CBD4E4':'silver',
		'#e84c8a':'pink',
		'#000000':'black'
		},
    initAction: function(){
        var $this = this;
        $('#machines-loader').isotope({
            itemSelector: '.vms-machine'
        });
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/box-template/',
            data: '',
            success: function(res){
                $this.template = res;
                setInterval(function(){
                    $this.loadMachinesData();
                },1000);
            }
        });
    },
    loadMachinesData: function(){
        var actualMachines = $(".vms-machine");

        var $this = this;
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/vms/',
            data: '',
            success: function(res){
                var jsonData = $.parseJSON(res);
                $this.checkRemoved(jsonData,actualMachines);
                $this.parseMachinesData(jsonData);

            }
        });
    },
    parseMachinesData: function(jsonData){
        var $this = this;
        if(jsonData){
            $.each(jsonData,function(vms,data){
                //exist VMS
                if($('#'+vms).length){
                    $this.updateVMS(vms,data);
                }
                else {
                    $this.addVMS(vms,data);
                }
            });
        }
    },
    updateVMS: function(vms,data){
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        $('#'+vms).find('.value').html(data.state);

        var panel = $("#"+vms).find('.panel');
        $.each(this.colors,function(code,color){
                if(panel.hasClass(color) && panel.attr('class').indexOf(data.vmcolor) === -1){

                        $(panel).switchClass(color,data.vmcolor);
                        console.log('VM '+vms+' changed color: '+color+' to: '+data.vmcolor+' and actual has class: '+panel.attr('class'));
                        return;
                }
        });

    },
    addVMS: function(vms,data){
        var template = this.template;
        template = template.replace('{@vmlink@}',data.link);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vmtitle@}',data.vmtitle);
        template = template.replace('{@vmcolor@}',data.vmcolor);
        template = template.replace('{@averge@}',data.averge);
        template = template.replace("{@state@}", data.state);

        template = $(template);
        console.log(template);
        var prepend = $('#machines-loader').prepend(template);
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        prepend.isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });

    },
    checkRemoved: function(machines,actualMachines){
        var machineIds = 'testVMS';
	var $container = $('#machines-loader');
        $.each(machines,function(vms,value){
            machineIds += vms+',';
        });

        $.each(actualMachines,function(index,item){
            var id = $(item).attr('id');
            if(machineIds.indexOf(id) < 0){
                $container.isotope( 'remove', item ).isotope('layout');
            }
        });

    },
    reloadPositions: function(){
            $('#machines-loader').isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });
    },
    addBlank: function(){
        this.addVMS('testVMS',{"averge":"0.0,0.0,0.0,0.0","state":"Running"});

    }
}

$(document).ready (function() {

	var btns = ['all','critical','offline', 'suspended', 'windows', 'linux', 'bsd', 'private'];
	for (var i = 0; i < btns.length; ++i) {
	    (function(){
		var type = btns[i];
		var btn = $('.machines-buttons .btn-'+type);
		btn.click(function() { filterMachines(type); });
	    })();
	}

        cloudlyVMSmanager.initAction();

});

<commit_msg>added on debugging onto the dashboard.js<commit_after>
function filterMachines(f) {
	$('.machines-buttons .quick-button').removeClass('active');
	$('.machines-buttons .btn-'+f).addClass('active');
	if (f === 'all') f = '*';
	else f = '.'+f;
	$('#machines-loader').isotope( { filter: f } );
}

var cloudlyVMSmanager  = {
    template: '',
    actualMachines: '',
    colors : {
		'#36a9e1':'lightBlue',
		'#78cd51':'green',
		'#333366':'darkGreen',
		'#eae874':'yellow',
		'#fa603d':'lightOrange',
		'#ff5454':'red',
		'#CBD4E4':'silver',
		'#e84c8a':'pink',
		'#000000':'black'
		},
    initAction: function(){
        var $this = this;
        $('#machines-loader').isotope({
            itemSelector: '.vms-machine'
        });
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/box-template/',
            data: '',
            success: function(res){
                $this.template = res;
                setInterval(function(){
                    $this.loadMachinesData();
                },1000);
            }
        });
    },
    loadMachinesData: function(){
        var actualMachines = $(".vms-machine");

        var $this = this;
        $.ajax({
            type: 'GET',
            url: '/ajax/cloud/vms/',
            data: '',
            success: function(res){
                var jsonData = $.parseJSON(res);
                $this.checkRemoved(jsonData,actualMachines);
                $this.parseMachinesData(jsonData);

            }
        });
    },
    parseMachinesData: function(jsonData){
        var $this = this;
        if(jsonData){
            $.each(jsonData,function(vms,data){
                //exist VMS
                if($('#'+vms).length){
                    $this.updateVMS(vms,data);
                }
                else {
                    $this.addVMS(vms,data);
                }
            });
        }
    },
    updateVMS: function(vms,data){
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        $('#'+vms).find('.value').html(data.state);

        var panel = $("#"+vms).find('.panel');
        $.each(this.colors,function(code,color){
                if(panel.hasClass(color) && panel.attr('class').indexOf(data.vmcolor) === -1){

                        $(panel).switchClass(color,data.vmcolor);
                        console.log('VM '+vms+' changed color: '+color+' to: '+data.vmcolor+' and actual has class: '+panel.attr('class'));
                        return;
                }
                console.log('here color:', data.vmcolor)
        });

    },
    addVMS: function(vms,data){
        var template = this.template;
        template = template.replace('{@vmlink@}',data.link);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vm@}',vms);
        template = template.replace('{@vmtitle@}',data.vmtitle);
        template = template.replace('{@vmcolor@}',data.vmcolor);
        template = template.replace('{@averge@}',data.averge);
        template = template.replace("{@state@}", data.state);

        template = $(template);
        console.log(template);
        var prepend = $('#machines-loader').prepend(template);
        chartStatElement($('#'+vms).find('.chart').html(data.averge));
        prepend.isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });

    },
    checkRemoved: function(machines,actualMachines){
        var machineIds = 'testVMS';
	var $container = $('#machines-loader');
        $.each(machines,function(vms,value){
            machineIds += vms+',';
        });

        $.each(actualMachines,function(index,item){
            var id = $(item).attr('id');
            if(machineIds.indexOf(id) < 0){
                $container.isotope( 'remove', item ).isotope('layout');
            }
        });

    },
    reloadPositions: function(){
            $('#machines-loader').isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });
    },
    addBlank: function(){
        this.addVMS('testVMS',{"averge":"0.0,0.0,0.0,0.0","state":"Running"});

    }
}

$(document).ready (function() {

	var btns = ['all','critical','offline', 'suspended', 'windows', 'linux', 'bsd', 'private'];
	for (var i = 0; i < btns.length; ++i) {
	    (function(){
		var type = btns[i];
		var btn = $('.machines-buttons .btn-'+type);
		btn.click(function() { filterMachines(type); });
	    })();
	}

        cloudlyVMSmanager.initAction();

});

<|endoftext|>


<commit_before>/* For the automatic client
 * This allows any person to create his
 * own chat on your server.
 */
 /****
h = document.location.hostname;
h = h.split('.');
c = h[0]; //->"IP-PORT"
c = c.split('-');
SERVER = c[0];
PORT = c[1];
****/
/*
 * If you want to install your own client,
 * please uncomment this part and remove all lines
 * beyond
 *-------------------.*/
PORT = '8000';
SERVER = 'localhost';

var socket = io.connect('http://'+SERVER+':'+PORT);

/*
 * Scrolling to the bottom every posts
 */
function scrollBottom()
  {
    var objDiv = document.getElementById("tchat");
    objDiv.scrollTop = objDiv.scrollHeight;
  }
  //setInterval(scrollBottom, 10)
/*
 * Escaping a string, basically...
 */
function htmlEscape(text) {
     return text.replace(/&/g, '&').
     replace(/</g, '<').
     replace(/"/g, '"').
     replace(/'/g, ''');
}

/*
 * Asking username
 */

function askLogin(){
    $('#modal1').trigger('openModal');
  }

function askRegister(){
    $('#modal2').trigger('openModal');
  }

function dismissRegister(){
  pseudo = $('#usernameregister').val();
  pw = $('#passwordregister').val();
  pwcheck = $('#passwordcheck').val();
  if(pw == pwcheck){
    socket.emit('newPost', {'message': '/register '+pseudo+' '+pw})
  }else{
    document.getElementById('tchat').innerHTML += '
Entered passwords are not the same.
';
  }
  $('#modal2').trigger('closeModal');
  return false;
  return pseudo;
}

function dismissLogin(){
  var nb = Math.floor(Math.random() * 1000);
  pseudo = $('#usernamelogin').val() || "Guest" + nb;
  pw = $('#passwordlogin').val();
  console.log(pseudo);
  socket.emit('newPost', {'message': '/login '+pseudo+' '+pw});
  $('#modal1').trigger('closeModal');
  return false;
  return pseudo;
}

/*
 * To send a message to the server
 * after sumitting the form with "enter"
 */
function sendMessage(mess) {
          var message = document.getElementById('message').value;
          var message = htmlEscape(message);
          socket.emit('newPost', { 'hour' : '', 'pseudo' : pseudo, password: pw, 'message' : message, rank: 5});
          scrollBottom();
          $('#message').val('');
          return false;
    }

<commit_msg>Update functions.js<commit_after>/* For the automatic client
 * This allows any person to create his
 * own chat on your server.
 */

h = document.location.hostname;
h = h.split('.');
c = h[0]; //->"IP-PORT"
c = c.split('-');
SERVER = c[0];
PORT = c[1];

/*
 * If you want to install your own client,
 * please uncomment this part and remove all lines
 * beyond
 *
PORT = '8000';
SERVER = 'localhost';
*/
var socket = io.connect('http://'+SERVER+':'+PORT);

/*
 * Scrolling to the bottom every posts
 */
function scrollBottom()
  {
    var objDiv = document.getElementById("tchat");
    objDiv.scrollTop = objDiv.scrollHeight;
  }
  //setInterval(scrollBottom, 10)
/*
 * Escaping a string, basically...
 */
function htmlEscape(text) {
     return text.replace(/&/g, '&').
     replace(/</g, '<').
     replace(/"/g, '"').
     replace(/'/g, ''');
}

/*
 * Asking username
 */

function askLogin(){
    $('#modal1').trigger('openModal');
  }

function askRegister(){
    $('#modal2').trigger('openModal');
  }

function dismissRegister(){
  pseudo = $('#usernameregister').val();
  pw = $('#passwordregister').val();
  pwcheck = $('#passwordcheck').val();
  if(pw == pwcheck){
    socket.emit('newPost', {'message': '/register '+pseudo+' '+pw})
  }else{
    document.getElementById('tchat').innerHTML += '
Entered passwords are not the same.
';
  }
  $('#modal2').trigger('closeModal');
  return false;
  return pseudo;
}

function dismissLogin(){
  var nb = Math.floor(Math.random() * 1000);
  pseudo = $('#usernamelogin').val() || "Guest" + nb;
  pw = $('#passwordlogin').val();
  console.log(pseudo);
  socket.emit('newPost', {'message': '/login '+pseudo+' '+pw});
  $('#modal1').trigger('closeModal');
  return false;
  return pseudo;
}

/*
 * To send a message to the server
 * after sumitting the form with "enter"
 */
function sendMessage(mess) {
          var message = document.getElementById('message').value;
          var message = htmlEscape(message);
          socket.emit('newPost', { 'hour' : '', 'pseudo' : pseudo, password: pw, 'message' : message, rank: 5});
          scrollBottom();
          $('#message').val('');
          return false;
    }

<|endoftext|>


<commit_before>var navigationTests = {
  'Location': [
    function(contentWindow) {
      logPhase('assign location');
      contentWindow.location = '/blank.html';
    },
    'back',
    'forward',
    'back',
    function(contentWindow) {
      logPhase('replace location');
      contentWindow.location.replace('/blank.html');
    }
  ],
  'Hash': [
    function(contentWindow) {
      logPhase('assign hash');
      contentWindow.location = contentWindow.location + '#foo';
    },
    'back',
    'forward',
    'back',
    function(contentWindow) {
      logPhase('replace location');
      contentWindow.location.replace(contentWindow.location + '#bar');
    }
  ],
  'Push State': [
    function(contentWindow) {
      logPhase('pushState');
      contentWindow.history.pushState(undefined, 'foo', 'foo');
    },
    'back',
    'forward',
    'back',
    function(contentWindow) {
      logPhase('replaceState');
      contentWindow.history.replaceState(undefined, 'foo', 'foo');
    }
  ],
  'Form Submission': [
    function(contentWindow) {
      logPhase('submit form');
      var form = contentWindow.document.createElement('form');
      form.action = '/blank.html';
      form.submit();
    },
    'back',
    'forward'
  ],
  'Page Refresh': [
    function(contentWindow) {
      logPhase('reload');
      contentWindow.location.reload();
    }
  ]
};

// Defer do the page is loaded as some of these operations behave differently
// if run while the page is still loading.
setTimeout(function testStep() {
  var running = localStorage.getItem('test-running') === 'true';
  if (running) {
    var suite = navigationTests[localStorage.getItem('test-name')],
        step = parseInt(localStorage.getItem('test-step'), 10);

    localStorage.setItem('test-step', step + 1 + '');

    step = suite[step];

    if (!step) {
      (window.opener || window).completeNavTest();

      if (window.opener) {
        window.close();
      }
    } else if (step === 'back') {
      logPhase('back');
      history.back();
    } else if (step === 'forward') {
      logPhase('forward');
      history.forward();
    } else {
      step(window);
    }

    // Handle tests that don't replace the context
    //
    // This will be terminated if we are on a test that leaves the page
    // context
    setTimeout(function() {
      var interval = setInterval(function() {
        if (window.document.getElementById('continue-tests')) {
          clearInterval(interval);

          testStep();
        }
      }, 50);
    }, 500);
  }
}, 100);

<commit_msg>Simplify tests into two separate tests<commit_after>var navigationTests = {
  'Page Change': [
    function(contentWindow) {
      logPhase('assign location', document.readyState);
      contentWindow.location = '/blank.html';
    },
    'back',
    'forward',
    'back',
    function(contentWindow) {
      logPhase('replace location', document.readyState);
      contentWindow.location.replace('/blank.html');
    },
    function(contentWindow) {
      logPhase('restore location', document.readyState);
      contentWindow.location = testOptions.type;
    },
    function(contentWindow) {
      logPhase('submit form', document.readyState);
      var form = contentWindow.document.createElement('form');
      form.action = '/blank.html';
      form.submit();
    }
  ],
  'Single Page': [
    function(contentWindow) {
      logPhase('assign hash location', document.readyState);
      contentWindow.location = contentWindow.location + '#foo';
    },
    'back',
    'forward',
    'back',
    function(contentWindow) {
      logPhase('assign hash', document.readyState);
      contentWindow.hash = '#hash-foo';
    },
    'back',
    'forward',
    function(contentWindow) {
      logPhase('replace location', document.readyState);
      contentWindow.location.replace(contentWindow.location + '#bar');
    },

    'back',
    'forward',

    function(contentWindow) {
      logPhase('pushState', document.readyState);
      contentWindow.history.pushState(undefined, 'foo', 'foo');
    },
    'back',
    'forward',
    function(contentWindow) {
      logPhase('replaceState', document.readyState);
      contentWindow.history.replaceState(undefined, 'foo', 'foo');
    },
    function(contentWindow) {
      logPhase('abort request', document.readyState);
      contentWindow.abortRequest();
    }
  ]
};

// Defer do the page is loaded as some of these operations behave differently
// if run while the page is still loading.
setTimeout(function testStep() {
  var running = localStorage.getItem('test-running') === 'true';
  if (running) {
    var suite = navigationTests[localStorage.getItem('test-name')],
        step = parseInt(localStorage.getItem('test-step'), 10);

    localStorage.setItem('test-step', step + 1 + '');

    step = suite[step];

    if (!step) {
      (window.opener || window).completeNavTest();

      if (window.opener) {
        window.close();
      }
    } else if (step === 'back') {
      logPhase('back');
      history.back();
    } else if (step === 'forward') {
      logPhase('forward');
      history.forward();
    } else {
      step(window);
    }

    // Handle tests that don't replace the context
    //
    // This will be terminated if we are on a test that leaves the page
    // context
    setTimeout(function() {
      var interval = setInterval(function() {
        if (window.document.getElementById('continue-tests')) {
          clearInterval(interval);

          testStep();
        }
      }, 50);
    }, 500);
  }
}, 100);

<|endoftext|>


<commit_before>$(document).ready(function () {

    var $status = $('#id_status');
    var $id_type = $('#id_type');
    var $periodical = $('#id_periodical');
    var $event = $('#id_event');
    var $published = $('#id_status_3');
    var $accepted = $('#id_status_2');
    var $submitted = $('#id_status_1');
    var $draft = $('#id_status_0');

    // ### Hide/show "Where will be published?" field ###
    if ($accepted.checked || $published.checked){
        $id_type.parents('.row').show();
    } else {
        $id_type.parents('.row').hide();
    }

    $status.click(function(){
       if ($accepted.is(':checked') || $published.is(':checked')) {
          $id_type.parents('.row').show();
       } else {
          $id_type.parents('.row').hide();
       }
    });

    // ### Hide/show event/periodical fields ###
    $id_type.each(function() {
        if($(this).val() == 'p' && ($published.is(':checked') || $accepted.is(':checked'))){
            $periodical.parents('.row').show();
        } else if($(this).val() == 'e' && ($published.is(':checked') || $accepted.is(':checked'))){
            $event.parents('.row').show();
        } else{
            $periodical.parents('.row').hide();
            $event.parents('.row').hide();
        }
    });

    $id_type.change(function(){
        if($(this).val() == 'p' && ($published.is(':checked') || $accepted.is(':checked'))){
            $periodical.parents('.row').show();
            $event.parents('.row').hide();
        } else if($(this).val() == 'e' && ($published.is(':checked') || $accepted.is(':checked'))){
            $periodical.parents('.row').hide();
            $event.parents('.row').show();
        } else{
            $periodical.parents('.row').hide();
            $event.parents('.row').hide();
        }
    });

    // ### Hide/show draft inline ###
    if ($draft.checked){
        $('[id^="draft"]').parents('._inline-group').show();
    } else {
        $('[id^="draft"]').parents('._inline-group').hide();
    }

    $status.click(function(){
       if ($draft.is(':checked')) {
          $('[id^="draft"]').parents('._inline-group').show();
       } else {
          $('[id^="draft"]').parents('._inline-group').hide();
       }
    });

    // ### Hide/show submitted inline ###
    if ($submitted.checked){
        $('[id^="submitted"]').parents('._inline-group').show();
    } else {
        $('[id^="submitted"]').parents('._inline-group').hide();
    }

    $status.click(function(){
       if ($submitted.is(':checked')) {
          $('[id^="submitted"]').parents('._inline-group').show();
       } else {
          $('[id^="submitted"]').parents('._inline-group').hide();
       }
    });

    // ### Hide/show accepted inline ###
    if ($accepted.checked){
        $('[id^="accepted"]').parents('._inline-group').show();
    } else {
        $('[id^="accepted"]').parents('._inline-group').hide();
    }

    $status.click(function(){
       if ($accepted.is(':checked')) {
          $('[id^="accepted"]').parents('._inline-group').show();
       } else {
          $('[id^="accepted"]').parents('._inline-group').hide();
       }
    });

    // ### Hide/show published in periodical inline ###
    $periodical.each(function() {
        if($(this).length && ($id_type.val() == 'p' && $published.is(':checked'))){
            $('[id^="publishedinperiodical"]').parents('._inline-group').show();
        } else{
            $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
        }
    });

    $periodical.change(function(){
        if($(this).val() != ''  && ($id_type.val() == 'p' && $published.is(':checked'))){
            $('[id^="publishedinperiodical"]').parents('._inline-group').show();
        } else{
            $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
        }
    });

    // ### Hide/show published inline ###
    $event.each(function() {
        if($(this).length && ($id_type.val() == 'e' && $published.is(':checked'))){
            $('[id^="published-"]').parents('._inline-group').show();
        } else{
            $('[id^="published-"]').parents('._inline-group').hide();
        }
    });

    $event.change(function(){
        if($(this).val() != ''  && ($id_type.val() == 'e' && $published.is(':checked'))){
            $('[id^="published-"]').parents('._inline-group').show();
        } else{
            $('[id^="published-"]').parents('._inline-group').hide();
        }
    });

    // ### Hide/show published or published in periodical inline ###
    $id_type.change(function(){
        if($(this).val() == 'p' && $periodical.val() != '' && $published.is(':checked')){
            $('[id^="publishedinperiodical"]').parents('._inline-group').show();
        } else if($(this).val() == 'e' && $event.val() != '' && $published.is(':checked')){
            $('[id^="published-"]').parents('._inline-group').show();
        } else{
            $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
            $('[id^="published-"]').parents('._inline-group').hide();
        }
    });

    $status.click(function(){
       if ($published.is(':checked') && ($id_type.val() == 'p' && $periodical.val() != '')) {
           $('[id^="publishedinperiodical"]').parents('._inline-group').show();
           $periodical.parents('.row').show();
       } else if($accepted.is(':checked') && ($id_type.val() == 'p' && $periodical.val() != '')){
           $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
           $periodical.parents('.row').show();
       } else if($published.is(':checked') && $id_type.val() == 'p'){
           $periodical.parents('.row').show();
       } else {
           $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
           $periodical.parents('.row').hide();
       }
    });

    $status.click(function(){
       if ($published.is(':checked') && $id_type.val() == 'e' && $event.val() != '') {
           $('[id^="published-"]').parents('._inline-group').show();
           $event.parents('.row').show();
       } else if($accepted.is(':checked') && ($id_type.val() == 'e' && $event.val() != '')){
           $('[id^="published-"]').parents('._inline-group').hide();
           $event.parents('.row').show();
       } else if($published.is(':checked') && $id_type.val() == 'e'){
           $event.parents('.row').show();
       } else {
           $('[id^="published-"]').parents('._inline-group').hide();
           $event.parents('.row').hide();
       }
    });

});<commit_msg>Bug fix<commit_after>$(document).ready(function () {

    var $status = $('#id_status');
    var $id_type = $('#id_type');
    var $periodical = $('#id_periodical');
    var $event = $('#id_event');
    var $published = $('#id_status_3');
    var $accepted = $('#id_status_2');
    var $submitted = $('#id_status_1');
    var $draft = $('#id_status_0');

    // ### Hide/show "Where will be published?" field ###
    if ($accepted.checked || $published.checked){
        $id_type.parents('.row').show();
    } else {
        $id_type.parents('.row').hide();
    }

    $status.click(function(){
       if ($accepted.is(':checked') || $published.is(':checked')) {
          $id_type.parents('.row').show();
       } else {
          $id_type.parents('.row').hide();
       }
    });

    // ### Hide/show event/periodical fields ###
    $id_type.each(function() {
        if($(this).val() == 'p' && ($published.is(':checked') || $accepted.is(':checked'))){
            $periodical.parents('.row').show();
        } else if($(this).val() == 'e' && ($published.is(':checked') || $accepted.is(':checked'))){
            $event.parents('.row').show();
        } else{
            $periodical.parents('.row').hide();
            $event.parents('.row').hide();
        }
    });

    $id_type.change(function(){
        if($(this).val() == 'p' && ($published.is(':checked') || $accepted.is(':checked'))){
            $periodical.parents('.row').show();
            $event.parents('.row').hide();
        } else if($(this).val() == 'e' && ($published.is(':checked') || $accepted.is(':checked'))){
            $periodical.parents('.row').hide();
            $event.parents('.row').show();
        } else{
            $periodical.parents('.row').hide();
            $event.parents('.row').hide();
        }
    });

    // ### Hide/show draft inline ###
    if ($draft.is(':checked')) {
        $('[id^="draft"]').parents('._inline-group').show();
    } else {
        $('[id^="draft"]').parents('._inline-group').hide();
    }

    $status.click(function(){
       if ($draft.is(':checked')) {
          $('[id^="draft"]').parents('._inline-group').show();
       } else {
          $('[id^="draft"]').parents('._inline-group').hide();
       }
    });

    // ### Hide/show submitted inline ###
    if ($submitted.is(':checked')) {
        $('[id^="submitted"]').parents('._inline-group').show();
    } else {
        $('[id^="submitted"]').parents('._inline-group').hide();
    }

    $status.click(function(){
       if ($submitted.is(':checked')) {
          $('[id^="submitted"]').parents('._inline-group').show();
       } else {
          $('[id^="submitted"]').parents('._inline-group').hide();
       }
    });

    // ### Hide/show accepted inline ###
    if ($accepted.is(':checked')) {
        $('[id^="accepted"]').parents('._inline-group').show();
    } else {
        $('[id^="accepted"]').parents('._inline-group').hide();
    }

    $status.click(function(){
       if ($accepted.is(':checked')) {
          $('[id^="accepted"]').parents('._inline-group').show();
       } else {
          $('[id^="accepted"]').parents('._inline-group').hide();
       }
    });

    // ### Hide/show published in periodical inline ###
    $periodical.each(function() {
        if($(this).length && ($id_type.val() == 'p' && $published.is(':checked'))){
            $('[id^="publishedinperiodical"]').parents('._inline-group').show();
        } else{
            $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
        }
    });

    $periodical.change(function(){
        if($(this).val() != ''  && ($id_type.val() == 'p' && $published.is(':checked'))){
            $('[id^="publishedinperiodical"]').parents('._inline-group').show();
        } else{
            $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
        }
    });

    // ### Hide/show published inline ###
    $event.each(function() {
        if($(this).length && ($id_type.val() == 'e' && $published.is(':checked'))){
            $('[id^="published-"]').parents('._inline-group').show();
        } else{
            $('[id^="published-"]').parents('._inline-group').hide();
        }
    });

    $event.change(function(){
        if($(this).val() != ''  && ($id_type.val() == 'e' && $published.is(':checked'))){
            $('[id^="published-"]').parents('._inline-group').show();
        } else{
            $('[id^="published-"]').parents('._inline-group').hide();
        }
    });

    // ### Hide/show published or published in periodical inline ###
    $id_type.change(function(){
        if($(this).val() == 'p' && $periodical.val() != '' && $published.is(':checked')){
            $('[id^="publishedinperiodical"]').parents('._inline-group').show();
        } else if($(this).val() == 'e' && $event.val() != '' && $published.is(':checked')){
            $('[id^="published-"]').parents('._inline-group').show();
        } else{
            $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
            $('[id^="published-"]').parents('._inline-group').hide();
        }
    });

    $status.click(function(){
       if ($published.is(':checked') && ($id_type.val() == 'p' && $periodical.val() != '')) {
           $('[id^="publishedinperiodical"]').parents('._inline-group').show();
           $periodical.parents('.row').show();
       } else if($accepted.is(':checked') && ($id_type.val() == 'p' && $periodical.val() != '')){
           $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
           $periodical.parents('.row').show();
       } else if($published.is(':checked') && $id_type.val() == 'p'){
           $periodical.parents('.row').show();
       } else {
           $('[id^="publishedinperiodical"]').parents('._inline-group').hide();
           $periodical.parents('.row').hide();
       }
    });

    $status.click(function(){
       if ($published.is(':checked') && $id_type.val() == 'e' && $event.val() != '') {
           $('[id^="published-"]').parents('._inline-group').show();
           $event.parents('.row').show();
       } else if($accepted.is(':checked') && ($id_type.val() == 'e' && $event.val() != '')){
           $('[id^="published-"]').parents('._inline-group').hide();
           $event.parents('.row').show();
       } else if($published.is(':checked') && $id_type.val() == 'e'){
           $event.parents('.row').show();
       } else {
           $('[id^="published-"]').parents('._inline-group').hide();
           $event.parents('.row').hide();
       }
    });

});<|endoftext|>