<commit_before>steal('can/util', function (can) {
	// ##string.js
	// _Miscellaneous string utility functions._

	// Several of the methods in this plugin use code adapated from Prototype
	// Prototype JavaScript framework, version 1.6.0.1.
	// © 2005-2007 Sam Stephenson
	var strUndHash = /_|-/,
		strColons = /\=\=/,
		strWords = /([A-Z]+)([A-Z][a-z])/g,
		strLowUp = /([a-z\d])([A-Z])/g,
		strDash = /([a-z\d])([A-Z])/g,
		strReplacer = /\{([^\}]+)\}/g,
		strQuote = /"/g,
		strSingleQuote = /'/g,

	// Returns the `prop` property from `obj`.
	// If `add` is true and `prop` doesn't exist in `obj`, create it as an
	// empty object.
		getNext = function (obj, prop, add) {
			var result = obj[prop];

			if (result === undefined && add === true) { result = obj[prop] = {} }
			return result
		},

	// Returns `true` if the object can have properties (no `null`s).
		isContainer = function (current) {
			return (/^f|^o/).test(typeof current);
		};

	can.extend(can, {
		// Escapes strings for HTML.
		/**
		 * @function can.esc
		 * @parent can.util
		 *
		 * `can.esc(string)` escapes a string for insertion into html.
		 *
		 *     can.esc( "<foo>&<bar>" ) //-> "<foo<&<bar<"
		 */
		esc: function (content) {
			// Convert bad values into empty strings
			var isInvalid = content === null || content === undefined || (isNaN(content) && ("" + content === 'NaN'));
			return ( "" + ( isInvalid ? '' : content ) )
				.replace(/&/g, '&')
				.replace(/</g, '<')
				.replace(/>/g, '>')
				.replace(strQuote, '"')
				.replace(strSingleQuote, "'");
		},

		/**
		 * @function can.getObject
		 * @parent can.util
		 * Gets an object from a string.  It can also modify objects on the
		 * 'object path' by removing or adding properties.
		 *
		 *     Foo = {Bar: {Zar: {"Ted"}}}
		 *     can.getObject("Foo.Bar.Zar") //-> "Ted"
		 *
		 * @param {String} name the name of the object to look for
		 * @param {Array} [roots] an array of root objects to look for the
		 *   name.  If roots is not provided, the window is used.
		 * @param {Boolean} [add] true to add missing objects to
		 *  the path. false to remove found properties. undefined to
		 *  not modify the root object
		 * @return {Object} The object.
		 */
		getObject: function (name, roots, add) {

			// The parts of the name we are looking up
			// `['App','Models','Recipe']`
			var parts = name ? name.split('.') : [],
				length = parts.length,
				current,
				r = 0,
				i, container, rootsLength;

			// Make sure roots is an `array`.
			roots = can.isArray(roots) ? roots : [roots || window];

			rootsLength = roots.length

			if (!length) {
				return roots[0];
			}

			// For each root, mark it as current.
			for (r; r < rootsLength; r++) {
				current = roots[r];
				container = undefined;

				// Walk current to the 2nd to last object or until there
				// is not a container.
				for (i = 0; i < length && isContainer(current); i++) {
					container = current;
					current = getNext(container, parts[i]);
				}

				// If we found property break cycle
				if (container !== undefined && current !== undefined) {
					break
				}
			}

			// Remove property from found container
			if (add === false && current !== undefined) {
				delete container[parts[i - 1]]
			}

			// When adding property add it to the first root
			if (add === true && current === undefined) {
				current = roots[0]

				for (i = 0; i < length && isContainer(current); i++) {
					current = getNext(current, parts[i], true);
				}
			}

			return current;
		},
		// Capitalizes a string.
		/**
		 * @function can.capitalize
		 * @parent can.util.
		 * @description Capitalize the first letter of a string.
		 * @signature `can.capitalize(str)`
		 * @param {String} str The string to capitalize.
		 * @return {String} The string with the first letter capitalized.
		 *
		 *        can.capitalize('candy is fun!'); //-> Returns: 'Candy is fun!'
		 *
		 */
		capitalize: function (s, cache) {
			// Used to make newId.
			return s.charAt(0).toUpperCase() + s.slice(1);
		},

		// Underscores a string.
		/**
		 * @function can.underscore
		 * @parent can.util
		 *
		 * Underscores a string.
		 *
		 *     can.underscore("OneTwo") //-> "one_two"
		 *
		 * @param {String} s
		 * @return {String} the underscored string
		 */
		underscore: function (s) {
			return s
				.replace(strColons, '/')
				.replace(strWords, '$1_$2')
				.replace(strLowUp, '$1_$2')
				.replace(strDash, '_')
				.toLowerCase();
		},
		// Micro-templating.
		/**
		 * @function can.sub
		 * @parent can.util
		 *
		 * Returns a string with {param} replaced values from data.
		 *
		 *     can.sub("foo {bar}",{bar: "far"})
		 *     //-> "foo far"
		 *
		 * @param {String} s The string to replace
		 * @param {Object} data The data to be used to look for properties.  If it's an array, multiple
		 * objects can be used.
		 * @param {Boolean} [remove] if a match is found, remove the property from the object
		 * @return {String} The converted string or `null` if any data to render are `undefined` or `null`
		 */
		sub: function (str, data, remove) {
			var obs = [];

			str = str || '';

			obs.push(str.replace(strReplacer, function (whole, inside) {

				// Convert inside to type.
				var ob = can.getObject(inside, data, remove === true ? false : undefined);

				if (ob == undefined) {//undefined or null
					obs = null;
					return "";
				}

				// If a container, push into objs (which will return objects found).
				if (isContainer(ob) && obs) {
					obs.push(ob);
					return "";
				}

				return "" + ob;
			}));

			return obs === null ? obs : (obs.length <= 1 ? obs[0] : obs);
		},

		// These regex's are used throughout the rest of can, so let's make
		// them available.
		replacer: strReplacer,
		undHash: strUndHash
	});
	return can;
});
<commit_msg>Making null or undefined check more explicit<commit_after>steal('can/util', function (can) {
	// ##string.js
	// _Miscellaneous string utility functions._

	// Several of the methods in this plugin use code adapated from Prototype
	// Prototype JavaScript framework, version 1.6.0.1.
	// © 2005-2007 Sam Stephenson
	var strUndHash = /_|-/,
		strColons = /\=\=/,
		strWords = /([A-Z]+)([A-Z][a-z])/g,
		strLowUp = /([a-z\d])([A-Z])/g,
		strDash = /([a-z\d])([A-Z])/g,
		strReplacer = /\{([^\}]+)\}/g,
		strQuote = /"/g,
		strSingleQuote = /'/g,

	// Returns the `prop` property from `obj`.
	// If `add` is true and `prop` doesn't exist in `obj`, create it as an
	// empty object.
		getNext = function (obj, prop, add) {
			var result = obj[prop];

			if (result === undefined && add === true) { result = obj[prop] = {} }
			return result
		},

	// Returns `true` if the object can have properties (no `null`s).
		isContainer = function (current) {
			return (/^f|^o/).test(typeof current);
		};

	can.extend(can, {
		// Escapes strings for HTML.
		/**
		 * @function can.esc
		 * @parent can.util
		 *
		 * `can.esc(string)` escapes a string for insertion into html.
		 *
		 *     can.esc( "<foo>&<bar>" ) //-> "<foo<&<bar<"
		 */
		esc: function (content) {
			// Convert bad values into empty strings
			var isInvalid = content === null || content === undefined || (isNaN(content) && ("" + content === 'NaN'));
			return ( "" + ( isInvalid ? '' : content ) )
				.replace(/&/g, '&')
				.replace(/</g, '<')
				.replace(/>/g, '>')
				.replace(strQuote, '"')
				.replace(strSingleQuote, "'");
		},

		/**
		 * @function can.getObject
		 * @parent can.util
		 * Gets an object from a string.  It can also modify objects on the
		 * 'object path' by removing or adding properties.
		 *
		 *     Foo = {Bar: {Zar: {"Ted"}}}
		 *     can.getObject("Foo.Bar.Zar") //-> "Ted"
		 *
		 * @param {String} name the name of the object to look for
		 * @param {Array} [roots] an array of root objects to look for the
		 *   name.  If roots is not provided, the window is used.
		 * @param {Boolean} [add] true to add missing objects to
		 *  the path. false to remove found properties. undefined to
		 *  not modify the root object
		 * @return {Object} The object.
		 */
		getObject: function (name, roots, add) {

			// The parts of the name we are looking up
			// `['App','Models','Recipe']`
			var parts = name ? name.split('.') : [],
				length = parts.length,
				current,
				r = 0,
				i, container, rootsLength;

			// Make sure roots is an `array`.
			roots = can.isArray(roots) ? roots : [roots || window];

			rootsLength = roots.length

			if (!length) {
				return roots[0];
			}

			// For each root, mark it as current.
			for (r; r < rootsLength; r++) {
				current = roots[r];
				container = undefined;

				// Walk current to the 2nd to last object or until there
				// is not a container.
				for (i = 0; i < length && isContainer(current); i++) {
					container = current;
					current = getNext(container, parts[i]);
				}

				// If we found property break cycle
				if (container !== undefined && current !== undefined) {
					break
				}
			}

			// Remove property from found container
			if (add === false && current !== undefined) {
				delete container[parts[i - 1]]
			}

			// When adding property add it to the first root
			if (add === true && current === undefined) {
				current = roots[0]

				for (i = 0; i < length && isContainer(current); i++) {
					current = getNext(current, parts[i], true);
				}
			}

			return current;
		},
		// Capitalizes a string.
		/**
		 * @function can.capitalize
		 * @parent can.util.
		 * @description Capitalize the first letter of a string.
		 * @signature `can.capitalize(str)`
		 * @param {String} str The string to capitalize.
		 * @return {String} The string with the first letter capitalized.
		 *
		 *        can.capitalize('candy is fun!'); //-> Returns: 'Candy is fun!'
		 *
		 */
		capitalize: function (s, cache) {
			// Used to make newId.
			return s.charAt(0).toUpperCase() + s.slice(1);
		},

		// Underscores a string.
		/**
		 * @function can.underscore
		 * @parent can.util
		 *
		 * Underscores a string.
		 *
		 *     can.underscore("OneTwo") //-> "one_two"
		 *
		 * @param {String} s
		 * @return {String} the underscored string
		 */
		underscore: function (s) {
			return s
				.replace(strColons, '/')
				.replace(strWords, '$1_$2')
				.replace(strLowUp, '$1_$2')
				.replace(strDash, '_')
				.toLowerCase();
		},
		// Micro-templating.
		/**
		 * @function can.sub
		 * @parent can.util
		 *
		 * Returns a string with {param} replaced values from data.
		 *
		 *     can.sub("foo {bar}",{bar: "far"})
		 *     //-> "foo far"
		 *
		 * @param {String} s The string to replace
		 * @param {Object} data The data to be used to look for properties.  If it's an array, multiple
		 * objects can be used.
		 * @param {Boolean} [remove] if a match is found, remove the property from the object
		 * @return {String} The converted string or `null` if any data to render are `undefined` or `null`
		 */
		sub: function (str, data, remove) {
			var obs = [];

			str = str || '';

			obs.push(str.replace(strReplacer, function (whole, inside) {

				// Convert inside to type.
				var ob = can.getObject(inside, data, remove === true ? false : undefined);

				if (ob === undefined || ob === null) {
					obs = null;
					return "";
				}

				// If a container, push into objs (which will return objects found).
				if (isContainer(ob) && obs) {
					obs.push(ob);
					return "";
				}

				return "" + ob;
			}));

			return obs === null ? obs : (obs.length <= 1 ? obs[0] : obs);
		},

		// These regex's are used throughout the rest of can, so let's make
		// them available.
		replacer: strReplacer,
		undHash: strUndHash
	});
	return can;
});
<|endoftext|>


