<commit_before>{
	"translatorID":"c159dcfe-8a53-4301-a499-30f6549c340d",
	"translatorType":4,
	"label":"DOI",
	"creator":"Simon Kornblith",
	"target":null,
	"minVersion":"1.0.10",
	"maxVersion":"",
	"priority":300,
	"inRepository":true,
	"lastUpdated":"2009-04-07 15:48:00"
}

var items = {};
var selectArray = {};

// builds a list of DOIs
function getDOIs(doc) {
	const DOIre = /\b(10\.[\w.]+\/[^\/\s]+)\.?\b/igm;
	const DOIXPath = "//text()[contains(., '10.')]";

	DOIre.lastMatch = 0;
	var DOIs = [];

	var node, m;
	var results = doc.evaluate(DOIXPath, doc, null, XPathResult.ANY_TYPE, null);
	while(node = results.iterateNext()) {
		while(m = DOIre.exec(node.nodeValue)) {
			var DOI = m[1];
			if(DOI.substr(-1) == ")" && DOI.indexOf("(") == -1) {
				DOI = DOI.substr(0, DOI.length-1);
			}
			// only add new DOIs
			if(DOIs.indexOf(DOI) == -1) {
				DOIs.push(DOI);
			}
		}
	}

	return DOIs;
}

function detectWeb(doc, url) {
	const blacklistRe = /^https?:\/\/[^/]*google\.com/i;

	if(!blacklistRe.test(url)) {
		var DOIs = getDOIs(doc);
		Zotero.debug(DOIs);
		if(DOIs.length) {
			return DOIs.length == 1 ? "journalArticle" : "multiple";
		}
	}
	return false;
}

function retrieveNextDOI(DOIs, doc) {
	if(DOIs.length) {
		// retrieve DOI
		var DOI = DOIs.shift();
		var translate = Zotero.loadTranslator("search");
		translate.setTranslator("11645bd1-0420-45c1-badb-53fb41eeb753");
		var item = {"itemType":"journalArticle", "DOI":DOI};
		translate.setSearch(item);
		// don't save when item is done
		translate.setHandler("itemDone", function(translate, item) {
			item.repository = "CrossRef";
			items[DOI] = item;
			selectArray[DOI] = item.title;
		});
		translate.setHandler("done", function(translate) {
			retrieveNextDOI(DOIs, doc);
		});
		translate.translate();
	} else {
		// all DOIs retrieved now
		// check to see if there is more than one DOI
		var numDOIs = 0;
		for(var DOI in selectArray) {
			numDOIs++;
			if(numDOIs == 2) break;
		}
		if(numDOIs == 0) {
			throw "DOI Translator: could not find DOI";
		} else if(numDOIs == 1) {
			// do we want to add URL of the page?
			items[DOI].url = doc.location.href;
			items[DOI].attachments = [{document:doc}];
			items[DOI].complete();
		} else {
			selectArray = Zotero.selectItems(selectArray);
			for(var DOI in selectArray) {
				items[DOI].complete();
			}
		}
		Zotero.done();
	}
}

function doWeb(doc, url) {
	var DOIs = getDOIs(doc);
	// retrieve full items asynchronously
	Zotero.wait();
	retrieveNextDOI(DOIs, doc);
}<commit_msg>remove extraneous DOI debug code<commit_after>{
	"translatorID":"c159dcfe-8a53-4301-a499-30f6549c340d",
	"translatorType":4,
	"label":"DOI",
	"creator":"Simon Kornblith",
	"target":null,
	"minVersion":"1.0.10",
	"maxVersion":"",
	"priority":300,
	"inRepository":true,
	"lastUpdated":"2009-04-07 15:48:00"
}

var items = {};
var selectArray = {};

// builds a list of DOIs
function getDOIs(doc) {
	const DOIre = /\b(10\.[\w.]+\/[^\/\s]+)\.?\b/igm;
	const DOIXPath = "//text()[contains(., '10.')]";

	DOIre.lastMatch = 0;
	var DOIs = [];

	var node, m;
	var results = doc.evaluate(DOIXPath, doc, null, XPathResult.ANY_TYPE, null);
	while(node = results.iterateNext()) {
		while(m = DOIre.exec(node.nodeValue)) {
			var DOI = m[1];
			if(DOI.substr(-1) == ")" && DOI.indexOf("(") == -1) {
				DOI = DOI.substr(0, DOI.length-1);
			}
			// only add new DOIs
			if(DOIs.indexOf(DOI) == -1) {
				DOIs.push(DOI);
			}
		}
	}

	return DOIs;
}

function detectWeb(doc, url) {
	const blacklistRe = /^https?:\/\/[^/]*google\.com/i;

	if(!blacklistRe.test(url)) {
		var DOIs = getDOIs(doc);
		if(DOIs.length) {
			return DOIs.length == 1 ? "journalArticle" : "multiple";
		}
	}
	return false;
}

function retrieveNextDOI(DOIs, doc) {
	if(DOIs.length) {
		// retrieve DOI
		var DOI = DOIs.shift();
		var translate = Zotero.loadTranslator("search");
		translate.setTranslator("11645bd1-0420-45c1-badb-53fb41eeb753");
		var item = {"itemType":"journalArticle", "DOI":DOI};
		translate.setSearch(item);
		// don't save when item is done
		translate.setHandler("itemDone", function(translate, item) {
			item.repository = "CrossRef";
			items[DOI] = item;
			selectArray[DOI] = item.title;
		});
		translate.setHandler("done", function(translate) {
			retrieveNextDOI(DOIs, doc);
		});
		translate.translate();
	} else {
		// all DOIs retrieved now
		// check to see if there is more than one DOI
		var numDOIs = 0;
		for(var DOI in selectArray) {
			numDOIs++;
			if(numDOIs == 2) break;
		}
		if(numDOIs == 0) {
			throw "DOI Translator: could not find DOI";
		} else if(numDOIs == 1) {
			// do we want to add URL of the page?
			items[DOI].url = doc.location.href;
			items[DOI].attachments = [{document:doc}];
			items[DOI].complete();
		} else {
			selectArray = Zotero.selectItems(selectArray);
			for(var DOI in selectArray) {
				items[DOI].complete();
			}
		}
		Zotero.done();
	}
}

function doWeb(doc, url) {
	var DOIs = getDOIs(doc);
	// retrieve full items asynchronously
	Zotero.wait();
	retrieveNextDOI(DOIs, doc);
}<|endoftext|>


<commit_before>const path = require('path')
const { createFilePath } = require(`gatsby-source-filesystem`)

// To add the slug field to each post
exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  // Ensures we are processing only markdown files
  if (node.internal.type === "MarkdownRemark") {
    // Use `createFilePath` to turn markdown files in our `data/faqs` directory into `/faqs/slug`
    const slug = createFilePath({
      node,
      getNode,
      basePath: "pages",
    })

    // Creates new query'able field with name of 'slug'
    createNodeField({
      node,
      name: "slug",
      value: `/${slug.slice(12)}`,
    })
  }
}

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  return graphql(`
    {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `).then(result => {
    result.data.allMarkdownRemark.edges.forEach(({ node }) => {
      createPage({
        path: node.fields.slug,
        component: path.resolve('./src/templates/blog-post.js'),
        context: {
          slug: node.fields.slug
        }
      })
    })
  })
}
<commit_msg>feat: add calc for pagination<commit_after>const path = require('path')
const { createFilePath } = require(`gatsby-source-filesystem`)

// To add the slug field to each post
exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  // Ensures we are processing only markdown files
  if (node.internal.type === "MarkdownRemark") {
    // Use `createFilePath` to turn markdown files in our `data/faqs` directory into `/faqs/slug`
    const slug = createFilePath({
      node,
      getNode,
      basePath: "pages",
    })

    // Creates new query'able field with name of 'slug'
    createNodeField({
      node,
      name: "slug",
      value: `/${slug.slice(12)}`,
    })
  }
}

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  return graphql(`
    {
      allMarkdownRemark(sort: {fields: frontmatter___date, order: DESC}) {
        edges {
          node {
            fields {
              slug
            }
            frontmatter {
              background
              category
              date(locale: "en-us", formatString: "MMMM DD[,] YYYY")
              description
              title
            }
            timeToRead
          }
        }
      }
    }
  `).then(result => {
    const posts = result.data.allMarkdownRemark.edges

    posts.forEach(({ node }) => {
      createPage({
        path: node.fields.slug,
        component: path.resolve('./src/templates/blog-post.js'),
        context: {
          slug: node.fields.slug
        }
      })
    })

    const postsPerPage = 16
    const numPages = Math.ceil(posts.length / postsPerPage)

    Array.from({ length: numPages }).forEach((_, index) => {
      createPage({
        path: index === 0 ? `/` : `/page/${index + 1}`,
        component: path.resolve(`./src/templates/blog-list.js`),
        context: {
          limit: postsPerPage,
          skip: index * postsPerPage,
          numPages,
          currentPage: index + 1
        }
      })
    })
  })
}
<|endoftext|>


<commit_before>import icon from 'part:@sanity/base/sync-icon'

export default {
  name: 'referenceTest',
  type: 'document',
  title: 'Reference test',
  description: 'Test cases for references',
  icon,
  fields: [
    {name: 'title', type: 'string'},
    {
      title: 'Book with decade filter',
      description: 'Reference will only search for books within given decade',
      name: 'filtered',
      type: 'object',
      validation: (Rule) =>
        Rule.custom((val) => (!val || val.decade ? true : 'Must have decade defined')),
      fields: [
        {
          title: 'Decade',
          description: 'eg. 1980, 1990, 2000',
          name: 'decade',
          type: 'number',
          validation: (Rule) =>
            Rule.required()
              .min(0)
              .max(3000)
              .custom((year) => {
                return year % 10 ? 'Must be a decade, eg use 1990 instead of 1994' : true
              }),
        },
        {
          name: 'book',
          title: 'Book reference',
          type: 'reference',
          to: {type: 'book'},
          options: {
            filter: (options) => {
              const decade = options.parent && options.parent.decade
              if (!decade) {
                return {filter: 'false'} // && false always returns no results :)
              }

              const minYear = Math.floor(decade / 10) * 10
              const maxYear = minYear + 9

              return {
                filter: 'publicationYear >= $minYear && publicationYear <= $maxYear',
                params: {minYear, maxYear},
              }
            },
          },
        },
      ],
    },
    {name: 'selfRef', type: 'reference', to: {type: 'referenceTest'}},
    {
      name: 'invalidFilter',
      title: 'Invalid filter',
      description: 'This will error when trying to search for anything',
      type: 'reference',
      to: {type: 'book'},
      options: {
        filter: '&',
      },
    },
    {
      name: 'asyncFilter',
      title: 'Async filter',
      type: 'reference',
      to: {type: 'book'},
      options: {
        filter: () =>
          Promise.resolve({filter: '$param == "something"', params: {param: 'something'}}),
      },
    },
    {
      name: 'refToTypeWithNoToplevelStrings',
      type: 'reference',
      to: {type: 'typeWithNoToplevelStrings'},
    },
    {
      name: 'someStrongRef',
      title: 'Strong reference (default)',
      type: 'reference',
      to: {type: 'author'},
    },
    {
      name: 'someWeakRef',
      title: 'Weak reference',
      type: 'reference',
      weak: true,
      to: {type: 'author'},
    },
    {
      name: 'anotherWeakRef',
      title: 'Another weak reference',
      type: 'reference',
      weak: true,
      to: {type: 'author'},
    },
    {
      title: 'Reference to book or author',
      name: 'multiTypeRef',
      type: 'reference',
      to: [{type: 'book'}, {type: 'author'}],
    },
    {
      name: 'array',
      type: 'array',
      of: [
        {
          type: 'reference',
          name: 'strongAuthorRef',
          title: 'A strong author ref',
          to: {type: 'author'},
        },
        {
          type: 'reference',
          name: 'weakAuthorRef',
          title: 'A weak author ref',
          weak: true,
          to: {type: 'author'},
        },
      ],
    },
  ],
  preview: {
    fields: {
      title: 'title',
      author0: 'array.0.name',
      author1: 'array.1.name',
    },
    prepare(val) {
      return {
        title: val.title,
        subtitle: [val.author0, val.author1].filter(Boolean).join(', '),
      }
    },
  },
}
<commit_msg>chore(test-studio): rearrange reference test type<commit_after>import icon from 'part:@sanity/base/sync-icon'

export default {
  name: 'referenceTest',
  type: 'document',
  title: 'Reference test',
  description: 'Test cases for references',
  icon,
  fields: [
    {name: 'title', type: 'string'},
    {name: 'selfRef', type: 'reference', to: {type: 'referenceTest'}},
    {
      title: 'Reference to book or author',
      name: 'multiTypeRef',
      type: 'reference',
      to: [{type: 'book'}, {type: 'author'}],
    },
    {
      title: 'Book with decade filter',
      description: 'Reference will only search for books within given decade',
      name: 'filtered',
      type: 'object',
      validation: (Rule) =>
        Rule.custom((val) => (!val || val.decade ? true : 'Must have decade defined')),
      fields: [
        {
          title: 'Decade',
          description: 'eg. 1980, 1990, 2000',
          name: 'decade',
          type: 'number',
          validation: (Rule) =>
            Rule.required()
              .min(0)
              .max(3000)
              .custom((year) => {
                return year % 10 ? 'Must be a decade, eg use 1990 instead of 1994' : true
              }),
        },
        {
          name: 'book',
          title: 'Book reference',
          type: 'reference',
          to: {type: 'book'},
          options: {
            filter: (options) => {
              const decade = options.parent && options.parent.decade
              if (!decade) {
                return {filter: 'false'} // && false always returns no results :)
              }

              const minYear = Math.floor(decade / 10) * 10
              const maxYear = minYear + 9

              return {
                filter: 'publicationYear >= $minYear && publicationYear <= $maxYear',
                params: {minYear, maxYear},
              }
            },
          },
        },
      ],
    },
    {
      name: 'invalidFilter',
      title: 'Invalid filter',
      description: 'This will error when trying to search for anything',
      type: 'reference',
      to: {type: 'book'},
      options: {
        filter: '&',
      },
    },
    {
      name: 'asyncFilter',
      title: 'Async filter',
      type: 'reference',
      to: {type: 'book'},
      options: {
        filter: () =>
          Promise.resolve({filter: '$param == "something"', params: {param: 'something'}}),
      },
    },
    {
      name: 'refToTypeWithNoToplevelStrings',
      type: 'reference',
      to: {type: 'typeWithNoToplevelStrings'},
    },
    {
      name: 'someStrongRef',
      title: 'Strong reference (default)',
      type: 'reference',
      to: {type: 'author'},
    },
    {
      name: 'someWeakRef',
      title: 'Weak reference',
      type: 'reference',
      weak: true,
      to: {type: 'author'},
    },
    {
      name: 'anotherWeakRef',
      title: 'Another weak reference',
      type: 'reference',
      weak: true,
      to: {type: 'author'},
    },
    {
      name: 'array',
      type: 'array',
      of: [
        {
          type: 'reference',
          name: 'strongAuthorRef',
          title: 'A strong author ref',
          to: {type: 'author'},
        },
        {
          type: 'reference',
          name: 'weakAuthorRef',
          title: 'A weak author ref',
          weak: true,
          to: {type: 'author'},
        },
      ],
    },
  ],
  preview: {
    fields: {
      title: 'title',
      author0: 'array.0.name',
      author1: 'array.1.name',
    },
    prepare(val) {
      return {
        title: val.title,
        subtitle: [val.author0, val.author1].filter(Boolean).join(', '),
      }
    },
  },
}
<|endoftext|>


<commit_before>"use strict";

console.log("Hello, world!");

var module = angular.module("main",[]);

module.controller("mainCtrl", function($scope, $http) {
	$scope.queryResult = "";
	$scope.queryText = "";
	$scope.onSubmitQuery = function() {
		$http.get('/query', {params:{query: $scope.queryText}}).
		  success(function(data, status, headers, config) {
		    $scope.queryResult = data;
		  }).
		  error(function(data, status, headers, config) {
		    $scope.queryResult = data;
		  });
	};
	$scope.$watch("queryResult", resultUpdate);
});

var chart;

function onload() {
	google.load('visualization', '1.0', {'packages':['corechart']});
	// Perform this callback once the package has loaded:
	google.setOnLoadCallback(drawChart);
}

function resultUpdate(object) {
	if (!(object && object.name == "select" && object.body && object.body.length && object.body[0].series && object.body[0].series.length && object.body[0].timerange)) {
		return;
	}
	var series = [];
	for (var i = 0; i < object.body.length; i++) {
		// Each of these is a list of series
		for (var j = 0; j < object.body[i].series.length; j++) {
			series.push(object.body[i].series[j]);
		}
	}
	var labels = ["Time"];
	for (var i = 0; i < series.length; i++) {
		var label = "";
		for (var k in series[i].tagset) {
			label += k + ": " + series[i].tagset[k] + " ";
		}
		labels.push(label);
	}
	var table = [labels];
	// Next, add each row.

	var startTime = object.body[0].timerange.start;
	var endTime = object.body[0].timerange.end;
	var resolution = object.body[0].timerange.resolution;

	for (var t = 0; t < series[0].values.length; t++) {
		var row = [new Date(startTime + resolution * t)];
		for (var i = 0; i < series.length; i++) {
			row.push(series[i].values[t] || 0);
		}
		table.push(row);
	}
	console.log(table);
	var trueTable = google.visualization.arrayToDataTable(table);
	var options = {
		title: "Select Result",
		legend: {position: "bottom"}
	}

	var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
	chart.draw(trueTable, options);
}

/*
function resultUpdate(value) {
	if (chart) {
		chart.destroy();
		chart = null;
	}
	if (value && value.name == "select" && value.body && value.body.length && value.body[0].series && value.body[0].series.length) {
		var datasets = [];
		for (var i = 0; i < value.body.length; i++) {
			var list = value.body[i];
			for (var j = 0; j < list.series.length; j++) {
				var series = list.series[j];
				var seriesData = {
					data:[],
					label: "D" + datasets.length,
		            strokeColor: "rgba(151,187,205,1)",
				};
				for (var t = 0; t < series.values.length; t++) {
					seriesData.data[t] = series.values[t];
				}
				datasets.push(seriesData);
			}
		}
		for (var i = 0; i < datasets.length; i++) {
			datasets[i].pointColor = datasets[i].strokeColor = "hsl(" + Math.floor(360 * i / datasets.length) + ",50%,65%)";
		}

		var labels = [];
		for (var i = 0; i < value.body[0].series[0].values.length; i++) {
			labels[i] = i + "X";
		}

		chart = new Chart(ctx).Line({datasets:datasets,labels:labels}, {datasetFill:false, bezierCurve: false, pointDot:false});
	}
}

*/<commit_msg>remove (harmless) erroring line<commit_after>"use strict";

console.log("Hello, world!");

var module = angular.module("main",[]);

module.controller("mainCtrl", function($scope, $http) {
	$scope.queryResult = "";
	$scope.queryText = "";
	$scope.onSubmitQuery = function() {
		$http.get('/query', {params:{query: $scope.queryText}}).
		  success(function(data, status, headers, config) {
		    $scope.queryResult = data;
		  }).
		  error(function(data, status, headers, config) {
		    $scope.queryResult = data;
		  });
	};
	$scope.$watch("queryResult", resultUpdate);
});

var chart;

function onload() {
	google.load('visualization', '1.0', {'packages':['corechart']});
}

function resultUpdate(object) {
	if (!(object && object.name == "select" && object.body && object.body.length && object.body[0].series && object.body[0].series.length && object.body[0].timerange)) {
		return;
	}
	var series = [];
	for (var i = 0; i < object.body.length; i++) {
		// Each of these is a list of series
		for (var j = 0; j < object.body[i].series.length; j++) {
			series.push(object.body[i].series[j]);
		}
	}
	var labels = ["Time"];
	for (var i = 0; i < series.length; i++) {
		var label = "";
		for (var k in series[i].tagset) {
			label += k + ": " + series[i].tagset[k] + " ";
		}
		labels.push(label);
	}
	var table = [labels];
	// Next, add each row.

	var startTime = object.body[0].timerange.start;
	var endTime = object.body[0].timerange.end;
	var resolution = object.body[0].timerange.resolution;

	for (var t = 0; t < series[0].values.length; t++) {
		var row = [new Date(startTime + resolution * t)];
		for (var i = 0; i < series.length; i++) {
			row.push(series[i].values[t] || 0);
		}
		table.push(row);
	}
	console.log(table);
	var trueTable = google.visualization.arrayToDataTable(table);
	var options = {
		title: "Select Result",
		legend: {position: "bottom"}
	}

	var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
	chart.draw(trueTable, options);
}

/*
function resultUpdate(value) {
	if (chart) {
		chart.destroy();
		chart = null;
	}
	if (value && value.name == "select" && value.body && value.body.length && value.body[0].series && value.body[0].series.length) {
		var datasets = [];
		for (var i = 0; i < value.body.length; i++) {
			var list = value.body[i];
			for (var j = 0; j < list.series.length; j++) {
				var series = list.series[j];
				var seriesData = {
					data:[],
					label: "D" + datasets.length,
		            strokeColor: "rgba(151,187,205,1)",
				};
				for (var t = 0; t < series.values.length; t++) {
					seriesData.data[t] = series.values[t];
				}
				datasets.push(seriesData);
			}
		}
		for (var i = 0; i < datasets.length; i++) {
			datasets[i].pointColor = datasets[i].strokeColor = "hsl(" + Math.floor(360 * i / datasets.length) + ",50%,65%)";
		}

		var labels = [];
		for (var i = 0; i < value.body[0].series[0].values.length; i++) {
			labels[i] = i + "X";
		}

		chart = new Chart(ctx).Line({datasets:datasets,labels:labels}, {datasetFill:false, bezierCurve: false, pointDot:false});
	}
}

*/<|endoftext|>