<commit_before><commit_msg>fix redirecting after deleting a community<commit_after><|endoftext|>


<commit_before>// Copyright 2014 Google Inc. All rights reserved.
//
// 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.

import AxiomError from 'axiom/core/error';

import BaseBinding from 'axiom/bindings/base';

export var FileSystem = function() {
  BaseBinding.call(this, {
    // Create an alias entry.
    alias: {type: 'method', args: ['pathSpecFrom', 'pathSpecTo']},

    // Create an open or execute context.
    createContext: {type: 'method', args: ['contextType', 'pathSpec', 'arg']},

    // Return an array of stat metadata for each entry in a directory.
    list: {type: 'method', args: ['pathSpec']},

    // Make a new directory.
    mkdir: {type: 'method', args: ['pathSpec']},

    // Move an entry from one location to another.
    move: {type: 'method', args: ['pathSpecFrom', 'pathSpecTo']},

    // Get metadata for a path.
    stat: {type: 'method', args: ['pathSpec']},

    // Remove a path.
    unlink: {type: 'method', args: ['pathSpec']},
  });
};

export default FileSystem;

FileSystem.prototype = Object.create(BaseBinding.prototype);

/**
 * Read the entire contents of a file.
 *
 * This is a utility method that creates an OpenContext, uses the read
 * method to read in the entire file (by default) and then discards the
 * open context.
 *
 * By default this will return the data in the dataType preferred by the
 * file. You can request a specific dataType by including it in readArg.
 *
 * @param {string} path The path to read.
 * @param {Object} openArg Additional arguments to pass to the
 *   OpenContext..open() call.
 * @param {Object} readArg Additional arguments to pass to the
 *   OpenContext..read() call.
 */
FileSystem.prototype.readFile = function(path, openArg, readArg) {
  if (!openArg)
    openArg = {};
  openArg.read = true;

  readArg = readArg || {};

  return this.createContext('open', path, openArg).then(
    function(ocx) {
      return ocx.open().then(
        function() {
          return ocx.read(readArg).then(function(result) {
            ocx.closeOk(null);
            return Promise.resolve(result);
          }).catch(function(e) {
            ocx.closeErrorValue(e);
            return Promise.reject(e);
          });
        });
    });
};

/**
 * Write the entire contents of a file.
 *
 * This is a utility method that creates an OpenContext, uses the write
 * method to write the entire file (by default) and then discards the
 * open context.
 *
 * @param {string} path The path to read.
 * @param {Object} openArg Additional arguments to pass to the
 *   OpenContext..open() call.
 * @param {Object} writeArg Additional arguments to pass to the
 *   OpenContext..write() call.
 */
FileSystem.prototype.writeFile = function(path, openArg, writeArg) {
  if (!openArg)
    openArg = {};

  openArg.create = 'true';

  writeArg = writeArg || {};

  return this.createContext('open', path, openArg).then(
    function(ocx) {
      return ocx.open().then(
        function() {
          return ocx.write(writeArg).then(function(result) {
            ocx.closeOk(null);
            return Promise.resolve(result);
          }).catch(function(e) {
            ocx.closeErrorValue(e);
            return Promise.reject(e);
          });
        });
   });
};
<commit_msg>Set write mode by default from writeFile()<commit_after>// Copyright 2014 Google Inc. All rights reserved.
//
// 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.

import AxiomError from 'axiom/core/error';

import BaseBinding from 'axiom/bindings/base';

export var FileSystem = function() {
  BaseBinding.call(this, {
    // Create an alias entry.
    alias: {type: 'method', args: ['pathSpecFrom', 'pathSpecTo']},

    // Create an open or execute context.
    createContext: {type: 'method', args: ['contextType', 'pathSpec', 'arg']},

    // Return an array of stat metadata for each entry in a directory.
    list: {type: 'method', args: ['pathSpec']},

    // Make a new directory.
    mkdir: {type: 'method', args: ['pathSpec']},

    // Move an entry from one location to another.
    move: {type: 'method', args: ['pathSpecFrom', 'pathSpecTo']},

    // Get metadata for a path.
    stat: {type: 'method', args: ['pathSpec']},

    // Remove a path.
    unlink: {type: 'method', args: ['pathSpec']},
  });
};

export default FileSystem;

FileSystem.prototype = Object.create(BaseBinding.prototype);

/**
 * Read the entire contents of a file.
 *
 * This is a utility method that creates an OpenContext, uses the read
 * method to read in the entire file (by default) and then discards the
 * open context.
 *
 * By default this will return the data in the dataType preferred by the
 * file. You can request a specific dataType by including it in readArg.
 *
 * @param {string} path The path to read.
 * @param {Object} openArg Additional arguments to pass to the
 *   OpenContext..open() call.
 * @param {Object} readArg Additional arguments to pass to the
 *   OpenContext..read() call.
 */
FileSystem.prototype.readFile = function(path, openArg, readArg) {
  if (!openArg)
    openArg = {};
  openArg.read = true;

  readArg = readArg || {};

  return this.createContext('open', path, openArg).then(
    function(ocx) {
      return ocx.open().then(
        function() {
          return ocx.read(readArg).then(function(result) {
            ocx.closeOk(null);
            return Promise.resolve(result);
          }).catch(function(e) {
            ocx.closeErrorValue(e);
            return Promise.reject(e);
          });
        });
    });
};

/**
 * Write the entire contents of a file.
 *
 * This is a utility method that creates an OpenContext, uses the write
 * method to write the entire file (by default) and then discards the
 * open context.
 *
 * @param {string} path The path to read.
 * @param {Object} openArg Additional arguments to pass to the
 *   OpenContext..open() call.
 * @param {Object} writeArg Additional arguments to pass to the
 *   OpenContext..write() call.
 */
FileSystem.prototype.writeFile = function(path, openArg, writeArg) {
  if (!openArg)
    openArg = {};

  openArg.write = true;

  writeArg = writeArg || {};

  return this.createContext('open', path, openArg).then(
    function(ocx) {
      return ocx.open().then(
        function() {
          return ocx.write(writeArg).then(function(result) {
            ocx.closeOk(null);
            return Promise.resolve(result);
          }).catch(function(e) {
            ocx.closeErrorValue(e);
            return Promise.reject(e);
          });
        });
   });
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.comics.v2',
  name: 'DAOBrowseControllerView',
  extends: 'foam.u2.View',

  documentation: `
    The inline DAO controller for a collection of instances of a model that can
    switch between multiple views
  `,

  imports: [
    'stack'
  ],

  requires: [
    'foam.comics.v2.DAOBrowserView',
    'foam.u2.borders.CardBorder',
    'foam.u2.layout.Cols',
    'foam.u2.layout.Rows',
    'foam.u2.view.IconChoiceView'
  ],

  css: `
    ^container {
      padding: 32px;
    }

    ^header-container {
      padding-bottom: 32px;
      align-items: center;
    }

    ^browse-title {
      font-size: 36px;
      font-weight: 600;
      line-height: 1.33;
      color: #1e1f21;
    }

    ^altview-container {
      position: absolute;
      right: 0;
      padding: 12px 16px 0 0;
    }
  `,

  properties: [
    {
      class: 'foam.dao.DAOProperty',
      name: 'data'
    },
    {
      class: 'FObjectProperty',
      of: 'foam.comics.v2.DAOControllerConfig',
      name: 'config',
      factory: function() {
        return foam.comics.v2.DAOControllerConfig.create({ dao: this.data });
      }
    },
    {
      class: 'foam.u2.ViewSpecWithJava',
      name: 'browseView',
      expression: function(config$browseViews) {
        return config$browseViews && config$browseViews.length
          ? config$browseViews[0].view
          : this.DAOBrowserView
          ;
      }
    }
  ],
  actions: [
    {
      name: 'create',
      isAvailable: function(config$createEnabled) {
        return config$createEnabled;
      },
      code: function() {
        if ( ! this.stack ) return;
        this.stack.push({
          class: 'foam.comics.v2.DAOCreateView',
          data: this.data.of.create({ mode: 'create' }, this),
          config$: this.config$,
          of: this.data.of
        });
      }
    }
  ],
  methods: [
    function initE() {
    this.SUPER();

    var self = this;

      this.addClass(this.myClass())
      .add(this.slot(function(data, config, config$CRUDActionsAuth$create, config$browseBorder, config$browseViews, config$browseTitle) {
        var createAction = config$CRUDActionsAuth$create
            ? self.CREATE.copyFrom({
              availablePermissions: config$CRUDActionsAuth$create
            })
            : self.CREATE;

        return self.E()
          .start(self.Rows)
            .addClass(self.myClass('container'))
            .start(self.Cols)
              .addClass(self.myClass('header-container'))
              .start()
                .addClass(self.myClass('browse-title'))
                .add(config$browseTitle)
              .end()
              .startContext({data: self}).tag(createAction).endContext()
            .end()
            .start(self.CardBorder)
              .style({ position: 'relative' })
              .start(config$browseBorder)
                .callIf(config$browseViews.length > 1, function() {
                  this
                    .start(self.IconChoiceView, {
                      choices:config$browseViews.map(o => [o.view, o.icon]),
                      data$: self.browseView$
                    })
                      .addClass(self.myClass('altview-container'))
                    .end();
                })
                .add(self.slot(function(browseView) {
                  return self.E().tag(browseView, {data: data, config: config});
                }))
              .end()
            .end()
          .end();
      }));
    }
  ]
});
<commit_msg>Update src/foam/comics/v2/DAOBrowseControllerView.js<commit_after>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.comics.v2',
  name: 'DAOBrowseControllerView',
  extends: 'foam.u2.View',

  documentation: `
    The inline DAO controller for a collection of instances of a model that can
    switch between multiple views
  `,

  imports: [
    'stack'
  ],

  requires: [
    'foam.comics.v2.DAOBrowserView',
    'foam.u2.borders.CardBorder',
    'foam.u2.layout.Cols',
    'foam.u2.layout.Rows',
    'foam.u2.view.IconChoiceView'
  ],

  css: `
    ^container {
      padding: 32px;
    }

    ^header-container {
      padding-bottom: 32px;
      align-items: center;
    }

    ^browse-title {
      font-size: 36px;
      font-weight: 600;
      line-height: 1.33;
      color: #1e1f21;
    }

    ^altview-container {
      position: absolute;
      right: 0;
      padding: 12px 16px 0 0;
    }
  `,

  properties: [
    {
      class: 'foam.dao.DAOProperty',
      name: 'data'
    },
    {
      class: 'FObjectProperty',
      of: 'foam.comics.v2.DAOControllerConfig',
      name: 'config',
      factory: function() {
        return foam.comics.v2.DAOControllerConfig.create({ dao: this.data });
      }
    },
    {
      class: 'foam.u2.ViewSpecWithJava',
      name: 'browseView',
      expression: function(config$browseViews) {
        return config$browseViews && config$browseViews.length
          ? config$browseViews[0].view
          : this.DAOBrowserView
          ;
      }
    }
  ],
  actions: [
    {
      name: 'create',
      isAvailable: function(config$createEnabled) {
        return config$createEnabled;
      },
      code: function() {
        if ( ! this.stack ) return;
        this.stack.push({
          class: 'foam.comics.v2.DAOCreateView',
          data: this.data.of.create({ mode: 'create' }, this),
          config$: this.config$,
          of: this.data.of
        });
      }
    }
  ],
  methods: [
    function initE() {
    this.SUPER();

    var self = this;

      this.addClass(this.myClass())
      .add(this.slot(function(data, config, config$CRUDActionsAuth$create, config$browseBorder, config$browseViews, config$browseTitle) {
        var createAction = config$CRUDActionsAuth$create
            ? self.CREATE.clone().copyFrom({
              availablePermissions: config$CRUDActionsAuth$create
            })
            : self.CREATE;

        return self.E()
          .start(self.Rows)
            .addClass(self.myClass('container'))
            .start(self.Cols)
              .addClass(self.myClass('header-container'))
              .start()
                .addClass(self.myClass('browse-title'))
                .add(config$browseTitle)
              .end()
              .startContext({data: self}).tag(createAction).endContext()
            .end()
            .start(self.CardBorder)
              .style({ position: 'relative' })
              .start(config$browseBorder)
                .callIf(config$browseViews.length > 1, function() {
                  this
                    .start(self.IconChoiceView, {
                      choices:config$browseViews.map(o => [o.view, o.icon]),
                      data$: self.browseView$
                    })
                      .addClass(self.myClass('altview-container'))
                    .end();
                })
                .add(self.slot(function(browseView) {
                  return self.E().tag(browseView, {data: data, config: config});
                }))
              .end()
            .end()
          .end();
      }));
    }
  ]
});
<|endoftext|>