<commit_before>/*
 * $Id: base64.js,v 1.2 2011/12/27 14:34:49 dankogai Exp dankogai $
 *
 *  Licensed under the MIT license.
 *  http://www.opensource.org/licenses/mit-license.php
 *
 */

(function(global){

if (global.Base64) return;

var b64chars
    = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var b64tab = function(bin){
    var t = {};
    for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;
    return t;
}(b64chars);

var sub_toBase64 = function(m){
    var n = (m.charCodeAt(0) << 16)
          | (m.charCodeAt(1) <<  8)
          | (m.charCodeAt(2)      );
    return b64chars.charAt( n >>> 18)
         + b64chars.charAt((n >>> 12) & 63)
         + b64chars.charAt((n >>>  6) & 63)
         + b64chars.charAt( n         & 63);
};

var toBase64 = function(bin){
    if (bin.match(/[^\x00-\xFF]/)) throw 'unsupported character found' ;
    var padlen = 0;
    while(bin.length % 3) {
        bin += '\0';
        padlen++;
    };
    var b64 = bin.replace(/[\x00-\xFF]{3}/g, sub_toBase64);
    if (!padlen) return b64;
    b64 = b64.substr(0, b64.length - padlen);
    while(padlen--) b64 += '=';
    return b64;
};

var btoa = global.btoa || toBase64;

var sub_fromBase64 = function(m){
        var n = (b64tab[ m.charAt(0) ] << 18)
            |   (b64tab[ m.charAt(1) ] << 12)
            |   (b64tab[ m.charAt(2) ] <<  6)
            |   (b64tab[ m.charAt(3) ]);
    return String.fromCharCode(  n >> 16 )
        +  String.fromCharCode( (n >>  8) & 0xff )
        +  String.fromCharCode(  n        & 0xff );
};

var fromBase64 = function(b64){
    b64 = b64.replace(/[^A-Za-z0-9\+\/]/g, '');
    var padlen = 0;
    while(b64.length % 4){
        b64 += 'A';
        padlen++;
    }
    var bin = b64.replace(/[A-Za-z0-9\+\/]{4}/g, sub_fromBase64);
    if (padlen != 0)
        bin = bin.substring(0, bin.length - padlen);
    return bin;
};

var atob = global.atob || fromBase64;

var re_char_nonascii = /[^\x00-\x7F]/g;

var sub_char_nonascii = function(m){
    var n = m.charCodeAt(0);
    return n < 0x800 ? String.fromCharCode(0xc0 | (n >>>  6))
                     + String.fromCharCode(0x80 | (n & 0x3f))
        :              String.fromCharCode(0xe0 | ((n >>> 12) & 0x0f))
                     + String.fromCharCode(0x80 | ((n >>>  6) & 0x3f))
                     + String.fromCharCode(0x80 |  (n         & 0x3f))
        ;
};

var utob = function(uni){
    return uni.replace(re_char_nonascii, sub_char_nonascii);
};

var re_bytes_nonascii
    = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;

var sub_bytes_nonascii = function(m){
    var c0 = m.charCodeAt(0);
    var c1 = m.charCodeAt(1);
    if(c0 < 0xe0){
        return String.fromCharCode(((c0 & 0x1f) << 6) | (c1 & 0x3f));
    }else{
        var c2 = m.charCodeAt(2);
        return String.fromCharCode(
            ((c0 & 0x0f) << 12) | ((c1 & 0x3f) <<  6) | (c2 & 0x3f)
        );
    }
};

var btou = function(bin){
    return bin.replace(re_bytes_nonascii, sub_bytes_nonascii);
};

global.Base64 = {
    fromBase64:fromBase64,
    toBase64:toBase64,
    atob:atob,
    btoa:btoa,
    utob:utob,
    btou:btou,
    encode:function(u){ return btoa(utob(u)) },
    encodeURI:function(u){
        return btoa(utob(u)).replace(/[+\/]/g, function(m0){
            return m0 == '+' ? '-' : '_';
        }).replace(/=+$/, '');
    },
    decode:function(a){
        return btou(atob(a.replace(/[-_]/g, function(m0){
            return m0 == '-' ? '+' : '/';
        })));
    }
};

})(this);
<commit_msg>pulled https://github.com/dankogai/js-base64/pull/2/files<commit_after>/*
 * $Id: base64.js,v 1.3 2012/08/06 02:18:40 dankogai Exp dankogai $
 */

(function(){

var b64chars
    = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

var b64charcodes = function(){
    var a = [];
    var codeA = 'A'.charCodeAt(0);
    var codea = 'a'.charCodeAt(0);
    var code0 = '0'.charCodeAt(0);
    for (var i = 0; i < 26; i ++) a.push(codeA + i);
    for (var i = 0; i < 26; i ++) a.push(codea + i);
    for (var i = 0; i < 10; i ++) a.push(code0 + i);
    a.push('+'.charCodeAt(0));
    a.push('/'.charCodeAt(0));
    return a;
}();

var b64tab = function(bin){
    var t = {};
    for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;
    return t;
}(b64chars);

var stringToArray = function(s){
    var a = [];
    for (var i = 0, l = s.length; i < l; i ++) a[i] = s.charCodeAt(i);
    return a;
};

var convertUTF8ArrayToBase64 = function(bin){
    var padlen = 0;
    while (bin.length % 3){
        bin.push(0);
        padlen++;
    };
    var b64 = [];
    for (var i = 0, l = bin.length; i < l; i += 3){
        var c0 = bin[i], c1 = bin[i+1], c2 = bin[i+2];
        if (c0 >= 256 || c1 >= 256 || c2 >= 256)
            throw 'unsupported character found';
        var n = (c0 << 16) | (c1 << 8) | c2;
        b64.push(
            b64charcodes[ n >>> 18],
            b64charcodes[(n >>> 12) & 63],
            b64charcodes[(n >>>  6) & 63],
            b64charcodes[ n         & 63]
        );
    }
    while (padlen--) b64[b64.length - padlen - 1] = '='.charCodeAt(0);
    return chunkStringFromCharCodeApply(b64);
};

var convertBase64ToUTF8Array = function(b64){
    b64 = b64.replace(/[^A-Za-z0-9+\/]+/g, '');
    var bin = [];
    var padlen = b64.length % 4;
    for (var i = 0, l = b64.length; i < l; i += 4){
        var n = ((b64tab[b64.charAt(i  )] || 0) << 18)
            |   ((b64tab[b64.charAt(i+1)] || 0) << 12)
            |   ((b64tab[b64.charAt(i+2)] || 0) <<  6)
            |   ((b64tab[b64.charAt(i+3)] || 0));
        bin.push(
            (  n >> 16 ),
            ( (n >>  8) & 0xff ),
            (  n        & 0xff )
        );
    }
    bin.length -= [0,0,2,1][padlen];
    return bin;
};

var convertUTF16ArrayToUTF8Array = function(uni){
    var bin = [];
    for (var i = 0, l = uni.length; i < l; i++){
        var n = uni[i];
        if (n < 0x80)
            bin.push(n);
        else if (n < 0x800)
            bin.push(
                0xc0 | (n >>>  6),
                0x80 | (n & 0x3f));
        else
            bin.push(
                0xe0 | ((n >>> 12) & 0x0f),
                0x80 | ((n >>>  6) & 0x3f),
                0x80 |  (n         & 0x3f));
    }
    return bin;
};

var convertUTF8ArrayToUTF16Array = function(bin){
    var uni = [];
    for (var i = 0, l = bin.length; i < l; i++){
        var c0 = bin[i];
        if    (c0 < 0x80){
            uni.push(c0);
        }else{
            var c1 = bin[++i];
            if (c0 < 0xe0){
                uni.push(((c0 & 0x1f) << 6) | (c1 & 0x3f));
            }else{
                var c2 = bin[++i];
                uni.push(
                       ((c0 & 0x0f) << 12) | ((c1 & 0x3f) << 6) | (c2 & 0x3f)
                );
            }
        }
    }
    return uni;
};

var convertUTF8StringToBase64 = function(bin){
    return convertUTF8ArrayToBase64(stringToArray(bin));
};

var convertBase64ToUTF8String = function(b64){
    return chunkStringFromCharCodeApply(convertBase64ToUTF8Array(b64));
};

var convertUTF8StringToUTF16Array = function(bin){
    return convertUTF8ArrayToUTF16Array(stringToArray(bin));
};

var convertUTF8ArrayToUTF16String = function(bin){
    return chunkStringFromCharCodeApply(convertUTF8ArrayToUTF16Array(bin));
};

var convertUTF8StringToUTF16String = function(bin){
    return chunkStringFromCharCodeApply(convertUTF8ArrayToUTF16Array(stringToArray(bin)));
};

var convertUTF16StringToUTF8Array = function(uni){
    return convertUTF16ArrayToUTF8Array(stringToArray(uni));
};

var convertUTF16ArrayToUTF8String = function(uni){
    return chunkStringFromCharCodeApply(convertUTF16ArrayToUTF8Array(uni));
};

var convertUTF16StringToUTF8String = function(uni){
    return chunkStringFromCharCodeApply(convertUTF16ArrayToUTF8Array(stringToArray(uni)));
};

//
// String.fromCharCode.apply will only handle arrays as big as 65536, after that
// it'll return a truncated string with no warning.
//
var chunkStringFromCharCodeApply = function(arr){
  var string = '';
  while(arr.length > 0)
    string += String.fromCharCode.apply(String, arr.splice(0, 65536));
  return string;
};

if (window.btoa){
    var btoa = window.btoa;
    var convertUTF16StringToBase64 = function (uni){
        return btoa(convertUTF16StringToUTF8String(uni));
    };
}
else {
    var btoa = convertUTF8StringToBase64;
    var convertUTF16StringToBase64 = function (uni){
        return convertUTF8ArrayToBase64(convertUTF16StringToUTF8Array(uni));
    };
}

if (window.atob){
    var atob = window.atob;
    var convertBase64ToUTF16String = function (b64){
        return convertUTF8StringToUTF16String(atob(b64));
    };
}
else {
    var atob = convertBase64ToUTF8String;
    var convertBase64ToUTF16String = function (b64){
        return convertUTF8ArrayToUTF16String(convertBase64ToUTF8Array(b64));
    };
}

window.Base64 = {
    convertUTF8ArrayToBase64:convertUTF8ArrayToBase64,
    convertByteArrayToBase64:convertUTF8ArrayToBase64,
    convertBase64ToUTF8Array:convertBase64ToUTF8Array,
    convertBase64ToByteArray:convertBase64ToUTF8Array,
    convertUTF16ArrayToUTF8Array:convertUTF16ArrayToUTF8Array,
    convertUTF16ArrayToByteArray:convertUTF16ArrayToUTF8Array,
    convertUTF8ArrayToUTF16Array:convertUTF8ArrayToUTF16Array,
    convertByteArrayToUTF16Array:convertUTF8ArrayToUTF16Array,
    convertUTF8StringToBase64:convertUTF8StringToBase64,
    convertBase64ToUTF8String:convertBase64ToUTF8String,
    convertUTF8StringToUTF16Array:convertUTF8StringToUTF16Array,
    convertUTF8ArrayToUTF16String:convertUTF8ArrayToUTF16String,
    convertByteArrayToUTF16String:convertUTF8ArrayToUTF16String,
    convertUTF8StringToUTF16String:convertUTF8StringToUTF16String,
    convertUTF16StringToUTF8Array:convertUTF16StringToUTF8Array,
    convertUTF16StringToByteArray:convertUTF16StringToUTF8Array,
    convertUTF16ArrayToUTF8String:convertUTF16ArrayToUTF8String,
    convertUTF16StringToUTF8String:convertUTF16StringToUTF8String,
    convertUTF16StringToBase64:convertUTF16StringToBase64,
    convertBase64ToUTF16String:convertBase64ToUTF16String,
    fromBase64:convertBase64ToUTF8String,
    toBase64:convertUTF8StringToBase64,
    atob:atob,
    btoa:btoa,
    utob:convertUTF16StringToUTF8String,
    btou:convertUTF8StringToUTF16String,
    encode:convertUTF16StringToBase64,
    encodeURI:function(u){
        return convertUTF16StringToBase64(u).replace(/[+\/]/g, function(m0){
            return m0 == '+' ? '-' : '_';
        }).replace(/=+$/, '');
    },
    decode:function(a){
        return convertBase64ToUTF16String(a.replace(/[-_]/g, function(m0){
            return m0 == '-' ? '+' : '/';
        }));
    }
};

})();
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */
/*jshint esnext:true, es5:true, curly:false */
/*global FBTrace:true, XPCNativeWrapper:true, Window:true, define:true */

define([
    "firebug/firebug",
    "firebug/lib/trace",
    "firebug/lib/object",
    "firebug/lib/array",
    "firebug/lib/wrapper",
    "firebug/lib/dom",
    "firebug/lib/locale",
    "firebug/console/closureInspector",
    "firebug/chrome/reps",
],
function(Firebug, FBTrace, Obj, Arr, Wrapper, Dom, Locale, ClosureInspector, FirebugReps) {

// ********************************************************************************************* //
// Constants

var Trace = FBTrace.to("DBG_DOM");
var TraceError = FBTrace.to("DBG_ERRORS");

// ********************************************************************************************* //
// DOM Member Provider

function DOMMemberProvider(context)
{
    this.context = context;
}

DOMMemberProvider.prototype =
{
    /**
     * @param object a user-level object wrapped in security blanket
     * @param level for a.b.c, level is 2
     */
    getMembers: function(object, level)
    {
        if (!level)
            level = 0;

        var ordinals = [];
        var userProps = [];
        var userClasses = [];
        var userFuncs = [];
        var domProps = [];
        var domClasses = [];
        var domFuncs = [];
        var domConstants = [];
        var proto = [];
        var domHandlers = [];

        var isScope = ClosureInspector.isScopeWrapper(object);

        try
        {
            // Special case for "arguments", which is not enumerable by for...in statement.
            if (isArguments(object))
                object = Arr.cloneArray(object);

            var properties;
            try
            {
                // Make sure not to touch the prototype chain of the magic scope objects.
                var ownOnly = Firebug.showOwnProperties || isScope;
                var enumerableOnly = Firebug.showEnumerableProperties;

                properties = this.getObjectProperties(object, enumerableOnly, ownOnly);
                properties = Arr.sortUnique(properties);

                var addOwn = function(prop)
                {
                    // Apparently, Object.prototype.hasOwnProperty.call(object, p) lies
                    // when 'object' is content and 'Object' is chrome... Bug 658909?
                    if (Object.getOwnPropertyDescriptor(object, prop) &&
                        properties.indexOf(prop) === -1)
                    {
                        properties.push(prop);
                    }
                };
                addOwn("constructor");
                addOwn("prototype");
                addOwn("wrappedJSObject");

                // __proto__ never shows in enumerations, so add it here. We currently
                // we don't want it when only showing own properties.
                if (object.__proto__ && Obj.hasProperties(object.__proto__) &&
                    properties.indexOf("__proto__") === -1 && !ownOnly)
                {
                    properties.push("__proto__");
                }
            }
            catch (exc)
            {
                if (FBTrace.DBG_ERRORS || FBTrace.DBG_DOM)
                    FBTrace.sysout("dom.getMembers: property lookups failed", exc);
            }

            var name, val;
            var add = function(type, where)
            {
                this.addMember(object, type, where, name, val, level, isScope);
            }.bind(this);

            for (var i=0; i<properties.length; i++)
            {
                name = properties[i];

                // Ignore only global variables (properties of the |window| object).
                if (Wrapper.shouldIgnore(name) && (object instanceof Window))
                {
                    if (FBTrace.DBG_DOM)
                    {
                        FBTrace.sysout("dom.getMembers: Wrapper.ignoreVars: " + name + ", " +
                            level, object);
                    }
                    continue;
                }

                try
                {
                    val = object[name];
                }
                catch (exc)
                {
                    // Sometimes we get exceptions trying to access certain members
                    if (FBTrace.DBG_ERRORS && FBTrace.DBG_DOM)
                        FBTrace.sysout("dom.getMembers cannot access "+name, exc);

                    val = undefined;
                }

                if (!isNaN(parseInt(name, 10)))
                {
                    add("ordinal", ordinals);
                }
                else if (typeof val === "function")
                {
                    var classFunc = isClassFunction(val);
                    var domMember = Dom.isDOMMember(object, name);
                    if (domMember && classFunc)
                    {
                        add("domClass", domClasses);
                    }
                    else if (domMember)
                    {
                        add("domFunction", domFuncs);
                    }
                    else if (classFunc)
                    {
                        add("userClass", userClasses);
                    }
                    else if (!Firebug.showUserFuncs && Firebug.showInlineEventHandlers &&
                        Dom.isInlineEventHandler(name))
                    {
                        add("userFunction", domHandlers);
                    }
                    else
                    {
                        add("userFunction", userFuncs);
                    }
                }
                else
                {
                    if (isPrototype(name))
                    {
                        add("proto", proto);
                    }
                    else if (Dom.isDOMMember(object, name))
                    {
                        add("dom", domProps);
                    }
                    else if (Dom.isDOMConstant(object, name))
                    {
                        add("dom", domConstants);
                    }
                    else if (val === null && object instanceof EventTarget &&
                        Dom.isInlineEventHandler(name))
                    {
                        add("user", domHandlers);
                    }
                    else
                    {
                        add("user", userProps);
                    }
                }
            }

            if (isScope || (typeof object === "function" && Firebug.showClosures && this.context))
            {
                this.maybeAddClosureMember(object, "proto", proto, level, isScope);
            }
        }
        catch (exc)
        {
            // Sometimes we get exceptions just from trying to iterate the members
            // of certain objects, like StorageList, but don't let that gum up the works
            if (FBTrace.DBG_DOM)
                FBTrace.sysout("dom.getMembers FAILS: ", exc);
        }

        function sortName(a, b) { return a.name > b.name ? 1 : -1; }
        function sortOrdinal(a, b) { return a.name - b.name; }

        var members = [];

        ordinals.sort(sortOrdinal);
        members.push.apply(members, ordinals);

        if (Firebug.showUserProps)
        {
            userProps.sort(sortName);
            members.push.apply(members, userProps);
        }

        if (Firebug.showUserFuncs)
        {
            userClasses.sort(sortName);
            members.push.apply(members, userClasses);

            userFuncs.sort(sortName);
            members.push.apply(members, userFuncs);
        }

        if (Firebug.showDOMProps)
        {
            domProps.sort(sortName);
            members.push.apply(members, domProps);
        }

        if (Firebug.showDOMFuncs)
        {
            domClasses.sort(sortName);
            members.push.apply(members, domClasses);

            domFuncs.sort(sortName);
            members.push.apply(members, domFuncs);
        }

        if (Firebug.showDOMConstants)
            members.push.apply(members, domConstants);

        members.push.apply(members, proto);

        if (Firebug.showInlineEventHandlers)
        {
            domHandlers.sort(sortName);
            members.push.apply(members, domHandlers);
        }

        if (FBTrace.DBG_DOM)
        {
            var showEnum = Firebug.showEnumerableProperties;
            var showOwn = Firebug.showOwnProperties;
            FBTrace.sysout("dom.getMembers; Report: enum-only: " + showEnum +
                ", own-only: " + showOwn,
            {
                object: object,
                ordinals: ordinals,
                userProps: userProps,
                userFuncs: userFuncs,
                userClasses: userClasses,
                domProps: domProps,
                domFuncs: domFuncs,
                domConstants: domConstants,
                domHandlers: domHandlers,
                proto: proto
            });
        }

        return members;
    },

    addMember: function()
    {
        try
        {
            return this.addMemberInternal.apply(this, arguments);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("domPanel.addMember; EXCEPTION " + err, err);
        }
    },

    addMemberInternal: function(object, type, props, name, value, level, parentIsScope)
    {
        // Do this first in case a call to instanceof (= QI, for XPCOM things) reveals contents.
        var rep = Firebug.getRep(value);
        var tag = rep.shortTag ? rep.shortTag : rep.tag;

        var hasProperties = Obj.hasProperties(value, !Firebug.showEnumerableProperties,
            Firebug.showOwnProperties);

        var valueType = typeof value;
        var hasChildren = hasProperties && !(value instanceof FirebugReps.ErrorCopy) &&
            ((valueType === "function") ||
             (valueType === "object" && value !== null));

        // Special case for closure inspection.
        if (!hasChildren && valueType === "function" && Firebug.showClosures && this.context)
        {
            try
            {
                var win = this.context.getCurrentGlobal();
                ClosureInspector.withEnvironmentForObject(win, value, this.context, function(env)
                {
                    hasChildren = true;
                });
            }
            catch (e) {}
        }

        // Special case for "arguments", which is not enumerable by for...in statement
        // and so, Obj.hasProperties always returns false.
        hasChildren = hasChildren || (!!value && isArguments(value) && value.length > 0);

        if (valueType === "function" && !hasChildren)
        {
            try
            {
                // Special case for functions with a prototype that has values
                var proto = value.prototype;
                if (proto)
                {
                    hasChildren = Obj.hasProperties(proto, !Firebug.showEnumerableProperties,
                        Firebug.showOwnProperties);
                }
            }
            catch (exc) {}
        }

        var descriptor = getPropertyDescriptor(object, name);
        if (!descriptor)
        {
            // xxxHonza: temporary tracing.
            TraceError.sysout("domMemberProvider.addMemberInternal; ERROR no descriptor for" +
                name, object);
        }

        var member = {
            object: object,
            name: name,
            value: value,
            type: type,
            rowClass: "memberRow-" + type,
            open: "",
            level: level,
            indent: level * 16,
            hasChildren: hasChildren,
            tag: tag,
            prefix: "",
            descriptor: descriptor,
            readOnly: (descriptor && !descriptor.writable && !descriptor.set),
            // XXX should probably move the tests from getContextMenuItems here
            deletable: (!parentIsScope && !(descriptor && !descriptor.configurable))
        };

        // The context doesn't have to be specified (e.g. in case of Watch panel that is based
        // on the same template as the DOM panel, but doesn't show any breakpoints).
        if (this.context)
        {
            // xxxHonza: Support for object change not implemented yet.
            member.breakable = !hasChildren && !parentIsScope;

            var breakpoints = this.context.dom.breakpoints;
            var bp = breakpoints.findBreakpoint(object, name);

            if (bp)
            {
                member.breakpoint = true;
                member.disabledBreakpoint = !bp.checked;
            }
        }

        if (parentIsScope)
            member.scopeNameTooltip = Locale.$STRF("dom.tip.scopeMemberName", ["%" + name]);

        // Set prefix for user defined properties. This prefix help the user to distinguish
        // among simple properties and those defined using getter and/or (only a) setter.
        // XXX This should be rewritten to use 'descriptor', and the unwrapping test is
        // always false! See issue 5377.
        if (object && !Dom.isDOMMember(object, name) && (XPCNativeWrapper.unwrap(object) !== object))
        {
            var getter = (object.__lookupGetter__) ? object.__lookupGetter__(name) : null;
            var setter = (object.__lookupSetter__) ? object.__lookupSetter__(name) : null;

            // both, getter and setter
            if (getter && setter)
                member.type = "userFunction";

            // only getter
            if (getter && !setter)
            {
                member.readOnly = true;
                member.prefix = "get";
            }

            // only setter
            if (!getter && setter)
            {
                member.prefix = "set";
            }
        }

        props.push(member);
        return member;
    },

    // Add the magic "(closure)" property.
    maybeAddClosureMember: function(object, type, props, level, isScope)
    {
        var win = this.context.getCurrentGlobal();
        var wrapper = ClosureInspector.getScopeWrapper(object, win, this.context, isScope);
        if (!wrapper)
            return;

        var name = (isScope ? Locale.$STR("dom.scopeParentName") : Locale.$STR("dom.scopeName"));
        var title = (isScope ? undefined : Locale.$STR("dom.tip.scopeName"));
        var rep = Firebug.getRep(wrapper);
        var tag = rep.shortTag ? rep.shortTag : rep.tag;

        var member = {
            object: object,
            name: name,
            value: wrapper,
            type: type,
            rowClass: "memberRow-" + type,
            open: "",
            level: level,
            indent: level*16,
            hasChildren: true,
            tag: tag,
            prefix: "",
            title: title,
            readOnly: true,
            deletable: false,
            ignoredPath: true
        };
        props.push(member);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Object properties

    /**
     * Returns a list of properties available on an object, filtered on enumerability and prototype
     * chain position. Due to prototype traversal, some property names may appear several times.
     *
     * @param {Object} object The object we want to get the list of properties for.
     * @param {Boolean} enumerableOnly If set to true, only enumerable properties are returned.
     * @param {Boolean} ownOnly If set to true, only own properties (not those from the
     *      prototype chain) are returned.
     */
    getObjectProperties: function(object, enumerableOnly, ownOnly)
    {
        var props = [];

        // Get all enumerable-only or all-properties of the object (but not inherited).
        if (enumerableOnly)
            props = Object.keys(object);
        else
            props = Object.getOwnPropertyNames(object);

        // Not interested in inherited properties, bail out.
        if (ownOnly)
            return props;

        // Climb the prototype chain.
        var inheritedProps = [];
        var parent = Object.getPrototypeOf(object);
        if (parent)
            inheritedProps = this.getObjectProperties(parent, enumerableOnly, ownOnly);

        // Push everything onto the returned array, to avoid O(nm) runtime behavior.
        inheritedProps.push.apply(inheritedProps, props);
        return inheritedProps;
    },
}

// ********************************************************************************************* //
// Helpers

function isArguments(obj)
{
    return Object.prototype.toString.call(obj) === "[object Arguments]";
}

function isClassFunction(fn)
{
    try
    {
        for (var name in fn.prototype)
            return true;
    }
    catch (exc)
    {
    }

    return false;
}

function isPrototype(name)
{
    return (name === "prototype" || name === "__proto__");
}

function getPropertyDescriptor(object, propName)
{
    try
    {
        var desc;
        while (object)
        {
            desc = Object.getOwnPropertyDescriptor(object, propName);
            if (desc)
                return desc;
            object = Object.getPrototypeOf(object);
        }
    }
    catch (e)
    {
    }
    return undefined;
}

// ********************************************************************************************* //
// Registration

return DOMMemberProvider;

// ********************************************************************************************* //
});
<commit_msg>Split the hasChildren check in domMemberProvider.addMember into a separate function<commit_after>/* See license.txt for terms of usage */
/*jshint esnext:true, es5:true, curly:false */
/*global FBTrace:true, XPCNativeWrapper:true, Window:true, define:true */

define([
    "firebug/firebug",
    "firebug/lib/trace",
    "firebug/lib/object",
    "firebug/lib/array",
    "firebug/lib/wrapper",
    "firebug/lib/dom",
    "firebug/lib/locale",
    "firebug/console/closureInspector",
    "firebug/chrome/reps",
],
function(Firebug, FBTrace, Obj, Arr, Wrapper, Dom, Locale, ClosureInspector, FirebugReps) {

// ********************************************************************************************* //
// Constants

var Trace = FBTrace.to("DBG_DOM");
var TraceError = FBTrace.to("DBG_ERRORS");

// ********************************************************************************************* //
// DOM Member Provider

function DOMMemberProvider(context)
{
    this.context = context;
}

DOMMemberProvider.prototype =
{
    /**
     * @param object a user-level object wrapped in security blanket
     * @param level for a.b.c, level is 2
     */
    getMembers: function(object, level)
    {
        if (!level)
            level = 0;

        var ordinals = [];
        var userProps = [];
        var userClasses = [];
        var userFuncs = [];
        var domProps = [];
        var domClasses = [];
        var domFuncs = [];
        var domConstants = [];
        var proto = [];
        var domHandlers = [];

        var isScope = ClosureInspector.isScopeWrapper(object);

        try
        {
            // Special case for "arguments", which is not enumerable by for...in statement.
            if (isArguments(object))
                object = Arr.cloneArray(object);

            var properties;
            try
            {
                // Make sure not to touch the prototype chain of the magic scope objects.
                var ownOnly = Firebug.showOwnProperties || isScope;
                var enumerableOnly = Firebug.showEnumerableProperties;

                properties = this.getObjectProperties(object, enumerableOnly, ownOnly);
                properties = Arr.sortUnique(properties);

                var addOwn = function(prop)
                {
                    // Apparently, Object.prototype.hasOwnProperty.call(object, p) lies
                    // when 'object' is content and 'Object' is chrome... Bug 658909?
                    if (Object.getOwnPropertyDescriptor(object, prop) &&
                        properties.indexOf(prop) === -1)
                    {
                        properties.push(prop);
                    }
                };
                addOwn("constructor");
                addOwn("prototype");
                addOwn("wrappedJSObject");

                // __proto__ never shows in enumerations, so add it here. We currently
                // we don't want it when only showing own properties.
                if (object.__proto__ && Obj.hasProperties(object.__proto__) &&
                    properties.indexOf("__proto__") === -1 && !ownOnly)
                {
                    properties.push("__proto__");
                }
            }
            catch (exc)
            {
                if (FBTrace.DBG_ERRORS || FBTrace.DBG_DOM)
                    FBTrace.sysout("dom.getMembers: property lookups failed", exc);
            }

            var name, val;
            var add = function(type, where)
            {
                this.addMember(object, type, where, name, val, level, isScope);
            }.bind(this);

            for (var i=0; i<properties.length; i++)
            {
                name = properties[i];

                // Ignore only global variables (properties of the |window| object).
                if (Wrapper.shouldIgnore(name) && (object instanceof Window))
                {
                    if (FBTrace.DBG_DOM)
                    {
                        FBTrace.sysout("dom.getMembers: Wrapper.ignoreVars: " + name + ", " +
                            level, object);
                    }
                    continue;
                }

                try
                {
                    val = object[name];
                }
                catch (exc)
                {
                    // Sometimes we get exceptions trying to access certain members
                    if (FBTrace.DBG_ERRORS && FBTrace.DBG_DOM)
                        FBTrace.sysout("dom.getMembers cannot access "+name, exc);

                    val = undefined;
                }

                if (!isNaN(parseInt(name, 10)))
                {
                    add("ordinal", ordinals);
                }
                else if (typeof val === "function")
                {
                    var classFunc = isClassFunction(val);
                    var domMember = Dom.isDOMMember(object, name);
                    if (domMember && classFunc)
                    {
                        add("domClass", domClasses);
                    }
                    else if (domMember)
                    {
                        add("domFunction", domFuncs);
                    }
                    else if (classFunc)
                    {
                        add("userClass", userClasses);
                    }
                    else if (!Firebug.showUserFuncs && Firebug.showInlineEventHandlers &&
                        Dom.isInlineEventHandler(name))
                    {
                        add("userFunction", domHandlers);
                    }
                    else
                    {
                        add("userFunction", userFuncs);
                    }
                }
                else
                {
                    if (isPrototype(name))
                    {
                        add("proto", proto);
                    }
                    else if (Dom.isDOMMember(object, name))
                    {
                        add("dom", domProps);
                    }
                    else if (Dom.isDOMConstant(object, name))
                    {
                        add("dom", domConstants);
                    }
                    else if (val === null && object instanceof EventTarget &&
                        Dom.isInlineEventHandler(name))
                    {
                        add("user", domHandlers);
                    }
                    else
                    {
                        add("user", userProps);
                    }
                }
            }

            if (isScope || (typeof object === "function" && Firebug.showClosures && this.context))
            {
                this.maybeAddClosureMember(object, "proto", proto, level, isScope);
            }
        }
        catch (exc)
        {
            // Sometimes we get exceptions just from trying to iterate the members
            // of certain objects, like StorageList, but don't let that gum up the works
            if (FBTrace.DBG_DOM)
                FBTrace.sysout("dom.getMembers FAILS: ", exc);
        }

        function sortName(a, b) { return a.name > b.name ? 1 : -1; }
        function sortOrdinal(a, b) { return a.name - b.name; }

        var members = [];

        ordinals.sort(sortOrdinal);
        members.push.apply(members, ordinals);

        if (Firebug.showUserProps)
        {
            userProps.sort(sortName);
            members.push.apply(members, userProps);
        }

        if (Firebug.showUserFuncs)
        {
            userClasses.sort(sortName);
            members.push.apply(members, userClasses);

            userFuncs.sort(sortName);
            members.push.apply(members, userFuncs);
        }

        if (Firebug.showDOMProps)
        {
            domProps.sort(sortName);
            members.push.apply(members, domProps);
        }

        if (Firebug.showDOMFuncs)
        {
            domClasses.sort(sortName);
            members.push.apply(members, domClasses);

            domFuncs.sort(sortName);
            members.push.apply(members, domFuncs);
        }

        if (Firebug.showDOMConstants)
            members.push.apply(members, domConstants);

        members.push.apply(members, proto);

        if (Firebug.showInlineEventHandlers)
        {
            domHandlers.sort(sortName);
            members.push.apply(members, domHandlers);
        }

        if (FBTrace.DBG_DOM)
        {
            var showEnum = Firebug.showEnumerableProperties;
            var showOwn = Firebug.showOwnProperties;
            FBTrace.sysout("dom.getMembers; Report: enum-only: " + showEnum +
                ", own-only: " + showOwn,
            {
                object: object,
                ordinals: ordinals,
                userProps: userProps,
                userFuncs: userFuncs,
                userClasses: userClasses,
                domProps: domProps,
                domFuncs: domFuncs,
                domConstants: domConstants,
                domHandlers: domHandlers,
                proto: proto
            });
        }

        return members;
    },

    addMember: function()
    {
        try
        {
            return this.addMemberInternal.apply(this, arguments);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("domPanel.addMember; EXCEPTION " + err, err);
        }
    },

    hasChildren: function(value)
    {
        if (!value || (typeof value !== "object" && typeof value !== "function"))
            return false;

        if (value instanceof FirebugReps.ErrorCopy)
            return false;

        var enumerableOnly = Firebug.showEnumerableProperties;
        var ownOnly = Firebug.showOwnProperties;
        if (Obj.hasProperties(value, !enumerableOnly, ownOnly))
            return true;

        // Special case for "arguments", which is not enumerable by for...in statement
        // and so, Obj.hasProperties always returns false.
        // XXX(simon): This doesn't seem to be required any more (Fx28).
        if (isArguments(value) && value.length > 0)
            return true;

        if (typeof value === "function")
        {
            // Special case for functions with a prototype that has values.
            try
            {
                var proto = value.prototype;
                if (proto && Obj.hasProperties(proto, !enumerableOnly, ownOnly))
                    return true;
            }
            catch (exc) {}
        }

        // Special case for closure inspection.
        if (typeof value === "function" && Firebug.showClosures && this.context)
        {
            try
            {
                var ret = false;
                var win = this.context.getCurrentGlobal();
                ClosureInspector.withEnvironmentForObject(win, value, this.context, function(env)
                {
                    ret = true;
                });

                if (ret)
                    return ret;
            }
            catch (e) {}
        }

        return false;
    },

    addMemberInternal: function(object, type, props, name, value, level, parentIsScope)
    {
        // Do this first in case a call to instanceof (= QI, for XPCOM things) reveals contents.
        var rep = Firebug.getRep(value);
        var tag = rep.shortTag ? rep.shortTag : rep.tag;

        var hasChildren = this.hasChildren(value);

        var descriptor = getPropertyDescriptor(object, name);
        if (!descriptor)
        {
            // xxxHonza: temporary tracing.
            TraceError.sysout("domMemberProvider.addMemberInternal; ERROR no descriptor for" +
                name, object);
        }

        var member = {
            object: object,
            name: name,
            value: value,
            type: type,
            rowClass: "memberRow-" + type,
            open: "",
            level: level,
            indent: level * 16,
            hasChildren: hasChildren,
            tag: tag,
            prefix: "",
            descriptor: descriptor,
            readOnly: (descriptor && !descriptor.writable && !descriptor.set),
            // XXX should probably move the tests from getContextMenuItems here
            deletable: (!parentIsScope && !(descriptor && !descriptor.configurable))
        };

        // The context doesn't have to be specified (e.g. in case of Watch panel that is based
        // on the same template as the DOM panel, but doesn't show any breakpoints).
        if (this.context)
        {
            // xxxHonza: Support for object change not implemented yet.
            member.breakable = !hasChildren && !parentIsScope;

            var breakpoints = this.context.dom.breakpoints;
            var bp = breakpoints.findBreakpoint(object, name);

            if (bp)
            {
                member.breakpoint = true;
                member.disabledBreakpoint = !bp.checked;
            }
        }

        if (parentIsScope)
            member.scopeNameTooltip = Locale.$STRF("dom.tip.scopeMemberName", ["%" + name]);

        // Set prefix for user defined properties. This prefix help the user to distinguish
        // among simple properties and those defined using getter and/or (only a) setter.
        // XXX This should be rewritten to use 'descriptor', and the unwrapping test is
        // always false! See issue 5377.
        if (object && !Dom.isDOMMember(object, name) && (XPCNativeWrapper.unwrap(object) !== object))
        {
            var getter = (object.__lookupGetter__) ? object.__lookupGetter__(name) : null;
            var setter = (object.__lookupSetter__) ? object.__lookupSetter__(name) : null;

            // both, getter and setter
            if (getter && setter)
                member.type = "userFunction";

            // only getter
            if (getter && !setter)
            {
                member.readOnly = true;
                member.prefix = "get";
            }

            // only setter
            if (!getter && setter)
            {
                member.prefix = "set";
            }
        }

        props.push(member);
        return member;
    },

    // Add the magic "(closure)" property.
    maybeAddClosureMember: function(object, type, props, level, isScope)
    {
        var win = this.context.getCurrentGlobal();
        var wrapper = ClosureInspector.getScopeWrapper(object, win, this.context, isScope);
        if (!wrapper)
            return;

        var name = (isScope ? Locale.$STR("dom.scopeParentName") : Locale.$STR("dom.scopeName"));
        var title = (isScope ? undefined : Locale.$STR("dom.tip.scopeName"));
        var rep = Firebug.getRep(wrapper);
        var tag = rep.shortTag ? rep.shortTag : rep.tag;

        var member = {
            object: object,
            name: name,
            value: wrapper,
            type: type,
            rowClass: "memberRow-" + type,
            open: "",
            level: level,
            indent: level*16,
            hasChildren: true,
            tag: tag,
            prefix: "",
            title: title,
            readOnly: true,
            deletable: false,
            ignoredPath: true
        };
        props.push(member);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Object properties

    /**
     * Returns a list of properties available on an object, filtered on enumerability and prototype
     * chain position. Due to prototype traversal, some property names may appear several times.
     *
     * @param {Object} object The object we want to get the list of properties for.
     * @param {Boolean} enumerableOnly If set to true, only enumerable properties are returned.
     * @param {Boolean} ownOnly If set to true, only own properties (not those from the
     *      prototype chain) are returned.
     */
    getObjectProperties: function(object, enumerableOnly, ownOnly)
    {
        var props = [];

        // Get all enumerable-only or all-properties of the object (but not inherited).
        if (enumerableOnly)
            props = Object.keys(object);
        else
            props = Object.getOwnPropertyNames(object);

        // Not interested in inherited properties, bail out.
        if (ownOnly)
            return props;

        // Climb the prototype chain.
        var inheritedProps = [];
        var parent = Object.getPrototypeOf(object);
        if (parent)
            inheritedProps = this.getObjectProperties(parent, enumerableOnly, ownOnly);

        // Push everything onto the returned array, to avoid O(nm) runtime behavior.
        inheritedProps.push.apply(inheritedProps, props);
        return inheritedProps;
    },
}

// ********************************************************************************************* //
// Helpers

function isArguments(obj)
{
    return Object.prototype.toString.call(obj) === "[object Arguments]";
}

function isClassFunction(fn)
{
    try
    {
        for (var name in fn.prototype)
            return true;
    }
    catch (exc)
    {
    }

    return false;
}

function isPrototype(name)
{
    return (name === "prototype" || name === "__proto__");
}

function getPropertyDescriptor(object, propName)
{
    try
    {
        var desc;
        while (object)
        {
            desc = Object.getOwnPropertyDescriptor(object, propName);
            if (desc)
                return desc;
            object = Object.getPrototypeOf(object);
        }
    }
    catch (e)
    {
    }
    return undefined;
}

// ********************************************************************************************* //
// Registration

return DOMMemberProvider;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>module.exports = function(slapp) {
  var request = require('request')
  var url = 'https://www.foaas.com/thanks/nick'

  var headers = {
      'User-Agent':       'Super Agent/0.0.1',
      'Content-Type':     'application/x-www-form-urlencoded'
  }

  var options = {
    url: url,
    method: 'POST',
    form: {'Accept':'application/json'}
  }

  function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
          // Print out the response body
          var result = JSON.parse(body)
          var message = result.message
          var subtitle = result.subtitle
          console.log('message:' + message)
          console.log('subtitle:' + subtitle)
      }
  }

  var regex = '.*'
  var location = 'ambient'

  slapp.
    message(regex,location, (msg) => {
      request(options, callback)
    })
// attempt to re-build
}
<commit_msg>logging is broken so using msg.say<commit_after>module.exports = function(slapp) {
  var request = require('request')
  var url = 'https://www.foaas.com/thanks/nick'

  var headers = {
      'User-Agent':       'Super Agent/0.0.1',
      'Content-Type':     'application/x-www-form-urlencoded'
  }

  var options = {
    url: url,
    method: 'POST',
    form: {'Accept':'application/json'}
  }

  function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
          // Print out the response body
          var result = JSON.parse(body)
          var message = result.message
          var subtitle = result.subtitle
          console.log('message:' + message)
          console.log('subtitle:' + subtitle)
          return message
      }
  }

  var regex = '.*'
  var location = 'ambient'

  slapp.
    message(regex,location, (msg) => {
      msg.say(
        request(options, callback)
      )
    })
// attempt to re-build
}
<|endoftext|>