<commit_before>/*
 * c_cpp_fold_mode.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *      Gastón Kleiman <gaston.kleiman AT gmail DOT com>
 *
 * Based on Bespin's C/C++ Syntax Plugin by Marc McIntyre.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

define("mode/c_cpp_fold_mode", ["require", "exports", "module"], function(require, exports, module) {

var oop = require("ace/lib/oop");
var Range = require("ace/range").Range;
var BaseFoldMode = require("ace/mode/folding/fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    var reBracketStart = /(\{|\[)[^\}\]]*$/;
    var reBracketEnd   = /^[^\[\{]*(\}|\])/;

    this.getFoldWidget = function(session, foldStyle, row) {

        var FOLD_NONE = "";
        var FOLD_START = "start";
        var FOLD_END = foldStyle === "markbeginend" ? "end" : "";

        var line = session.getLine(row);

        if (reBracketStart.test(line))
            return FOLD_START;

        if (reBracketEnd.test(line))
            return FOLD_END;

        var commentStartIdx = line.indexOf("/*");
        var commentEndIdx = line.indexOf("*/");

        if (commentStartIdx !== -1 && (commentEndIdx === -1 || commentStartIdx > commentEndIdx))
            return FOLD_START;

        if (commentEndIdx !== -1 && (commentStartIdx === -1 || commentEndIdx < commentStartIdx))
            return FOLD_END;

        return FOLD_NONE;

    };

    function getBlockCommentRange(session, startRow, startColumn, delta)
    {
        var lines = session.doc.$lines;
        var row = startRow + delta;
        var line = lines[row];
        var target = delta > 0 ? "*/" : "/*";

        var range;
        while (line != null)
        {
            var idx = line.indexOf(target);
            if (idx !== -1)
            {
                range = delta > 0 ?
                    new Range(startRow, startColumn, row, idx) :
                    new Range(row, line.length, startRow, startColumn);
                break;
            }

            row += delta;
            line = lines[row];
        }

        return range;
    }

    this.getFoldWidgetRange = function(session, foldStyle, row) {

        var line = session.getLine(row);
        var match;

        // First, check for brackets for folding.
        match = line.match(reBracketStart);
        if (match)
            return this.openingBracketBlock(session, match[1], row, match.index);

        match = foldStyle === "markbeginend" && line.match(reBracketEnd);
        if (match)
            return this.closingBracketBlock(session, match[1], row, match.index + match[0].length);

        // Next, check for block comment folds.
        var idx;

        idx = line.indexOf("/*");
        if (idx !== -1)
            return getBlockCommentRange(session, row, line.length, 1);

        idx = line.indexOf("*/");
        if (idx !== -1)
            return getBlockCommentRange(session, row, idx, -1);

        // No match -- just return undefined.
    };

}).call(FoldMode.prototype);

});
<commit_msg>find chunk ranges (for R code blocks)<commit_after>/*
 * c_cpp_fold_mode.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *      Gastón Kleiman <gaston.kleiman AT gmail DOT com>
 *
 * Based on Bespin's C/C++ Syntax Plugin by Marc McIntyre.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

define("mode/c_cpp_fold_mode", ["require", "exports", "module"], function(require, exports, module) {

var oop = require("ace/lib/oop");
var Range = require("ace/range").Range;
var BaseFoldMode = require("ace/mode/folding/fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    var reBracketStart = /(\{|\[)[^\}\]]*$/;
    var reBracketEnd   = /^[^\[\{]*(\}|\])/;

    this.getFoldWidget = function(session, foldStyle, row) {

        var FOLD_NONE = "";
        var FOLD_START = "start";
        var FOLD_END = foldStyle === "markbeginend" ? "end" : "";

        var line = session.getLine(row);

        if (reBracketStart.test(line))
            return FOLD_START;

        if (reBracketEnd.test(line))
            return FOLD_END;

        var commentStartIdx = line.indexOf("/*");
        var commentEndIdx = line.indexOf("*/");

        if (commentStartIdx !== -1 && (commentEndIdx === -1 || commentStartIdx > commentEndIdx))
            return FOLD_START;

        if (commentEndIdx !== -1 && (commentStartIdx === -1 || commentEndIdx < commentStartIdx))
            return FOLD_END;

        return FOLD_NONE;

    };

    function getBlockCommentRange(session, startRow, startColumn, delta)
    {
        var lines = session.doc.$lines;
        var row = startRow + delta;
        var line = lines[row];
        var target = delta > 0 ? "*/" : "/*";

        var range;
        while (line != null)
        {
            var idx = line.indexOf(target);
            if (idx !== -1)
            {
                range = delta > 0 ?
                    new Range(startRow, startColumn, row, idx) :
                    new Range(row, line.length, startRow, startColumn);
                break;
            }

            row += delta;
            line = lines[row];
        }

        return range;
    }

    function findChunkRange(session, startRow, startColumn, targetType, delta)
    {
        var row = startRow + delta;
        var lines = session.doc.$lines;

        var range;
        while (row >= 0 && row < session.getLength())
        {
            var tokens = session.getTokens(row);
            var line = lines[row];

            if (tokens.length === 1)
            {
                var token = tokens[0];
                if (token.type === targetType)
                {
                    range = delta > 0 ?
                        new Range(startRow, startColumn, row, 0) :
                        new Range(row, line.length, startRow, startColumn);
                    break;
                }
            }

            row += delta;
        }

        return range;
    }

    this.getFoldWidgetRange = function(session, foldStyle, row) {

        var line = session.getLine(row);
        var match;

        // First, check for brackets for folding.
        match = line.match(reBracketStart);
        if (match)
            return this.openingBracketBlock(session, match[1], row, match.index);

        match = foldStyle === "markbeginend" && line.match(reBracketEnd);
        if (match)
            return this.closingBracketBlock(session, match[1], row, match.index + match[0].length);

        // Check for chunk headers / footers.
        var tokens = session.getTokens(row);
        if (tokens.length === 1)
        {
            var line = session.getLine(row);
            var token = tokens[0];
            if (token.type === "support.function.codebegin")
                return findChunkRange(session, row, line.length, "support.function.codeend", 1);
            else if (token.type === "support.function.codeend")
                return findChunkRange(session, row, 0, "support.function.codebegin", -1);
        }

        // Next, check for block comment folds.
        var idx;

        idx = line.indexOf("/*");
        if (idx !== -1)
            return getBlockCommentRange(session, row, line.length, 1);

        idx = line.indexOf("*/");
        if (idx !== -1)
            return getBlockCommentRange(session, row, idx, -1);

        // No match -- just return undefined.
    };

}).call(FoldMode.prototype);

});
<|endoftext|>