<commit_before>/*
 * Copyright © 2015 Cask Data, Inc.
 *
 * 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.
 */

angular.module(PKG.name + '.feature.admin')
  .controller('NamespaceSettingsController', function ($scope, MyCDAPDataSource, $state, $alert, $timeout, myNamespace, EventPipe) {

    var dataSrc = new MyCDAPDataSource($scope);
    $scope.loading = false;

    dataSrc.request({
      _cdapPath: '/namespaces/' + $state.params.nsadmin
    })
    .then(function (res) {
      $scope.description = res.description;
    });

    $scope.save = function() {

      dataSrc.request({
        _cdapPath: '/namespaces/' + $state.params.nsadmin + '/properties',
        method: 'PUT',
        body: {
          'description': $scope.description
        }
      })
      .then(function () {
        $alert({
          type: 'success',
          content: 'Namespace successfully updated'
        });
      });

    };

    $scope.deleteNamespace = function() {
      $scope.loading = true;
      EventPipe.emit('showLoadingIcon');

      dataSrc.request({
        _cdapPath: '/unrecoverable/namespaces/' + $state.params.nsadmin,
        method: 'DELETE'
      })
      .then(function () {
        myNamespace.getList(true).then(function() {
          EventPipe.emit('namespace.update');
        });

        $timeout(function() {
          EventPipe.emit('hideLoadingIcon.immediate');

          $state.go('admin.overview', {}, {reload: true});
          $alert({
            type: 'success',
          });
        }, 500);
      }, function error() {
        EventPipe.emit('hideLoadingIcon.immediate');
      });
    };

  });
<commit_msg>Reversing deleting of message.<commit_after>/*
 * Copyright © 2015 Cask Data, Inc.
 *
 * 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.
 */

angular.module(PKG.name + '.feature.admin')
  .controller('NamespaceSettingsController', function ($scope, MyCDAPDataSource, $state, $alert, $timeout, myNamespace, EventPipe) {

    var dataSrc = new MyCDAPDataSource($scope);
    $scope.loading = false;

    dataSrc.request({
      _cdapPath: '/namespaces/' + $state.params.nsadmin
    })
    .then(function (res) {
      $scope.description = res.description;
    });

    $scope.save = function() {

      dataSrc.request({
        _cdapPath: '/namespaces/' + $state.params.nsadmin + '/properties',
        method: 'PUT',
        body: {
          'description': $scope.description
        }
      })
      .then(function () {
        $alert({
          type: 'success',
          content: 'Namespace successfully updated'
        });
      });

    };

    $scope.deleteNamespace = function() {
      $scope.loading = true;
      EventPipe.emit('showLoadingIcon');

      dataSrc.request({
        _cdapPath: '/unrecoverable/namespaces/' + $state.params.nsadmin,
        method: 'DELETE'
      })
      .then(function () {
        myNamespace.getList(true).then(function() {
          EventPipe.emit('namespace.update');
        });

        $timeout(function() {
          EventPipe.emit('hideLoadingIcon.immediate');

          $state.go('admin.overview', {}, {reload: true});
          $alert({
            type: 'success',
            content: 'You have successfully deleted a namespace'
          });
        }, 500);
      }, function error() {
        EventPipe.emit('hideLoadingIcon.immediate');
      });
    };

  });