<commit_before>define([
    "dojo/_base/declare", // declare
    "dojo/_base/array" // forEach, indexOf
], function(declare, arrayUtil){
    /**
     * @class
     * @name rishson.widget.WidgetInWidgetMixin
     * @description This is a class based version of Phil Higgin's awesome solution to memory leaks that can occur
     * when creating widgets programatically inside custom widgets

     * Please see here.
     */
    return declare('rishson.widget._WidgetInWidgetMixin', null, {

        /**
         * @function
         * @name rishson.widget._WidgetInWidget.adopt
         * @description Instantiate some new item from a passed Class, with props with an optional srcNode (node)
         * reference. Also tracks this widget as if it were a child to be destroyed when this parent widget
         * is removed.
         * @param {Function} cls the class to instantiate. Cannot be a string. Use lang.getObject to get a full class object
         * if you must.

         * example:

         *      this.adopt(my.ui.Button, { onClick: function(){} }).placeAt(this.domNode);

         * example:

         *      var x = this.adopt(my.ui.Button).placeAt(this.domNode);

         *      x.connect(this.domNode, "onclick", "fooBar");

         * example:

         *      //If you *must* new up a thinger and only want to adopt it once, use __addItem instead:

         *      var t;

         *      if(4 > 5){ t = new my.ui.Button(); }else{ t = new joost.ui.OtherButton() }

         *      this.__addItem(t);
         * @param {Object} props optional an object mixed into the constructor of said cls.
         * @param {DOMNode} node optional a srcNodeRef to use with dijit._Widget. This thinger will be instantiated using
         * this passed node as the target if passed. Otherwise a new node is created and you must placeAt() your
         * instance somewhere in the dom for it to be useful.
         * @returns {Object} the created Widget instance
         */
        adopt : function (/*Function*/cls, /*Object*/props, /*DomNode*/node) {
            var x = new cls(props, node);
            this.__addItem(x);
            return x; // my.Widget
        },

        /**
         * @function
         * @name rishson.widget._WidgetInWidget.orphan
         * @description Remove a single item from this instance when we destroy it. It is the parent widget's job
         * to properly destroy an orphaned child.

         * example:

         *      //Clear out all the children in an array, but do not destroy them.

         *      arrayUtil.forEach(this._thumbs, this.orphan, this);

         * example:

         *      //Create and destroy a button cleanly:

         *      var x = this.adopt(my.ui.Button, {});

         *      this.orphan(x, true);
         * @param {Object} widget a widget reference to remove from this parent.
         * @param {Boolean} destroy an optional boolean used to force immediate destruction of the child. Pass any truthy
         * value here and the child will be orphaned and killed.
         */
        orphan : function(/*dijit._Widget*/widget, /*Boolean*/destroy){
            this._addedItems = this._addedItems || [];
            var i = arrayUtil.indexOf(this._addedItems, widget);
            if (i >= 0) {
                this._addedItems.splice(i, 1);
            }
            destroy && this.__kill(widget);
        },

        /**
         * @function
         * @name rishson.widget._WidgetInWidget.destroy
         * @override : dijit._widget
         * @description Override the default destroy function to account for programatically added children.
         */
        destroy : function() {
            // summary: override the default destroy function to account for programatically added children.
            arrayUtil.forEach(this._addedItems, this.__kill, this);  //destroy any adopted widgets
            this.inherited(arguments);  //call dijit._Widget to actually destroy this widget
        },

        //private functions-------------------------------------------------------------------------------------------------

        /**
         * @function
         * @name rishson.widget._WidgetInWidget._addItem
         * @private
         * @description Add any number of programmaticaly created children to this instance for later cleanup.
         * @varargs any number of widgets
         */
        __addItem : function (/* dijit._Widget... */) {
            this._addedItems = this._addedItems || [];
            this._addedItems.push.apply(this._addedItems, arguments);
        },

        /**
         * @function
         * @name rishson.widget._widgetInWidget.__kill
         * @private
         * @description Private helper function to properly destroy a widget instance.
         * @param {Object} w a widget to destroy
         */
        __kill : function (w) {
            try {
                if (w && w.destroyRecursive) {
                    w.destroyRecursive();
                }
            }
            catch (e){
                //ignore errors thrown by IE when doing teardown of Grids whose domNode's get removed early
            }
        }

    });
});<commit_msg>Refactor _WidgetInWidgetMixin to take advantage of _supportingWidgets<commit_after>define([
    "dojo/_base/declare", // declare
    "dojo/_base/array" // forEach, indexOf
], function(declare, arrayUtil){
    /**
     * @class
     * @name rishson.widget.WidgetInWidgetMixin
     * @description This is a class based version of Phil Higgin's awesome solution to memory leaks that can occur
     * when creating widgets programatically inside custom widgets

     * Please see here.
     */
    return declare('rishson.widget._WidgetInWidgetMixin', null, {

        /**
         * @function
         * @name rishson.widget._WidgetInWidget.adopt
         * @description Instantiate some new item from a passed Class, with props with an optional srcNode (node)
         * reference. Also tracks this widget as if it were a child to be destroyed when this parent widget
         * is removed.
         * @param {Function} cls the class to instantiate. Cannot be a string. Use lang.getObject to get a full class object
         * if you must.

         * example:

         *      this.adopt(my.ui.Button, { onClick: function(){} }).placeAt(this.domNode);

         * example:

         *      var x = this.adopt(my.ui.Button).placeAt(this.domNode);

         *      x.connect(this.domNode, "onclick", "fooBar");

         * example:

         *      //If you *must* new up a thinger and only want to adopt it once, use __addItem instead:

         *      var t;

         *      if(4 > 5){ t = new my.ui.Button(); }else{ t = new joost.ui.OtherButton() }

         *      this.__addItem(t);
         * @param {Object} props optional an object mixed into the constructor of said cls.
         * @param {DOMNode} node optional a srcNodeRef to use with dijit._Widget. This thinger will be instantiated using
         * this passed node as the target if passed. Otherwise a new node is created and you must placeAt() your
         * instance somewhere in the dom for it to be useful.
         * @returns {Object} the created Widget instance
         */
        adopt : function (/*Function*/cls, /*Object*/props, /*DomNode*/node) {
            var x = new cls(props, node);
            this._supportingWidgets.push(x);
            return x; // my.Widget
        },

        /**
         * @function
         * @name rishson.widget._WidgetInWidget.orphan
         * @description Remove a single item from this instance when we destroy it. It is the parent widget's job
         * to properly destroy an orphaned child.

         * example:

         *      //Clear out all the children in an array, but do not destroy them.

         *      arrayUtil.forEach(this._thumbs, this.orphan, this);

         * example:

         *      //Create and destroy a button cleanly:

         *      var x = this.adopt(my.ui.Button, {});

         *      this.orphan(x, true);
         * @param {Object} widget a widget reference to remove from this parent.
         * @param {Boolean} destroy an optional boolean used to force immediate destruction of the child. Pass any truthy
         * value here and the child will be orphaned and killed.
         */
        orphan : function(/*dijit._Widget*/widget, /*Boolean*/destroy){
            var i = arrayUtil.indexOf(this._supportingWidgets, widget);
            if (i >= 0) {
                this._supportingWidgets.splice(i, 1);
            }
            destroy && this.__kill(widget);
        },

        //private functions-------------------------------------------------------------------------------------------------

        /**
         * @function
         * @name rishson.widget._WidgetInWidget.__addItem
         * @private
         * @description Add any number of programmaticaly created children to this instance for later cleanup.
         * @varargs any number of widgets
         */
        __addItem : function (/* dijit._Widget... */) {
            this._supportingWidgets.push.apply(this._supportingWidgets, arguments);
        },

        /**
         * @function
         * @name rishson.widget._widgetInWidget.__kill
         * @private
         * @description Private helper function to properly destroy a widget instance.
         * @param {Object} w a widget to destroy
         */
        __kill : function (w) {
            try {
                if (w && w.destroyRecursive) {
                    w.destroyRecursive();
                }
            }
            catch (e){
                //ignore errors thrown by IE when doing teardown of Grids whose domNode's get removed early
            }
        }

    });
});<|endoftext|>


<commit_before>// ==UserScript==
// @name        EPFL People
// @namespace   none
// @description A script to improve browsing on people.epfl.ch
// @include     http://people.epfl.ch/*
// @include     https://people.epfl.ch/*
// @version     1.0.8
// @grant       GM_xmlhttpRequest
// @grant       GM_addStyle
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @author      EPFL-dojo
// @downloadURL https://raw.githubusercontent.com/epfl-dojo/EPFL_People_UserScript/master/EPFL_People.user.js
// @updateURL   https://raw.githubusercontent.com/epfl-dojo/EPFL_People_UserScript/master/EPFL_People.user.js
// ==/UserScript==