<|endoftext|>


<commit_before>function LODnode() {
}

LODnode.prototype.create = function create( inX, inY, inSize, inLevel ) {
	this.x = inX;
	this.y = inY;
	this.centerX = inX + inSize * 0.5;
	this.centerY = inY + inSize * 0.5;
	this.size = inSize;
	this.level = inLevel;
	this.height = 0;
	this.childs = [];

	if( 0 === inLevel ) {
		// If we are a leaf, stop the creation process
	}
	else {
		// Else, create childs
		var childSize = inSize * 0.5;

		for( var i = 0; i < 2; ++i ) {
			for( var j = 0; j < 2; ++j ) {
				var child = new LODnode();

				child.create( inX + childSize * j, inY + childSize * i, childSize, inLevel - 1 );

				this.childs[j * 2 + i] = child;
			}
		}
	}
}

LODnode.prototype.intersectsSphere = function intersectsSphere( inRange, inPosition ) {
	var xp = this.centerX;
	var yp = this.height;
	var zp = this.centerY;

	var distance = Math.sqrt(
		(inPosition.x - xp) * (inPosition.x - xp) +
		(inPosition.z - yp) * (inPosition.z - yp) +
		(inPosition.y - zp) * (inPosition.y - zp)
	);

	//console.log( distance + " " + inRange );
	return ( distance - this.size * 0.5 ) < inRange;
}

LODnode.prototype.frustumIntersect = function frustumIntersect( inFrustum ) {
	return true ;
}

LODnode.prototype.select = function select( inRanges, inFrustum, inPosition, outSelection ) {

	if( !this.intersectsSphere( inRanges[ this.level ], inPosition ) ) {
		// No node or child nodes were selected; return false so that our parent node handles our area
		//console.log("!this.intersectsSphere level");
		return false;
	}

	if( !this.frustumIntersect( inFrustum ) ) {
		/* We are out of frustum, select nothing but return true to mark this node as having been
		   correctly handled so that our parent node does not select itself over our area */
		//console.log("frustumIntersect");
		return true;
	}

	if( 0 === this.level ) {
		// We are in our LOD range and we are the last LOD level
		//console.log("0 === this.level");
		outSelection.add( this );
		return true;
	}
	else {
		if( !this.intersectsSphere( inRanges[this.level-1], inPosition ) ) {
			/* We are in range of our LOD level and we are not the last level: if we are also in range
			   of a more detailed LOD level, then some of our child nodes will need to be selected
			   instead in order to display a more detailed mesh.
			   We cover the required lodLevel range */
			outSelection.nodes.push( this );
		}
		else {
			/* We cover the more detailed lodLevel range: some or all of our four child nodes will
			   have to be selected instead */
			for( var key in this.childs ) {
				var childNode = this.childs[key];
				if( !childNode.select( inRanges, inFrustum, inPosition, outSelection ) ) {
					//console.log("childNode.select?");
					outSelection.add( this, childNode.x, childNode.y, true );
				}
			}
		}

		return true;
	}

};<commit_msg>Review code organization<commit_after><|endoftext|>


<commit_before>import React, {PropTypes, Component} from 'react';
import {connect} from 'react-redux'

import {increase, decrease} from '../actions/count'

class PageTestCounter extends Component {
  static propTypes = {
    number: PropTypes.number.isRequired,
    increase: PropTypes.func.isRequired,
    decrease: PropTypes.func.isRequired
  }

  constructor(props, context) {
    super(props, context);

    this.handleIncreaseClick = this.handleIncreaseClick.bind(this);
    this.handleDecreaseClick = this.handleDecreaseClick.bind(this);
  }

  handleIncreaseClick() {
    this.props.increase(1);
  }

  handleDecreaseClick() {
    this.props.decrease(1);
  }

  render() {
    let {number} = this.props;

    return (

HELLO, index

          Some state changes:
          {number}

          <button onClick={this.handleIncreaseClick}>Increase</button>
          <button onClick={this.handleDecreaseClick}>Decrease</button>

    );
  }
}

const mapStateToProps = (state) => ({
  number: state.count.number
});

const mapDispatchToProps = {increase, decrease};

export default connect(mapStateToProps, mapDispatchToProps)(PageTestCounter);
<commit_msg>counter测试<commit_after>import React, {PropTypes, Component} from 'react';
import {connect} from 'react-redux'

import {increase, decrease} from '../actions/count'

class PageTestCounter extends Component {
  static propTypes = {
    number: PropTypes.number.isRequired,
    increase: PropTypes.func.isRequired,
    decrease: PropTypes.func.isRequired
  }

  constructor(props, context) {
    super(props, context);

    this.handleIncreaseClick = this.handleIncreaseClick.bind(this);
    this.handleDecreaseClick = this.handleDecreaseClick.bind(this);
  }

  handleIncreaseClick() {
    this.props.increase(1);
  }

  handleDecreaseClick() {
    this.props.decrease(1);
  }

  render() {
    let {number} = this.props;

    return (

使用 Redux 实现计数器

参考：

https://github.com/reactjs/redux/tree/master/examples/counter

https://github.com/reactjs/react-router-redux/tree/master/examples/basic

          Some state changes: {number}
          <button onClick={this.handleIncreaseClick}>Increase</button>
          <button onClick={this.handleDecreaseClick}>Decrease</button>

    );
  }
}

const mapStateToProps = (state) => ({
  number: state.count.number
});

const mapDispatchToProps = {increase, decrease};

export default connect(mapStateToProps, mapDispatchToProps)(PageTestCounter);
<|endoftext|>


<commit_before>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redexutil/LICENSE

import assert from 'assert';
import bunyan from 'bunyan';
import lodash from 'lodash';

const DefaultLevel = 'info';
const Levels = ['debug', 'info', 'warn', 'error'];
const ExtraLevels = ['state', 'digest', 'child'];
const AllLevels = Levels.concat(ExtraLevels);
const digestLimit = 100;
const state = {
   limit: 10,
   counters: {},
   logging: {
      error: [],
      warn: [],
      info: [],
      debug: [],
      digest: []
   }
};

function increment(name, prop) {
   prop = name + '.' + prop;
   if (!state.counters[prop]) {
      state.counters[prop] = 0;
   }
   state.counters[prop] += 1;
}

function basename(file) {
   var matcher = file.match(/([^\/]+)\.[a-z]+$/);
   if (matcher) {
      return matcher[1];
   } else {
      return file;
   }
}

module.exports = {
   pub() {
      return Object.assign({}, {counters: state.counters}, state.logging);
   },
   counters() {
      return state.counters;
   },
   create(name, level) {
      name = basename(name);
      level = level || global.loggerLevel || process.env.loggerLevel || DefaultLevel;
      if (lodash.includes(Levels, level)) {
         let logger = bunyan.createLogger({name, level});
         return decorate(logger, name, level);
      } else {
         assert(lodash.includes(ExtraLevels, level), 'level: ' + level);
         return decorate(null, name, level);
      }
   }
};

function logging(logger, name, loggerLevel, context, level, args, count) {
   increment(name, level);
   args = [].slice.call(args); // convert arguments to array
   if (!lodash.isEmpty(context)) {
      if (lodash.isArray(context)) {
         args = context.concat(args);
      }
   }
   if (!state.logging.hasOwnProperty(level)) {
      args.splice(0, 0, 'Invalid level: ' + level);
      level = 'warn';
   }
   if (logger) {
      if (level === 'digest') {
         if (count < digestLimit/10 && count % digestLimit === 0) {
            logger.info('digest', count, ...args);
         }
      } else if (lodash.includes(Levels, level)) {
         if (Levels.indexOf(level) >= Levels.indexOf(loggerLevel)) {
            logger[level].call(logger, ...args);
         }
      } else {

      }
   }
   args.splice(0, 0, name);
   state.logging[level].splice(0, 0, args);
   if (state.logging[level].length > state.limit) { // trim
      state.logging[level].length = state.limit;
   }
}

function decorate(logger, name, level) {
   let count = 0;
   let context = [];
   const those = {
      get name() {
         return name;
      },
      verbose() {
      },
      vdebug() {
      },
      debug() {
         if (level === 'debug') {
            logging(logger, name, level, context, 'debug', arguments);
         }
      },
      info() {
         if (level !== 'warn') {
            logging(logger, name, level, context, 'info', arguments);
         }
      },
      dev() {
         logging(logger, name, level, context, 'warn', arguments);
      },
      dverbose() {
         logging(logger, name, level, context, 'warn', arguments);
      },
      dinfo() {
         logging(logger, name, level, context, 'warn', arguments);
      },
      warn() {
         logging(logger, name, level, context, 'warn', arguments);
      },
      error() {
         logging(logger, name, level, context, 'error', arguments);
      },
      state() {
         logging(logger, name, level, context, 'state', arguments);
      },
      digest() {
         if (level === 'debug') {
            count += 1;
            logging(logger, name, level, context, 'digest', arguments, count);
         }
      },
      context() {
         context = [].slice.call(arguments);
      },
      child() {
         let childName = [name].concat([].slice.call(arguments)).join('.');
         return Loggers.create(childName, level);
      },
      increment(prop) {
         increment(name, prop);
      }
   };
   return those;
}
<commit_msg>logger<commit_after>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redexutil/LICENSE

import assert from 'assert';
import bunyan from 'bunyan';
import lodash from 'lodash';

const DefaultLevel = 'info';
const Levels = ['debug', 'info', 'warn', 'error'];
const ExtraLevels = ['state', 'digest', 'child'];
const AllLevels = Levels.concat(ExtraLevels);
const digestLimit = 100;
const state = {
   limit: 10,
   counters: {},
   logging: {
      error: [],
      warn: [],
      info: [],
      debug: [],
      digest: []
   }
};

function increment(name, prop) {
   prop = name + '.' + prop;
   if (!state.counters[prop]) {
      state.counters[prop] = 0;
   }
   state.counters[prop] += 1;
}

function basename(file) {
   var matcher = file.match(/([^\/]+)\.[a-z]+$/);
   if (matcher) {
      return matcher[1];
   } else {
      return file;
   }
}

module.exports = {
   pub() {
      return Object.assign({}, {counters: state.counters}, state.logging);
   },
   counters() {
      return state.counters;
   },
   create(name, level) {
      name = basename(name);
      level = level || global.loggerLevel || process.env.loggerLevel || DefaultLevel;
      if (lodash.includes(Levels, level)) {
         let logger = bunyan.createLogger({name, level});
         return decorate(logger, name, level);
      } else {
         assert(lodash.includes(ExtraLevels, level), 'level: ' + level);
         return decorate(null, name, level);
      }
   }
};

function logging(logger, name, loggerLevel, context, level, args, count) {
   increment(name, level);
   args = [].slice.call(args); // convert arguments to array
   if (!lodash.isEmpty(context)) {
      if (lodash.isArray(context)) {
         args = context.concat(args);
      }
   }
   if (!state.logging.hasOwnProperty(level)) {
      args.splice(0, 0, 'Invalid level: ' + level);
      level = 'warn';
   }
   if (logger) {
      if (level === 'digest') {
         if (count < digestLimit/10 && count % digestLimit === 0) {
            logger.info('digest', count, ...args);
         }
      } else if (lodash.includes(Levels, level)) {
         if (Levels.indexOf(level) >= Levels.indexOf(loggerLevel)) {
            logger[level].call(logger, ...args);
            if (level === 'error') {
               if (args[0]) {
                  if (lodash.isError(args[0])) {
                     logger[level].call(logger, ...args);
                  }
               }
            }
         }
      } else {
      }
   }
   args.splice(0, 0, name);
   state.logging[level].splice(0, 0, args);
   if (state.logging[level].length > state.limit) { // trim
      state.logging[level].length = state.limit;
   }
}

function decorate(logger, name, level) {
   let count = 0;
   let context = [];
   const those = {
      get name() {
         return name;
      },
      verbose() {
      },
      vdebug() {
      },
      debug() {
         if (level === 'debug') {
            logging(logger, name, level, context, 'debug', arguments);
         }
      },
      info() {
         if (level !== 'warn') {
            logging(logger, name, level, context, 'info', arguments);
         }
      },
      dev() {
         logging(logger, name, level, context, 'warn', arguments);
      },
      dverbose() {
         logging(logger, name, level, context, 'warn', arguments);
      },
      dinfo() {
         logging(logger, name, level, context, 'warn', arguments);
      },
      warn() {
         logging(logger, name, level, context, 'warn', arguments);
      },
      error() {
         logging(logger, name, level, context, 'error', arguments);
      },
      state() {
         logging(logger, name, level, context, 'state', arguments);
      },
      digest() {
         if (level === 'debug') {
            count += 1;
            logging(logger, name, level, context, 'digest', arguments, count);
         }
      },
      context() {
         context = [].slice.call(arguments);
      },
      child() {
         let childName = [name].concat([].slice.call(arguments)).join('.');
         return Loggers.create(childName, level);
      },
      increment(prop) {
         increment(name, prop);
      }
   };
   return those;
}
<|endoftext|>


<commit_before>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016  Khartec Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import {initialiseData, invokeFunction} from "../../../common";
import _ from "lodash";

const bindings = {
    status: '<',
    onCancel: '<',
    onSubmit: '<'
};

const initialState = {
    status: null,
    specDefinition: {
        def: {
            delimiter: ',',
            type: 'DELIMITED'
        }
    },
    specDefFields: {},
    onCancel: () => console.log('psdcp::onCancel'),
    onSubmit: (specDef) => console.log('psdcp::onSubmit', specDef)
};

const allowedTypes= ['DATE', 'DECIMAL', 'INTEGER', 'STRING', 'BOOLEAN'];

const template = require('./physical-spec-definition-create-panel.html');

function attemptSplit(line, position) {
    /* TEST STRINGS
Field1	INTEGER	description for field 1
Field2	DATE	description for field 2
Field 3 and a bit  DECIMAL	fooobaa for the win
Field 4 and a bit, STRING,	more text	, and more
Field 5 and a bit,STRING,desc
     */

    const atoms = _.split(line, /[,\W]+/);
    if (atoms.length > 2) {
        const words = _.chain(atoms)
            .map(w => w.trim())
            .filter(w => w.length > 0)
            .value();
        const typePos = _.findIndex(words, w => _.includes(allowedTypes, w));
        const name =_.join(_.take(words, typePos), " ");
        const type = words[typePos];
        const description = _.join(_.drop(words, typePos + 1), " ");
        return {
            name,
            type,
            description,
            position
        };
    }
}

function parseFieldLine(line = [], position) {
    const fieldData = {
        field: attemptSplit(line, position),
        errors: []
    };
    if (! fieldData.field) {
        fieldData.errors.push('Make sure all three columns: Name, Type and Description are populated');
    } else {
        if (_.isEmpty(fieldData.field.name)) {
            fieldData.errors.push('Name must be defined');
        }

        if (_.isEmpty(fieldData.field.type)) {
            fieldData.errors.push('Type must be defined');
        }

        if (_.isEmpty(fieldData.field.description)) {
            fieldData.errors.push('Description must be defined');
        }

        if (! _.includes(allowedTypes, fieldData.field.type)) {
            fieldData.errors.push('Type is invalid');
        }
    }

    return fieldData;
}

function controller() {
    const vm = initialiseData(this, initialState);

    vm.cancel = () => invokeFunction(vm.onCancel);

    vm.preview = () => {
        vm.specDefFields.hasErrors = false;
        vm.specDefFields.parsedData = [];

        const lines = _.chain(vm.specDefFields.rawData)
            .split('\n')
            .value();

        vm.specDefFields.parsedData = _.map(lines, (line, index) => {
            const fieldData = parseFieldLine(line, index + 1, vm.allowedTypesMap);
            if (fieldData.errors.length > 0) {
                vm.specDefFields.hasErrors = true;
            }
            return fieldData;
        });
        vm.specDefinition.def.status = vm.status;
    };

    vm.submit = () => {
        vm.specDefinition.fields = _.map(vm.specDefFields.parsedData, 'field');
        invokeFunction(vm.onSubmit, vm.specDefinition);
    };
}

const component = {
    controller,
    template,
    bindings
};

export default component;<commit_msg>Spec creation improvements<commit_after>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016  Khartec Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import {initialiseData, invokeFunction} from "../../../common";
import _ from "lodash";

const bindings = {
    status: '<',
    onCancel: '<',
    onSubmit: '<'
};

const initialState = {
    status: null,
    specDefinition: {
        def: {
            delimiter: ',',
            type: 'DELIMITED'
        }
    },
    specDefFields: {},
    onCancel: () => console.log('psdcp::onCancel'),
    onSubmit: (specDef) => console.log('psdcp::onSubmit', specDef)
};

const allowedTypes= ['DATE', 'DECIMAL', 'INTEGER', 'STRING', 'BOOLEAN'];

const template = require('./physical-spec-definition-create-panel.html');

function attemptSplit(line, position) {
    /* TEST STRINGS
Field1	INTEGER	description for field 1
Field2	DATE	description for field 2
Field 3 and a bit  DECIMAL	fooobaa for the win
Field 4 and a bit, STRING,	more text	, and more
Field 5 and a bit,STRING,desc
     */

    const atoms = _.split(line, /[,\W]+/);
    if (atoms.length > 2) {
        const words = _.chain(atoms)
            .map(w => w.trim())
            .filter(w => w.length > 0)
            .value();
        const typePos = _.findIndex(words, w => _.includes(allowedTypes, w));
        const name =_.join(_.take(words, typePos), " ");
        const type = words[typePos];
        const description = _.join(_.drop(words, typePos + 1), " ");
        return {
            name,
            type,
            description,
            position
        };
    }
}

function parseFieldLine(line = [], position) {
    const fieldData = {
        field: attemptSplit(line, position),
        errors: []
    };
    if (! fieldData.field) {
        fieldData.errors.push('Make sure all three columns: Name, Type and Description are populated');
    } else {
        if (_.isEmpty(fieldData.field.name)) {
            fieldData.errors.push('Name must be defined');
        }

        if (_.isEmpty(fieldData.field.type)) {
            fieldData.errors.push('Type must be defined');
        }

        if (_.isEmpty(fieldData.field.description)) {
            fieldData.errors.push('Description must be defined');
        }

        if (! _.includes(allowedTypes, fieldData.field.type)) {
            fieldData.errors.push('Type is invalid');
        }
    }

    return fieldData;
}

function controller() {
    const vm = initialiseData(this, initialState);

    vm.cancel = () => invokeFunction(vm.onCancel);

    vm.preview = () => {
        vm.specDefFields.hasErrors = false;
        vm.specDefFields.parsedData = [];

        const lines = _.chain(vm.specDefFields.rawData)
            .split('\n')
            .value();

        vm.specDefFields.parsedData = _.map(lines, (line, index) => {
            const fieldData = parseFieldLine(line, index + 1);
            if (fieldData.errors.length > 0) {
                vm.specDefFields.hasErrors = true;
            }
            return fieldData;
        });
        vm.specDefinition.def.status = vm.status;
    };

    vm.submit = () => {
        vm.specDefinition.fields = _.map(vm.specDefFields.parsedData, 'field');
        invokeFunction(vm.onSubmit, vm.specDefinition);
    };
}

const component = {
    controller,
    template,
    bindings
};

export default component;<|endoftext|>


<commit_before>(function (module) {
    module.controller('projectListProcess', projectListProcess);
    projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"];

    function projectListProcess(processes, project, $state, mcmodal, $filter) {
        var ctrl = this;

        ctrl.viewProcess = viewProcess;
        ctrl.chooseTemplate = chooseTemplate;

        ctrl.processes = processes;
        ctrl.project = project;
        if (ctrl.processes.length !== 0) {
            ctrl.processes = $filter('orderBy')(ctrl.processes, 'name');
            ctrl.current = ctrl.processes[0];
            $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
        }

        ///////////////////////////////////

        function viewProcess(process) {
            ctrl.current = process;
            $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
        }

        function chooseTemplate() {
            mcmodal.chooseTemplate(ctrl.project);
        }
    }
}(angular.module('materialscommons')));
<commit_msg>Goto create process state when the chooseTemplate modal returns a process.<commit_after>(function (module) {
    module.controller('projectListProcess', projectListProcess);
    projectListProcess.$inject = ["processes", "project", "templates", "$state", "mcmodal", "$filter"];

    function projectListProcess(processes, project, templates, $state, mcmodal, $filter) {
        var ctrl = this;

        ctrl.viewProcess = viewProcess;
        ctrl.chooseTemplate = chooseTemplate;

        ctrl.processes = processes;
        ctrl.project = project;
        if (ctrl.processes.length !== 0) {
            ctrl.processes = $filter('orderBy')(ctrl.processes, 'name');
            ctrl.current = ctrl.processes[0];
            $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
        }

        ///////////////////////////////////

        function viewProcess(process) {
            ctrl.current = process;
            $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
        }

        function chooseTemplate() {
            mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
                $state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
            });
        }
    }
}(angular.module('materialscommons')));
<|endoftext|>