//Avoid conflicts
this.$ = this.jQuery = jQuery.noConflict(true);
$(document).ready(function()
{
  // get the h1 name content
  $.epfl_user = {
      "name": $("h1").text(),
      "sciper": $('a[href*="http://people.epfl.ch/cgi-bin/people?id="]').attr('href').match(/id=([0-9]{6})/)[1]
  };
  // change the main title content to add the sciper in it
  $("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " ()");

  $.get("/cgi-bin/people/showcv?id=" + $.epfl_user["sciper"] + "&op=admindata&type=show&lang=en&cvlang=en", function(data){
    $.epfl_user["username"] = data.match(/Username: (\w+)\s/)[1];
    $("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " (" + $.epfl_user["username"]+ ")");
    $('.presentation').append('Username : ' + $.epfl_user["username"]+'
');
  });
  $('.presentation').append('Sciper : ' + $.epfl_user["sciper"]+'
');

  // Add user's mailing list in the right column
  var cadiURL = 'http://cadiwww.epfl.ch/listes?sciper='+$.epfl_user["sciper"];
  GM_xmlhttpRequest({
    method: "GET",
    url: cadiURL,
    onload: function(response) {
      html = $.parseHTML( response.responseText );
      // Mailing list emails
      mailinglistUL = $(html).contents('ul').not(':last');
      if (0 < mailinglistUL.length) {
        $('.right-col').append('
Mailing Lists

test

');
        $('#cadiML').html(mailinglistUL);
      }
      // Group list emails
      grouplistUL = $(html).contents('ul').last();
      if (0 < grouplistUL.length) {
        $('.right-col').append('

Groups Lists

test

');
        $('#cadiGL').html(grouplistUL);
      }
    }
  });
  GM_addStyle("#cadiMLdiv{ padding-left: 20px; } #cadiML ul ul { margin-left: 10px; }" );
  GM_addStyle("#cadiGLdiv{ padding-left: 20px; } #cadiGL ul ul { margin-left: 10px; }" );

  // var adminDataURL = "http://people.epfl.ch/cgi-bin/people?id="+sciper+"&op=admindata&lang=en&cvlang=en";
  /* Idea => add accred link

      <button class="icon"></button>
       Accreditations of Jean-Claude De Giorgi (fr)

*/
});
<commit_msg>HTTPS fixed for people<commit_after>// ==UserScript==
// @name        EPFL People
// @namespace   none
// @description A script to improve browsing on people.epfl.ch
// @include     http://people.epfl.ch/*
// @include     https://people.epfl.ch/*
// @version     1.0.8
// @grant       GM_xmlhttpRequest
// @grant       GM_addStyle
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @author      EPFL-dojo
// @downloadURL https://raw.githubusercontent.com/epfl-dojo/EPFL_People_UserScript/master/EPFL_People.user.js
// @updateURL   https://raw.githubusercontent.com/epfl-dojo/EPFL_People_UserScript/master/EPFL_People.user.js
// ==/UserScript==

//Avoid conflicts
this.$ = this.jQuery = jQuery.noConflict(true);
$(document).ready(function()
{
  // get the h1 name content
  $.epfl_user = {
      "name": $("h1").text(),
      "sciper": $('a[href*="https://people.epfl.ch/cgi-bin/people?id="]').attr('href').match(/id=([0-9]{6})/)[1]
  };
  // change the main title content to add the sciper in it
  $("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " ()");

  $.get("/cgi-bin/people/showcv?id=" + $.epfl_user["sciper"] + "&op=admindata&type=show&lang=en&cvlang=en", function(data){
    $.epfl_user["username"] = data.match(/Username: (\w+)\s/)[1];
    $("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " (" + $.epfl_user["username"]+ ")");
    $('.presentation').append('Username : ' + $.epfl_user["username"]+'
');
  });
  $('.presentation').append('Sciper : ' + $.epfl_user["sciper"]+'
');

  // Add user's mailing list in the right column
  var cadiURL = 'http://cadiwww.epfl.ch/listes?sciper='+$.epfl_user["sciper"];
  GM_xmlhttpRequest({
    method: "GET",
    url: cadiURL,
    onload: function(response) {
      html = $.parseHTML( response.responseText );
      // Mailing list emails
      mailinglistUL = $(html).contents('ul').not(':last');
      if (0 < mailinglistUL.length) {
        $('.right-col').append('
Mailing Lists

test

');
        $('#cadiML').html(mailinglistUL);
      }
      // Group list emails
      grouplistUL = $(html).contents('ul').last();
      if (0 < grouplistUL.length) {
        $('.right-col').append('

Groups Lists

test

');
        $('#cadiGL').html(grouplistUL);
      }
    }
  });
  GM_addStyle("#cadiMLdiv{ padding-left: 20px; } #cadiML ul ul { margin-left: 10px; }" );
  GM_addStyle("#cadiGLdiv{ padding-left: 20px; } #cadiGL ul ul { margin-left: 10px; }" );

  // var adminDataURL = "http://people.epfl.ch/cgi-bin/people?id="+sciper+"&op=admindata&lang=en&cvlang=en";
  /* Idea => add accred link

      <button class="icon"></button>
       Accreditations of Jean-Claude De Giorgi (fr)

*/
});
<|endoftext|>


<commit_before>/*
 *  ExpressTransport.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-03-27
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  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.
 */

"use strict";

var iotdb = require('iotdb');
var iotdb_transport = require('iotdb-transport');
var errors = iotdb_transport.errors;
var _ = iotdb._;

var path = require('path');

var events = require('events');
var util = require('util');
var url = require('url');

var logger = iotdb.logger({
    name: 'iotdb-transport-express',
    module: 'ExpressTransport',
});

/* --- forward definitions --- */
var _encode;
var _decode;
var _unpack;
var _pack;

/* --- constructor --- */

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 *

 *  Create a web interface for Express.
 *
 *  @param {dictionary} initd
 *
 *  @param {object} app
 *  An ExpressJS app
 */
var ExpressTransport = function (initd, app) {
    var self = this;

    self.initd = _.defaults(
        initd, {
            channel: iotdb_transport.channel,
            unchannel: iotdb_transport.unchannel,
            encode: _encode,
            decode: _decode,
            pack: _pack,
            unpack: _unpack,
        },
        iotdb.keystore().get("/transports/ExpressTransport/initd"), {
            prefix: "/",
            key_things: "item",
        }
    );

    self.native = app;

    self._setup_app_thing_band();
    self._setup_app_thing();
    self._setup_app_things();

    this._emitter = new events.EventEmitter();
};

ExpressTransport.prototype = new iotdb_transport.Transport();
ExpressTransport.prototype._class = "ExpressTransport";

/* --- web --- */

ExpressTransport.prototype._setup_app_things = function () {
    var self = this;

    var channel = self.initd.channel(self.initd);

    self.native.use(channel, function (request, response) {
        var ids = [];
        self.list({
            user: request.user,
        }, function (error, ld) {
            if (!error && ld && ld.id) {
                ids.push(self.initd.channel(self.initd, ld.id));
                return;
            }

            var rd = {
                "@id": self.initd.channel(self.initd),
                "@context": "https://iotdb.org/pub/iot",
            };

            if (error) {
                rd.error = _.error.message(ld.error);
                response.status(_.error.code(ld.error));
            } else {
                rd[self.initd.key_things] = ids;
            }

            return response
                .set('Content-Type', 'application/json')
                .set('Access-Control-Allow-Origin', '*')
                .send(JSON.stringify(rd, null, 2));

        });
    });
};

ExpressTransport.prototype._setup_app_thing = function () {
    var self = this;

    var channel = self.initd.channel(self.initd, ':id');

    self.native.use(channel, function (request, response) {
        self.bands({
            id: request.params.id,
            user: request.user,
        }, function (error, ad) {
            var rd = {
                "@id": self.initd.channel(self.initd, request.params.id),
                "@context": "https://iotdb.org/pub/iot",
            };

            _.mapObject(ad.bandd, function (url, band) {
                if (url) {
                    rd[band] = url;
                } else {
                    rd[band] = self.initd.channel(self.initd, request.params.id, band);
                }
            });

            return response
                .set('Content-Type', 'application/json')
                .set('Access-Control-Allow-Origin', '*')
                .send(JSON.stringify(rd, null, 2));
        });
    });
};

ExpressTransport.prototype._setup_app_thing_band = function () {
    var self = this;

    var channel = self.initd.channel(self.initd, ':id', ':band');

    self.native.get(channel, function (request, response) {
        self.get({
            id: request.params.id,
            band: request.params.band,
            user: request.user,
        }, function (error, gd) {
            var rd = {
                "@id": self.initd.channel(self.initd, request.params.id, request.params.band),
            };

            if ((request.params.band === "istate") || (request.params.band === "ostate")) {
                rd["@context"] = self.initd.channel(self.initd, request.params.id, "model");
            } else if (request.params.band === "meta") {
                rd["@context"] = "https://iotdb.org/pub/iot";
            }

            if (!error && !gd.value) {
                error = new errors.NotFound();
            }

            if (error) {
                response.status(_.error.code(error));
            } else {
                rd = _.defaults(rd, gd.value);
            }

            if (request.params.band === "model") {
                if (rd["@context"]) {
                    delete rd["@context"]["@base"];
                    delete rd["@context"]["@vocab"];
                }
            }

            return response
                .set('Content-Type', 'application/json')
                .set('Access-Control-Allow-Origin', '*')
                .send(JSON.stringify(rd, null, 2));
        });
    });

    self.native.put(channel, function (request, response) {
        self.get({
            id: request.params.id,
            band: request.params.band,
            user: request.user,
        }, function (error, gd) {
            if (error) {
                var rd = {
                    "@id": self.initd.channel(self.initd, gd.id, gd.band),
                };
                rd.error = _.error.message(gd.error);

                response.status(_.error.code(gd.error));

                return response
                    .set('Content-Type', 'application/json')
                    .send(JSON.stringify(rd, null, 2));
            }

            var d = request.body;
            _.timestamp.update(d);

            self._emitter.emit("updated", {
                id: request.params.id,
                band: request.params.band,
                value: d,
                user: request.user,
                response: response,
            });
        });
    });
};

/* --- methods --- */

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.list = function (paramd, callback) {
    var self = this;
    var ld;

    self._validate_list(paramd, callback);

    ld = _.d.clone.shallow(paramd);
    callback(new errors.NeverImplemented(), ld);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.added = function (paramd, callback) {
    var self = this;

    var channel = self.initd.channel(self.initd);
};

/**
 *  See {iotdb_transport.Transport#bands} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.bands = function (paramd, callback) {
    callback(new errors.NeverImplemented(), null);
};

/**
 *  See {iotdb_transport.Transport#get} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.get = function (paramd, callback) {
    callback(new errors.NeverImplemented(), null);
};

/**
 *  See {iotdb_transport.Transport#update} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.put = function (paramd, callback) {
    callback(new errors.NeverImplemented(), null);
};

/**
 *  See {iotdb_transport.Transport#updated} for documentation.
 *

 *  This will be triggered from the Express/Express API
 */
ExpressTransport.prototype.updated = function (paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_updated(paramd, callback);

    self._emitter.on("updated", function (ud) {
        if (paramd.id && (ud.id !== paramd.id)) {
            return;
        }
        if (paramd.band && (ud.band !== paramd.band)) {
            return;
        }

        var response = ud.response;
        delete ud.response;

        callback(null, ud);

        var rd = {
            "@id": self.initd.channel(self.initd, ud.id, ud.band),
        };

        return response
            .set('Content-Type', 'application/json')
            .send(JSON.stringify(rd, null, 2));
    });
};

/**
 *  See {iotdb_transport.Transport#remove} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.remove = function (paramd) {
    var self = this;

    self._validate_remove(paramd, callback);

    var rd = _.d.clone.shallow(paramd);
    delete rd.band;
    delete rd.value;

    callback(new errors.NotImplemented(), rd);
};

/* -- internals -- */
var _encode = function (s) {
    return s.replace(/[\/$%#.\]\[]/g, function (c) {
        return '%' + c.charCodeAt(0).toString(16);
    });
};

var _decode = function (s) {
    return decodeURIComponent(s);
};

var _unpack = function (d) {
    return _.d.transform(d, {
        pre: _.ld_compact,
        key: _decode,
    });
};

var _pack = function (d) {
    return _.d.transform(d, {
        pre: _.ld_compact,
        key: _encode,
    });
};

/**
 *  API
 */
exports.ExpressTransport = ExpressTransport;
<commit_msg>@context for connection<commit_after>/*
 *  ExpressTransport.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-03-27
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  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.
 */

"use strict";

var iotdb = require('iotdb');
var iotdb_transport = require('iotdb-transport');
var errors = iotdb_transport.errors;
var _ = iotdb._;

var path = require('path');

var events = require('events');
var util = require('util');
var url = require('url');

var logger = iotdb.logger({
    name: 'iotdb-transport-express',
    module: 'ExpressTransport',
});

/* --- forward definitions --- */
var _encode;
var _decode;
var _unpack;
var _pack;

/* --- constructor --- */

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 *

 *  Create a web interface for Express.
 *
 *  @param {dictionary} initd
 *
 *  @param {object} app
 *  An ExpressJS app
 */
var ExpressTransport = function (initd, app) {
    var self = this;

    self.initd = _.defaults(
        initd, {
            channel: iotdb_transport.channel,
            unchannel: iotdb_transport.unchannel,
            encode: _encode,
            decode: _decode,
            pack: _pack,
            unpack: _unpack,
        },
        iotdb.keystore().get("/transports/ExpressTransport/initd"), {
            prefix: "/",
            key_things: "item",
        }
    );

    self.native = app;

    self._setup_app_thing_band();
    self._setup_app_thing();
    self._setup_app_things();

    this._emitter = new events.EventEmitter();
};

ExpressTransport.prototype = new iotdb_transport.Transport();
ExpressTransport.prototype._class = "ExpressTransport";

/* --- web --- */

ExpressTransport.prototype._setup_app_things = function () {
    var self = this;

    var channel = self.initd.channel(self.initd);

    self.native.use(channel, function (request, response) {
        var ids = [];
        self.list({
            user: request.user,
        }, function (error, ld) {
            if (!error && ld && ld.id) {
                ids.push(self.initd.channel(self.initd, ld.id));
                return;
            }

            var rd = {
                "@id": self.initd.channel(self.initd),
                "@context": "https://iotdb.org/pub/iot",
            };

            if (error) {
                rd.error = _.error.message(ld.error);
                response.status(_.error.code(ld.error));
            } else {
                rd[self.initd.key_things] = ids;
            }

            return response
                .set('Content-Type', 'application/json')
                .set('Access-Control-Allow-Origin', '*')
                .send(JSON.stringify(rd, null, 2));

        });
    });
};

ExpressTransport.prototype._setup_app_thing = function () {
    var self = this;

    var channel = self.initd.channel(self.initd, ':id');

    self.native.use(channel, function (request, response) {
        self.bands({
            id: request.params.id,
            user: request.user,
        }, function (error, ad) {
            var rd = {
                "@id": self.initd.channel(self.initd, request.params.id),
                "@context": "https://iotdb.org/pub/iot",
            };

            _.mapObject(ad.bandd, function (url, band) {
                if (url) {
                    rd[band] = url;
                } else {
                    rd[band] = self.initd.channel(self.initd, request.params.id, band);
                }
            });

            return response
                .set('Content-Type', 'application/json')
                .set('Access-Control-Allow-Origin', '*')
                .send(JSON.stringify(rd, null, 2));
        });
    });
};

ExpressTransport.prototype._setup_app_thing_band = function () {
    var self = this;

    var channel = self.initd.channel(self.initd, ':id', ':band');

    self.native.get(channel, function (request, response) {
        self.get({
            id: request.params.id,
            band: request.params.band,
            user: request.user,
        }, function (error, gd) {
            var rd = {
                "@id": self.initd.channel(self.initd, request.params.id, request.params.band),
            };

            if ((request.params.band === "istate") || (request.params.band === "ostate")) {
                rd["@context"] = self.initd.channel(self.initd, request.params.id, "model");
            } else if ((request.params.band === "meta") || (request.params.band === "connection")) {
                rd["@context"] = "https://iotdb.org/pub/iot";
            }

            if (!error && !gd.value) {
                error = new errors.NotFound();
            }

            if (error) {
                response.status(_.error.code(error));
            } else {
                rd = _.defaults(rd, gd.value);
            }

            if (request.params.band === "model") {
                if (rd["@context"]) {
                    delete rd["@context"]["@base"];
                    delete rd["@context"]["@vocab"];
                }
            }

            return response
                .set('Content-Type', 'application/json')
                .set('Access-Control-Allow-Origin', '*')
                .send(JSON.stringify(rd, null, 2));
        });
    });

    self.native.put(channel, function (request, response) {
        self.get({
            id: request.params.id,
            band: request.params.band,
            user: request.user,
        }, function (error, gd) {
            if (error) {
                var rd = {
                    "@id": self.initd.channel(self.initd, gd.id, gd.band),
                };
                rd.error = _.error.message(gd.error);

                response.status(_.error.code(gd.error));

                return response
                    .set('Content-Type', 'application/json')
                    .send(JSON.stringify(rd, null, 2));
            }

            var d = request.body;
            _.timestamp.update(d);

            self._emitter.emit("updated", {
                id: request.params.id,
                band: request.params.band,
                value: d,
                user: request.user,
                response: response,
            });
        });
    });
};

/* --- methods --- */

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.list = function (paramd, callback) {
    var self = this;
    var ld;

    self._validate_list(paramd, callback);

    ld = _.d.clone.shallow(paramd);
    callback(new errors.NeverImplemented(), ld);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.added = function (paramd, callback) {
    var self = this;

    var channel = self.initd.channel(self.initd);
};

/**
 *  See {iotdb_transport.Transport#bands} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.bands = function (paramd, callback) {
    callback(new errors.NeverImplemented(), null);
};

/**
 *  See {iotdb_transport.Transport#get} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.get = function (paramd, callback) {
    callback(new errors.NeverImplemented(), null);
};

/**
 *  See {iotdb_transport.Transport#update} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.put = function (paramd, callback) {
    callback(new errors.NeverImplemented(), null);
};

/**
 *  See {iotdb_transport.Transport#updated} for documentation.
 *

 *  This will be triggered from the Express/Express API
 */
ExpressTransport.prototype.updated = function (paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_updated(paramd, callback);

    self._emitter.on("updated", function (ud) {
        if (paramd.id && (ud.id !== paramd.id)) {
            return;
        }
        if (paramd.band && (ud.band !== paramd.band)) {
            return;
        }

        var response = ud.response;
        delete ud.response;

        callback(null, ud);

        var rd = {
            "@id": self.initd.channel(self.initd, ud.id, ud.band),
        };

        return response
            .set('Content-Type', 'application/json')
            .send(JSON.stringify(rd, null, 2));
    });
};

/**
 *  See {iotdb_transport.Transport#remove} for documentation.
 *

 *  Inherently this does nothing. To properly support this
 *  you should use iotdb.transport.bind
 *  to effectively replace this function.
 */
ExpressTransport.prototype.remove = function (paramd) {
    var self = this;

    self._validate_remove(paramd, callback);

    var rd = _.d.clone.shallow(paramd);
    delete rd.band;
    delete rd.value;

    callback(new errors.NotImplemented(), rd);
};

/* -- internals -- */
var _encode = function (s) {
    return s.replace(/[\/$%#.\]\[]/g, function (c) {
        return '%' + c.charCodeAt(0).toString(16);
    });
};

var _decode = function (s) {
    return decodeURIComponent(s);
};

var _unpack = function (d) {
    return _.d.transform(d, {
        pre: _.ld_compact,
        key: _decode,
    });
};

var _pack = function (d) {
    return _.d.transform(d, {
        pre: _.ld_compact,
        key: _encode,
    });
};

/**
 *  API
 */
exports.ExpressTransport = ExpressTransport;
<|endoftext|>


<commit_before>export default {
  stable: 'v7.5.2',
  beta: 'v7.6.0-beta.1',
  betaAvailable: true,
}
<commit_msg>Update for v7.6.0<commit_after>export default {
  stable: 'v7.6.0',
  beta: 'v7.6.0-beta.1',
  betaAvailable: false,
}
<|endoftext|>


<commit_before>// @flow
/**
 * All About Olaf
 * Balances page
 */

import React from 'react'
import {
  StyleSheet,
  ScrollView,
  View,
  Text,
  RefreshControl,
} from 'react-native'

import {Cell, Section, TableView} from 'react-native-tableview-simple'

import {isLoggedIn} from '../../lib/login'
import delay from 'delay'
import * as c from '../components/colors'
import {getFinancialData} from '../../lib/financials'
import ErrorView from './error-screen'

const buttonStyles = StyleSheet.create({
  Common: {
    backgroundColor: c.white,
  },
  Balances: {
    borderRightWidth: 1,
    borderRightColor: c.iosGray,
  },
  Courses: {
    borderRightWidth: 1,
    borderRightColor: c.iosGray,
  },
  Search: {},
})

export default class BalancesView extends React.Component {
  static propTypes = {
    navigator: React.PropTypes.object,
    route: React.PropTypes.object,
  };

  state = {
    flex: null,
    ole: null,
    print: null,
    successsFinancials: false,
    loading: true,
    error: null,
    refreshing: false,
  }

  state: {
    flex: null|number,
    ole: null|number,
    print: null|number,
    successsFinancials: bool,
    loading: bool,
    error: null|Error,
    refreshing: bool,
  };

  componentWillMount() {
    this.loadIfLoggedIn()
  }

  loadIfLoggedIn = async () => {
    let shouldContinue = await this.checkLogin()
    if (shouldContinue) {
      await this.fetchData()
    }
  }

  checkLogin = async () => {
    let loggedIn = await isLoggedIn()
    this.setState({loggedIn})
    return loggedIn
  }

  fetchData = async (forceFromServer=false) => {
    try {
      let {flex, ole, print} = await getFinancialData(forceFromServer)
      this.setState({flex, ole, print})
    } catch (error) {
      this.setState({error})
      console.warn(error)
    }
    this.setState({loading: false})
  }

  refresh = async () => {
    let start = Date.now()
    this.setState({refreshing: true})

    await this.fetchData(true)

    // wait 0.5 seconds – if we let it go at normal speed, it feels broken.
    let elapsed = start - Date.now()
    if (elapsed < 500) {
      await delay(500 - elapsed)
    }

    this.setState({refreshing: false})
  }

  render() {
    if (this.state.error) {
      return <Text>Error: {this.state.error.message}</Text>
    }

    if (!this.state.loggedIn) {
      return <ErrorView
        route={this.props.route}
        navigator={this.props.navigator}
        onLoginComplete={() => this.loadIfLoggedIn()}
      />
    }

    let {flex, ole, print, loading} = this.state

    return (
      <ScrollView
        contentContainerStyle={styles.stage}
        refreshControl={
          <RefreshControl
            refreshing={this.state.refreshing}
            onRefresh={this.refresh}
          />
        }
      >
        <TableView>

            <View style={styles.balancesRow}>
              <View style={[styles.rectangle, buttonStyles.Common, buttonStyles.Balances]}>
                <Text style={styles.financialText} autoAdjustsFontSize={true}>
                  {loading ? '…' : flex === null ? 'N/A' : ('$' + (flex / 100).toFixed(2))}
                </Text>
                <Text style={styles.rectangleButtonText} autoAdjustsFontSize={true}>
                  Flex
                </Text>
              </View>

              <View style={[styles.rectangle, buttonStyles.Common, buttonStyles.Balances]}>
                <Text style={styles.financialText} autoAdjustsFontSize={true}>
                  {loading ? '…' : ole === null ? 'N/A' : ('$' + (ole / 100).toFixed(2))}
                </Text>
                <Text style={styles.rectangleButtonText} autoAdjustsFontSize={true}>
                  Ole
                </Text>
              </View>

              <View style={[styles.rectangle, buttonStyles.Common, buttonStyles.Balances]}>
                <Text style={styles.financialText} autoAdjustsFontSize={true}>
                  {loading ? '…' : print === null ? 'N/A' : ('$' + (print / 100).toFixed(2))}
                </Text>
                <Text style={styles.rectangleButtonText} autoAdjustsFontSize={true}>
                  Copy/Print
                </Text>
              </View>
             </View>

            <Cell cellStyle='RightDetail'
              title='Daily Meals Left'
              detail='Not Available'
            />

            <Cell cellStyle='RightDetail'
              title='Weekly Meals Left'
              detail='Not Available'
            />

        </TableView>
      </ScrollView>
    )
  }
}

let cellMargin = 10
let cellSidePadding = 10
let cellEdgePadding = 10

let styles = StyleSheet.create({
  stage: {
    backgroundColor: '#EFEFF4',
    paddingTop: 20,
    paddingBottom: 20,
  },

  balancesRow: {
    flex: 1,
    flexDirection: 'row',
    marginTop: 0,
    marginBottom: -10,
  },

  rectangle: {
    height: 88,
    flex: 1,
    alignItems: 'center',
    paddingTop: cellSidePadding,
    paddingBottom: cellSidePadding,
    paddingRight: cellEdgePadding,
    paddingLeft: cellEdgePadding,
    marginBottom: cellMargin,
  },

  // Text styling
  financialText: {
    paddingTop: 8,
    color: c.iosDisabledText,
    textAlign: 'center',
    fontWeight: '200',
    fontSize: 23,
  },
  rectangleButtonIcon: {
    color: c.black,
  },
  rectangleButtonText: {
    paddingTop: 15,
    color: c.black,
    textAlign: 'center',
    fontSize: 16,
  },
})
<commit_msg>add base loggedIn state to balances<commit_after>// @flow
/**
 * All About Olaf
 * Balances page
 */

import React from 'react'
import {
  StyleSheet,
  ScrollView,
  View,
  Text,
  RefreshControl,
} from 'react-native'

import {Cell, Section, TableView} from 'react-native-tableview-simple'

import {isLoggedIn} from '../../lib/login'
import delay from 'delay'
import * as c from '../components/colors'
import {getFinancialData} from '../../lib/financials'
import ErrorView from './error-screen'

const buttonStyles = StyleSheet.create({
  Common: {
    backgroundColor: c.white,
  },
  Balances: {
    borderRightWidth: 1,
    borderRightColor: c.iosGray,
  },
  Courses: {
    borderRightWidth: 1,
    borderRightColor: c.iosGray,
  },
  Search: {},
})

export default class BalancesView extends React.Component {
  static propTypes = {
    navigator: React.PropTypes.object,
    route: React.PropTypes.object,
  };

  state = {
    flex: null,
    ole: null,
    print: null,
    successsFinancials: false,
    loading: true,
    error: null,
    refreshing: false,
    loggedIn: false,
  }

  state: {
    flex: null|number,
    ole: null|number,
    print: null|number,
    successsFinancials: bool,
    loading: bool,
    error: null|Error,
    refreshing: bool,
    loggedIn: bool,
  };

  componentWillMount() {
    this.loadIfLoggedIn()
  }

  loadIfLoggedIn = async () => {
    let shouldContinue = await this.checkLogin()
    if (shouldContinue) {
      await this.fetchData()
    }
  }

  checkLogin = async () => {
    let loggedIn = await isLoggedIn()
    this.setState({loggedIn})
    return loggedIn
  }

  fetchData = async (forceFromServer=false) => {
    try {
      let {flex, ole, print} = await getFinancialData(forceFromServer)
      this.setState({flex, ole, print})
    } catch (error) {
      this.setState({error})
      console.warn(error)
    }
    this.setState({loading: false})
  }

  refresh = async () => {
    let start = Date.now()
    this.setState({refreshing: true})

    await this.fetchData(true)

    // wait 0.5 seconds – if we let it go at normal speed, it feels broken.
    let elapsed = start - Date.now()
    if (elapsed < 500) {
      await delay(500 - elapsed)
    }

    this.setState({refreshing: false})
  }

  render() {
    if (this.state.error) {
      return <Text>Error: {this.state.error.message}</Text>
    }

    if (!this.state.loggedIn) {
      return <ErrorView
        route={this.props.route}
        navigator={this.props.navigator}
        onLoginComplete={() => this.loadIfLoggedIn()}
      />
    }

    let {flex, ole, print, loading} = this.state

    return (
      <ScrollView
        contentContainerStyle={styles.stage}
        refreshControl={
          <RefreshControl
            refreshing={this.state.refreshing}
            onRefresh={this.refresh}
          />
        }
      >
        <TableView>

            <View style={styles.balancesRow}>
              <View style={[styles.rectangle, buttonStyles.Common, buttonStyles.Balances]}>
                <Text style={styles.financialText} autoAdjustsFontSize={true}>
                  {loading ? '…' : flex === null ? 'N/A' : ('$' + (flex / 100).toFixed(2))}
                </Text>
                <Text style={styles.rectangleButtonText} autoAdjustsFontSize={true}>
                  Flex
                </Text>
              </View>

              <View style={[styles.rectangle, buttonStyles.Common, buttonStyles.Balances]}>
                <Text style={styles.financialText} autoAdjustsFontSize={true}>
                  {loading ? '…' : ole === null ? 'N/A' : ('$' + (ole / 100).toFixed(2))}
                </Text>
                <Text style={styles.rectangleButtonText} autoAdjustsFontSize={true}>
                  Ole
                </Text>
              </View>

              <View style={[styles.rectangle, buttonStyles.Common, buttonStyles.Balances]}>
                <Text style={styles.financialText} autoAdjustsFontSize={true}>
                  {loading ? '…' : print === null ? 'N/A' : ('$' + (print / 100).toFixed(2))}
                </Text>
                <Text style={styles.rectangleButtonText} autoAdjustsFontSize={true}>
                  Copy/Print
                </Text>
              </View>
             </View>

            <Cell cellStyle='RightDetail'
              title='Daily Meals Left'
              detail='Not Available'
            />

            <Cell cellStyle='RightDetail'
              title='Weekly Meals Left'
              detail='Not Available'
            />

        </TableView>
      </ScrollView>
    )
  }
}

let cellMargin = 10
let cellSidePadding = 10
let cellEdgePadding = 10

let styles = StyleSheet.create({
  stage: {
    backgroundColor: '#EFEFF4',
    paddingTop: 20,
    paddingBottom: 20,
  },

  balancesRow: {
    flex: 1,
    flexDirection: 'row',
    marginTop: 0,
    marginBottom: -10,
  },

  rectangle: {
    height: 88,
    flex: 1,
    alignItems: 'center',
    paddingTop: cellSidePadding,
    paddingBottom: cellSidePadding,
    paddingRight: cellEdgePadding,
    paddingLeft: cellEdgePadding,
    marginBottom: cellMargin,
  },

  // Text styling
  financialText: {
    paddingTop: 8,
    color: c.iosDisabledText,
    textAlign: 'center',
    fontWeight: '200',
    fontSize: 23,
  },
  rectangleButtonIcon: {
    color: c.black,
  },
  rectangleButtonText: {
    paddingTop: 15,
    color: c.black,
    textAlign: 'center',
    fontSize: 16,
  },
})
<|endoftext|>


<commit_before>/**
 * Vue Bridge Webview v1.0
 * https://github.com/cmp-cc/vue-bridge-webview
 *
 * Copyright 2016, cmp-cc
 * Released under the MIT license
 */

(function() {

  /**
   *  vue-bridge-webview config
   *
   * @type {{bridgeWebViewDelay: number}}
   */
  var bridgeConfig = {
    bridgeWebViewDelay : 0.3 * 1000 , // 页面启动多久向android/ios 请求数据
    callHandle : {}, // bridge android / ios
    silent : false
  }

  var $bridge = {
    registerHandler : function (name,callback) {
      if(bridgeConfig.silent){
        console.log(name,' register handler failure')
      }
    },
    callHandler : function (name, params, callback) {
      if(bridgeConfig.silent){
        console.log(name,' call handler webView failure')
      }
    }
  };

// ============ device init operation start ===========

  /* setup WebView Javascript Bridge for ios , ios 初始化 */
  function setupWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
  }

  /* 用于创建桥接对象的函数 , android 初始化 */
  function connectWebViewJavascriptBridge(callback) {
    //如果桥接对象已存在，则直接调用callback函数
    if (window.WebViewJavascriptBridge) {
      callback(WebViewJavascriptBridge)
    }
    //否则添加一个监听器来执行callback函数
    else {
      document.addEventListener('WebViewJavascriptBridgeReady', function () {
        callback(WebViewJavascriptBridge)
      }, false)
    }
  }

  /* device detect for ios/android */

  if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    setupWebViewJavascriptBridge(function(bridge){
      $bridge = bridge
    })
  }else if(/(Android)/i.test(navigator.userAgent)) {
   connectWebViewJavascriptBridge(function(bridge){
     $bridge = bridge
   })
  }

// ==============device init operation end ============

  var VueBridgeWebView = {

    install: function(Vue) {
      Vue.prototype.$bridge = this
      Vue.bridge = this

      // config
      bridgeConfig.slient = Vue.config.slient
    },

    /**
     *  Android / IOS 调用JS,需要明确调用的`function名称` .
     *
     *
     * @param name `function name`
     * @param registerCallback 回调的响应事件
     */
    registerHandler : function(name, registerCallback){
      if($bridge['registerHandler']){

        setTimeout(function(){
          $bridge.registerHandler(name,registerCallback)
        },bridgeConfig.bridgeWebViewDelay)

      }else if(bridgeConfig.slient){
        console.log("don't built-in WebView invoking ",name,'{registerHandler}')
      }
    },

    /**
     *  JS 调用 Android / IOS
     *
     *  name: 回调名称, android/ios 名称 ,eg: 'getUserInfo'
     *  params 请求参数, eg: { 'userId' : 1}
     *  callback: response(响应函数)
     *
     *  eg: this.$bridge.callHandler('getUserInfo',{'userId':1},function(data){...})
     *
     */
    callHandler: function(name,params,callback){

      /* 解决部分系统加载延迟导致 ios/android 不响应问题 */
      setTimeout(function(){

        if($bridge['callHandler']){
          $bridge.callHandler(name,params,function(data){
            if(typeof callback == 'function'){
              callback(data);
            }
          })
        }else {
          console.log("don't built-in WebView invoking ",name,'{callHandler}')
        }

      },bridgeConfig.bridgeWebViewDelay)
    }
  }

  if (typeof exports == "object") {
    module.exports = VueBridgeWebView;
  } else if (typeof define == "function" && define.amd) {
    define([], function(){ return VueBridgeWebView; })
  } else if (window.Vue) {
    window.$bridge = VueBridgeWebView
    Vue.use(VueBridgeWebView);
  }else{
    window.$bridge = VueBridgeWebView
  }

})()<commit_msg>update<commit_after>/**
 * Vue Bridge Webview v1.0
 * https://github.com/cmp-cc/vue-bridge-webview
 *
 * Copyright 2016, cmp-cc
 * Released under the MIT license
 */

(function() {

  /**
   *  vue-bridge-webview config
   *
   * @type {{bridgeWebViewDelay: number}}
   */
  var bridgeConfig = {
    bridgeWebViewDelay : 0.3 * 1000 , // 页面启动多久向android/ios 请求数据
    callHandle : {}, // bridge android / ios
    silent : false
  }

  var $bridge = {
    registerHandler : function (name,callback) {
      if(bridgeConfig.silent){
        console.log(name,' register handler failure')
      }
    },
    callHandler : function (name, params, callback) {
      if(bridgeConfig.silent){
        console.log(name,' call handler webView failure')
      }
    }
  };

// ============ device init operation start ===========

  /* setup WebView Javascript Bridge for ios , ios 初始化 */
  function setupWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
  }

  /* 用于创建桥接对象的函数 , android 初始化 */
  function connectWebViewJavascriptBridge(callback) {
    //如果桥接对象已存在，则直接调用callback函数
    if (window.WebViewJavascriptBridge) {
      callback(WebViewJavascriptBridge)
    }
    //否则添加一个监听器来执行callback函数
    else {
      document.addEventListener('WebViewJavascriptBridgeReady', function () {
        callback(WebViewJavascriptBridge)
      }, false)
    }
  }

  /* device detect for ios/android */

  if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    setupWebViewJavascriptBridge(function(bridge){
      $bridge = bridge
    })
  }else if(/(Android)/i.test(navigator.userAgent)) {
   connectWebViewJavascriptBridge(function(bridge){
     $bridge = bridge
   })
  }

// ==============device init operation end ============

  var VueBridgeWebView = {

    install: function(Vue) {
      Vue.prototype.$bridge = this
      Vue.bridge = this

      // config
      bridgeConfig.slient = Vue.config.slient
    },

    /**
     *  Android / IOS 调用JS,需要明确调用的`function名称` .
     *
     *
     * @param name `function name`
     * @param registerCallback 回调的响应事件
     */
    registerHandler : function(name, registerCallback){
      if($bridge['registerHandler']){

        setTimeout(function(){
          $bridge.registerHandler(name,registerCallback)
        },bridgeConfig.bridgeWebViewDelay)

      }else if(bridgeConfig.slient){
        console.log("don't built-in WebView invoking ",name,'{registerHandler}')
      }
    },

    /**
     *  JS 调用 Android / IOS
     *
     *  name: 回调名称, android/ios 名称 ,eg: 'getUserInfo'
     *  params 请求参数, eg: { 'userId' : 1}
     *  callback: response(响应函数)
     *
     *  eg: this.$bridge.callHandler('getUserInfo',{'userId':1},function(data){...})
     *
     */
    callHandler: function(name,params,callback){

        if($bridge['callHandler']){

          $bridge.callHandler(name,params,function(data){
            if(typeof callback == 'function'){
              /* 解决部分系统加载延迟导致 ios/android 不响应问题 */
              setTimeout(function(){
                callback(data);
              },bridgeConfig.bridgeWebViewDelay)
            }
          })

        }else {
          console.log("don't built-in WebView invoking ",name,'{callHandler}')
        }

    }
  }

  if (typeof exports == "object") {
    module.exports = VueBridgeWebView;
  } else if (typeof define == "function" && define.amd) {
    define([], function(){ return VueBridgeWebView; })
  } else if (window.Vue) {
    window.$bridge = VueBridgeWebView
    Vue.use(VueBridgeWebView);
  }else{
    window.$bridge = VueBridgeWebView
  }

})()<|endoftext|>


<commit_before><commit_msg>Updated node's loadACL method to point it to the right rest service.<commit_after><|endoftext|>


<commit_before>describe('Angular.js \'main\' Module', function() {

  var module;

  beforeEach(function() {
    module = angular.module('main');
  });

  it("should be registered", function() {
    expect(module).not.toEqual(null);
  });

  describe("Dependencies:", function() {

    var deps;

    var hasModule = function(m) {
      return deps.indexOf(m) >= 0;
    };

    beforeEach(function() {
      deps = module.value('appName').requires;
    });

    var mainDeps = [
     'ngRoute',

      'ui.bootstrap',

      'templatesCache',

      'fend.progressbar.loading',
      'fend.navbar',

      'home',
      'about',

      'bookmarks',

      'help'
    ];

    mainDeps.forEach(function( depName ) {
      it('should have ' + depName +  ' as a dependency', function() {
        expect(hasModule( depName )).toEqual(true);
      });
    });

  });

});
<commit_msg>lint spaces code review #9<commit_after>describe('Angular.js \'main\' Module', function() {

  var module;

  beforeEach(function() {
    module = angular.module('main');
  });

  it("should be registered", function() {
    expect(module).not.toEqual(null);
  });

  describe("Dependencies:", function() {

    var deps;

    var hasModule = function(m) {
      return deps.indexOf(m) >= 0;
    };

    beforeEach(function() {
      deps = module.value('appName').requires;
    });

    var mainDeps = [
      'ngRoute',

      'ui.bootstrap',

      'templatesCache',

      'fend.progressbar.loading',
      'fend.navbar',

      'home',
      'about',

      'bookmarks',

      'help'
    ];

    mainDeps.forEach(function( depName ) {
      it('should have ' + depName +  ' as a dependency', function() {
        expect(hasModule( depName )).toEqual(true);
      });
    });

  });

});
<|endoftext|>


<commit_before>/**
 * Dependencies.
 */

let React = require('react');
let analytics = require('../../../common/analytics');

/**
 * Post Component.
 *
 * Renders a post inside the default tab.
 *
 * Usage:
 *
 * ```js
 * <Post post={post} />
 * ```
 *
 * Properties:
 *
 * - `post`: Post from the ProductHunt API
 * - `onClick`: On post click cb
 *
 * @class
 */

let Post = React.createClass({

  /**
   * Render the view.
   */

  render() {
    let post = this.props.post;

    return (

            {post.votes_count}

{post.name}

{post.tagline}

            {post.comments_count}

    );
  },

  /**
   * Handle post click events.
   *
   * @param {Object} event
   */

  _onClick(e) {
    e.stopPropagation();
    analytics.clickPost(this.props.post);
    this.props.onClick(this.props.post.discussion_url);
  },

  /**
   * Handle open post click events.
   *
   * @param {Object} event
   */

  _openPost(e) {
    e.stopPropagation();
    analytics.clickPost(this.props.post);
    open(this.props.post.redirect_url);
  }
});

/**
 * Export `Post`.
 */

module.exports = Post;
<commit_msg>Remove obsolete method<commit_after>/**
 * Dependencies.
 */

let React = require('react');
let analytics = require('../../../common/analytics');

/**
 * Post Component.
 *
 * Renders a post inside the default tab.
 *
 * Usage:
 *
 * ```js
 * <Post post={post} />
 * ```
 *
 * Properties:
 *
 * - `post`: Post from the ProductHunt API
 * - `onClick`: On post click cb
 *
 * @class
 */

let Post = React.createClass({

  /**
   * Render the view.
   */

  render() {
    let post = this.props.post;

    return (

            {post.votes_count}

{post.name}

{post.tagline}

            {post.comments_count}

    );
  },

  /**
   * Handle open post click events.
   *
   * @param {Object} event
   */

  _openPost(e) {
    e.stopPropagation();
    analytics.clickPost(this.props.post);
    open(this.props.post.redirect_url);
  }
});

/**
 * Export `Post`.
 */

module.exports = Post;
<|endoftext|>


<commit_before>require.def('lancaster-vision/appui/formatters/searchformatter',
  [
    "antie/formatter",
    "antie/widgets/label",
    "antie/widgets/button",
    "antie/widgets/image",
    "antie/widgets/horizontallist",
    "antie/widgets/verticallist"
  ],
  function(Formatter, Label, Button, Image, HorizontalList, VerticalList) {
    return Formatter.extend({
      format : function (iterator) {
        var button, item, list;
        item = iterator.next();

        var list = new VerticalList("search_" + item.programme_id);

        var width = 310;
        var height = 182;
        item.image_url = "http://148.88.32.64/cache/" + width + "x" + height + "-2/programmes/" + item.image;

        list.appendChildWidget(new Image("trending_img_" + item.programme_id, item.image_url, { width : width, height: height}));

        var prog_details_list = new VerticalList("prog_details");
        prog_details_list.addClass("prog_details");

        var prog_name_label = new Label(item.programme_name);
        prog_name_label.addClass("prog_name");
        prog_details_list.appendChildWidget(prog_name_label);

        var formatted_date = moment(item.watched_at).fromNow();
        var datetime = new Label("Watched " + formatted_date);
        datetime.addClass("watched_at");
        prog_details_list.appendChildWidget(datetime);

        var synopsis = new Label(item.synopsis);
        synopsis.addClass("synopsis");
        prog_details_list.appendChildWidget(synopsis);
        list.appendChildWidget(prog_details_list);

        var buttons_list = new VerticalList("buttons_list");

        // Play button
        this._play = new Button("play_button");
        this._play.appendChildWidget(new Label("Play From Beginning"));
        this._play.addClass("play_button");
        buttons_list.appendChildWidget(this._play);

        prog_details_list.appendChildWidget(buttons_list);

        list.setDataItem(item);
        return list;
      }
    });
  }
);<commit_msg>Remove 'watched at' from search results page<commit_after>require.def('lancaster-vision/appui/formatters/searchformatter',
  [
    "antie/formatter",
    "antie/widgets/label",
    "antie/widgets/button",
    "antie/widgets/image",
    "antie/widgets/horizontallist",
    "antie/widgets/verticallist"
  ],
  function(Formatter, Label, Button, Image, HorizontalList, VerticalList) {
    return Formatter.extend({
      format : function (iterator) {
        var button, item, list;
        item = iterator.next();

        var list = new VerticalList("search_" + item.programme_id);

        var width = 310;
        var height = 182;
        item.image_url = "http://148.88.32.64/cache/" + width + "x" + height + "-2/programmes/" + item.image;

        list.appendChildWidget(new Image("trending_img_" + item.programme_id, item.image_url, { width : width, height: height}));

        var prog_details_list = new VerticalList("prog_details");
        prog_details_list.addClass("prog_details");

        var prog_name_label = new Label(item.programme_name);
        prog_name_label.addClass("prog_name");
        prog_details_list.appendChildWidget(prog_name_label);

        var synopsis = new Label(item.synopsis);
        synopsis.addClass("synopsis");
        prog_details_list.appendChildWidget(synopsis);
        list.appendChildWidget(prog_details_list);

        var buttons_list = new VerticalList("buttons_list");

        // Play button
        this._play = new Button("play_button");
        this._play.appendChildWidget(new Label("Play From Beginning"));
        this._play.addClass("play_button");
        buttons_list.appendChildWidget(this._play);

        prog_details_list.appendChildWidget(buttons_list);

        list.setDataItem(item);
        return list;
      }
    });
  }
);<|endoftext|>