<commit_before>DS.CouchDBSerializer = DS.Serializer.extend({
  primaryKey: function(type) {
    return "_id";
  },
  extractId: function(type, hash) {
    return hash._id || hash.id;
  },
  materializeFromJSON: function(record, hash) {
    this._super.apply(this, arguments);
    record.materializeAttribute("_rev", hash.rev || hash._rev);
    record.materializeAttribute("_id", hash.id || hash._id);
  },
  toJSON: function(record, options) {
    var json = this._super.apply(this, arguments);
    var rev = record.get('_data.attributes._rev');
    if (rev) json._rev = rev;
    json.ember_type = record.constructor.toString();
    return json;
  }
});

DS.CouchDBAdapter = DS.Adapter.extend({
  typeAttribute: 'ember_type',
  typeViewName: 'by-ember-type',
  customTypeLookup: false,

  serializer: DS.CouchDBSerializer,

  _ajax: function(url, type, hash) {
    hash.url = url;
    hash.type = type;
    hash.dataType = 'json';
    hash.contentType = 'application/json; charset=utf-8';
    hash.context = this;

    if (hash.data && type !== 'GET') {
      hash.data = JSON.stringify(hash.data);
    }

    Ember.$.ajax(hash);
  },

  shouldCommit: function(record, relationships) {
    return this._super.apply(arguments);
  },

  ajax: function(url, type, hash) {
    var db = this.get('db');
    return this._ajax('/%@/%@'.fmt(db, url || ''), type, hash);
  },

  stringForType: function(type) {
    return type.toString();
  },

  addTypeProperty: function(json, type) {
    var typeAttribute = this.get('typeAttribute');
    json[typeAttribute] = this.stringForType(type);
  },

  find: function(store, type, id) {
    this.ajax(id, 'GET', {
      context: this,
      success: function(data) {
        store.loadMany(type, [data]);
      }
    });
  },

  findMany: function(store, type, ids) {
    this.ajax('_all_docs', 'POST', {
      data: {
        include_docs: true,
        keys: ids
      },
      context: this,
      success: function(data) {
        store.loadMany(type, data.rows.getEach('doc'));
      }
    });
  },

  findQuery: function(store, type, query, modelArray) {
    var designDoc = this.get('designDoc');
    if (query.type === 'view') {
      this.ajax('_design/%@/_view/%@'.fmt(query.designDoc || designDoc, query.viewName), 'GET', {
        data: query.options,
        success: function(data) {
          modelArray.load(data.rows.getEach('doc'));
        },
        context: this
      });
    }
  },

  findAll: function(store, type) {
    var designDoc = this.get('designDoc');
    if (this.get('customTypeLookup') === true && this.viewForType) {
      var params = {};
      var viewName = this.viewForType(type, params);
      params.include_docs = true;
      this.ajax('_design/%@/_view/%@'.fmt(designDoc, viewName), 'GET', {
        data: params,
        context: this,
        success: function(data) {
          store.loadMany(type, data.rows.getEach('doc'));
        }
      });
    } else {
      var typeViewName = this.get('typeViewName');
      var typeString = this.stringForType(type);
      this.ajax('_design/%@/_view/%@'.fmt(designDoc, typeViewName), 'GET', {
        context: this,
        data: {
          include_docs: true,
          key: encodeURI('"' + typeString + '"')
        },
        success: function(data) {
          store.loadMany(type, data.rows.getEach('doc'));
        }
      });
    }
  },

  createRecord: function(store, type, record) {
    var json = record.toJSON();
    this.addTypeProperty(json, type);
    this.ajax('', 'POST', {
      data: json,
      context: this,
      success: function(data) {
        record.eachAssociation(function(name, meta) {
          if (meta.kind === 'hasMany') {
            store.didUpdateRelationship(record, name);
          }
        });
        store.didSaveRecord(record, $.extend(json, data));
      }
    });
  },

  updateRecord: function(store, type, record) {
    var json = record.toJSON({associations: true, includeId: true });
    this.ajax(record.get('id'), 'PUT', {
      data: json,
      context: this,
      success: function(data) {
        record.eachAssociation(function(name, meta) {
          if (meta.kind === 'hasMany') {
            store.didUpdateRelationship(record, name);
          }
        });
        store.didSaveRecord(record, $.extend(json, data));
      },
      error: function(xhr, textStatus, errorThrown) {
        if (xhr.status === 409) {
          store.recordWasInvalid(record, {});
        }
      }
    });
  },

  deleteRecord: function(store, type, record) {
    this.ajax(record.get('id') + '?rev=' + record.get('_data.attributes._rev'), 'DELETE', {
      context: this,
      success: function(data) {
        store.didDeleteRecord(record);
      }
    });
  }
});<commit_msg>Update CouchDBAdapter to work with Ember-Data revision 8<commit_after>DS.CouchDBSerializer = DS.Serializer.extend({
  primaryKey: function(type) {
    return "_id";
  },
  extractId: function(type, hash) {
    return hash._id || hash.id;
  },
  materializeFromData: function(record, hash) {
    this._super.apply(this, arguments);
    record.materializeAttribute("_rev", hash.rev || hash._rev);
    record.materializeAttribute("_id", hash.id || hash._id);
  },
  toData: function(record, options) {
    var json = this._super.apply(this, arguments);
    var rev = record.get('_data.attributes._rev');
    if (rev) json._rev = rev;
    json.ember_type = record.constructor.toString();
    return json;
  }
});

DS.CouchDBAdapter = DS.Adapter.extend({
  typeAttribute: 'ember_type',
  typeViewName: 'by-ember-type',
  customTypeLookup: false,

  serializer: DS.CouchDBSerializer,

  _ajax: function(url, type, hash) {
    hash.url = url;
    hash.type = type;
    hash.dataType = 'json';
    hash.contentType = 'application/json; charset=utf-8';
    hash.context = this;

    if (hash.data && type !== 'GET') {
      hash.data = JSON.stringify(hash.data);
    }

    Ember.$.ajax(hash);
  },

  shouldCommit: function(record, relationships) {
    return this._super.apply(arguments);
  },

  ajax: function(url, type, hash) {
    var db = this.get('db');
    return this._ajax('/%@/%@'.fmt(db, url || ''), type, hash);
  },

  stringForType: function(type) {
    return type.toString();
  },

  addTypeProperty: function(json, type) {
    var typeAttribute = this.get('typeAttribute');
    json[typeAttribute] = this.stringForType(type);
  },

  find: function(store, type, id) {
    this.ajax(id, 'GET', {
      context: this,
      success: function(data) {
        store.loadMany(type, [data]);
      }
    });
  },

  findMany: function(store, type, ids) {
    this.ajax('_all_docs', 'POST', {
      data: {
        include_docs: true,
        keys: ids
      },
      context: this,
      success: function(data) {
        store.loadMany(type, data.rows.getEach('doc'));
      }
    });
  },

  findQuery: function(store, type, query, modelArray) {
    var designDoc = this.get('designDoc');
    if (query.type === 'view') {
      this.ajax('_design/%@/_view/%@'.fmt(query.designDoc || designDoc, query.viewName), 'GET', {
        data: query.options,
        success: function(data) {
          modelArray.load(data.rows.getEach('doc'));
        },
        context: this
      });
    }
  },

  findAll: function(store, type) {
    var designDoc = this.get('designDoc');
    if (this.get('customTypeLookup') === true && this.viewForType) {
      var params = {};
      var viewName = this.viewForType(type, params);
      params.include_docs = true;
      this.ajax('_design/%@/_view/%@'.fmt(designDoc, viewName), 'GET', {
        data: params,
        context: this,
        success: function(data) {
          store.loadMany(type, data.rows.getEach('doc'));
        }
      });
    } else {
      var typeViewName = this.get('typeViewName');
      var typeString = this.stringForType(type);
      this.ajax('_design/%@/_view/%@'.fmt(designDoc, typeViewName), 'GET', {
        context: this,
        data: {
          include_docs: true,
          key: encodeURI('"' + typeString + '"')
        },
        success: function(data) {
          store.loadMany(type, data.rows.getEach('doc'));
        }
      });
    }
  },

  createRecord: function(store, type, record) {
    var json = this.toData(record);
    this.ajax('', 'POST', {
      data: json,
      context: this,
      success: function(data) {
        record.eachAssociation(function(name, meta) {
          if (meta.kind === 'hasMany') {
            store.didUpdateRelationship(record, name);
          }
        });
        store.didSaveRecord(record, $.extend(json, data));
      }
    });
  },

  updateRecord: function(store, type, record) {
    var json = this.toData(record, {associations: true, includeId: true });
    this.ajax(record.get('id'), 'PUT', {
      data: json,
      context: this,
      success: function(data) {
        record.eachAssociation(function(name, meta) {
          if (meta.kind === 'hasMany') {
            store.didUpdateRelationship(record, name);
          }
        });
        store.didSaveRecord(record, $.extend(json, data));
      },
      error: function(xhr, textStatus, errorThrown) {
        if (xhr.status === 409) {
          store.recordWasInvalid(record, {});
        }
      }
    });
  },

  deleteRecord: function(store, type, record) {
    this.ajax(record.get('id') + '?rev=' + record.get('_data.attributes._rev'), 'DELETE', {
      context: this,
      success: function(data) {
        store.didDeleteRecord(record);
      }
    });
  }
});<|endoftext|>


<commit_before>(function( window, document, undefined ) {
  'use strict';

  var hslEl = document.createElement( 'div' );
  hslEl.classList.add( 'hsl' );
  document.body.appendChild( hslEl );

  window.addEventListener( 'mousemove', function( event ) {
    var x = event.pageX,
        y = event.pageY;

    var h = x / window.innerWidth * 360,
        s = ( window.innerHeight - y ) / window.innerHeight * 100,
        l = 50;

    var hsl = 'hsl(' +
      Math.round( h ) + ', ' +
      Math.round( s ) + '%, ' +
      Math.round( l ) + '%)';

    document.body.style.backgroundColor = hsl;
    hslEl.textContent = hsl;
  });
}) ( window, document );
<commit_msg>palette[picker]: Use mouse wheel to control HSL lightness.<commit_after>(function( window, document, undefined ) {
  'use strict';

  function clamp( value, min, max ) {
    return Math.min( Math.max( value, min ), max );
  }

  var hslEl = document.createElement( 'div' );
  hslEl.classList.add( 'hsl' );
  document.body.appendChild( hslEl );

  var h = 0,
      s = 50,
      l = 50;

  function update() {
    var hsl = 'hsl(' +
      Math.round( h ) + ', ' +
      Math.round( s ) + '%, ' +
      Math.round( l ) + '%)';

    document.body.style.backgroundColor = hsl;
    hslEl.textContent = hsl;
  }

  window.addEventListener( 'mousemove', function( event ) {
    var x = event.pageX,
        y = event.pageY;

    h = x / window.innerWidth * 360;
    s = ( window.innerHeight - y ) / window.innerHeight * 100;

    update();
  });

  window.addEventListener( 'wheel', function( event ) {
    event.preventDefault();
    l = clamp( l - event.deltaY, 0, 100 );
    update();
  });

  update();
}) ( window, document );
<|endoftext|>


<commit_before>function strip_tags(str, allowed_tags) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: strip_tags('
Kevin

van Zonneveld', ',');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: strip_tags('
Kevin van Zonneveld
', '
');
    // *     returns 2: '
Kevin van Zonneveld
'
    // *     example 3: strip_tags("Kevin van Zonneveld", "");
    // *     returns 3: 'Kevin van Zonneveld'

    var key = '', tag = '', allowed = false;
    var matches = allowed_array = [];
    var allowed_keys = {};

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_tags  = allowed_tags.replace(/[^a-zA-Z,]+/g, '');;
        allowed_array = allowed_tags.split(',');
    }

    str += '';

    // Match tags
    matches = str.match(/(<\/?[^>]+>)/gi);

    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }

        // Save HTML tag
        html = matches[key].toString();

        // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }

        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }

    return str;
}<commit_msg>Unfinished: strip_tags implementation is not correct<commit_after>function strip_tags(str, allowed_tags) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: strip_tags('
Kevin

van Zonneveld', '');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: strip_tags('
Kevin van Zonneveld
', '
');
    // *     returns 2: '
Kevin van Zonneveld
'
    // *     example 3: strip_tags("Kevin van Zonneveld", "");
    // *     returns 3: 'Kevin van Zonneveld'

    var key = '', tag = '', allowed = false;
    var matches = allowed_array = [];
    var allowed_keys = {};

    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };

    // Build allowes tags associative array
    if (allowed_tags) {
        //allowed_tags  = allowed_tags.replace(/[^a-zA-Z,]+/g, '');;
        //allowed_array = allowed_tags.split(',');
        allowed_array = allowed_tags.match(/<\/?([^>]+)>/gi);
    }
	tester_print_r(allowed_array);

    str += '';

    // Match tags
    matches = str.match(/(<\/?[^>]+>)/gi);

    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }

        // Save HTML tag
        html = matches[key].toString();

        // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }

        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }

    return str;
}<|endoftext|>


<commit_before>const build = require('@glimmer/build');
const buildVendorPackage = require('@glimmer/build/lib/build-vendor-package');
const funnel = require('broccoli-funnel');
const path = require('path');

module.exports = function() {
  let buildOptions = {};

  if (process.env.BROCCOLI_ENV === 'tests') {
    buildOptions.vendorTrees = [
      buildVendorPackage('@glimmer/compiler', {
        external: ['babel-helpers', '@glimmer/syntax', '@glimmer/wire-format', '@glimmer/util'] }),
      buildVendorPackage('@glimmer/component', {
        external: ['babel-helpers', '@glimmer/di', '@glimmmer/reference', '@glimmer/runtime', '@glimmer/object-reference', '@glimmer/util'] }),
      buildVendorPackage('@glimmer/di', {
        external: ['babel-helpers'] }),
      buildVendorPackage('@glimmer/object-reference', {
        external: ['babel-helpers', '@glimmer/util', '@glimmer/reference'] }),
      buildVendorPackage('@glimmer/reference', {
        external: ['babel-helpers', '@glimmer/util'] }),
      buildVendorPackage('@glimmer/runtime', {
        external: ['babel-helpers',
                  '@glimmer/util',
                  '@glimmer/reference',
                  '@glimmer/wire-format',
                  '@glimmer/syntax']}),
      buildVendorPackage('@glimmer/syntax', {
        external: ['babel-helpers', 'handlebars', 'simple-html-tokenizer'] }),
      buildVendorPackage('@glimmer/util', {
        external: ['babel-helpers'] }),
      buildVendorPackage('@glimmer/wire-format', {
        external: ['@glimmer/util'] }),
      buildVendorPackage('simple-html-tokenizer'),
      funnel(path.dirname(require.resolve('handlebars/package')), {
        include: ['dist/handlebars.amd.js'] })
    ];
  }

  return build(buildOptions);
};<commit_msg>Ember CLI env<commit_after>const build = require('@glimmer/build');
const buildVendorPackage = require('@glimmer/build/lib/build-vendor-package');
const funnel = require('broccoli-funnel');
const path = require('path');

module.exports = function() {
  let buildOptions = {};

  if (process.env.EMBER_ENV === 'test') {
    buildOptions.vendorTrees = [
      buildVendorPackage('@glimmer/compiler', {
        external: ['babel-helpers', '@glimmer/syntax', '@glimmer/wire-format', '@glimmer/util'] }),
      buildVendorPackage('@glimmer/component', {
        external: ['babel-helpers', '@glimmer/di', '@glimmmer/reference', '@glimmer/runtime', '@glimmer/object-reference', '@glimmer/util'] }),
      buildVendorPackage('@glimmer/di', {
        external: ['babel-helpers'] }),
      buildVendorPackage('@glimmer/object-reference', {
        external: ['babel-helpers', '@glimmer/util', '@glimmer/reference'] }),
      buildVendorPackage('@glimmer/reference', {
        external: ['babel-helpers', '@glimmer/util'] }),
      buildVendorPackage('@glimmer/runtime', {
        external: ['babel-helpers',
                  '@glimmer/util',
                  '@glimmer/reference',
                  '@glimmer/wire-format',
                  '@glimmer/syntax']}),
      buildVendorPackage('@glimmer/syntax', {
        external: ['babel-helpers', 'handlebars', 'simple-html-tokenizer'] }),
      buildVendorPackage('@glimmer/util', {
        external: ['babel-helpers'] }),
      buildVendorPackage('@glimmer/wire-format', {
        external: ['@glimmer/util'] }),
      buildVendorPackage('simple-html-tokenizer'),
      funnel(path.dirname(require.resolve('handlebars/package')), {
        include: ['dist/handlebars.amd.js'] })
    ];
  }

  return build(buildOptions);
}

function includeVendorPackage(name) {
  // Resolve package's `package.json`, in case `main` is set and it points deep
  // into a `dist` directory.
  let packagePath = require.resolve(`${name}/package`);
  packagePath = path.dirname(packagePath);

  return funnel(packagePath, {
    include: [
      'dist/amd/es5/**/*.js',
      'amd/es5/**/*.js'
    ]
  });
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { Table, TableCell, TableRow, TableBody } from 'react-components';

import KeysActions from './KeysActions';
import KeysStatus from './KeysStatus';

const KeysTable = ({ keys = [], onAction }) => {
    const headerCells = [
        { node: c('Title header for keys table').t`Fingerprint`, className: 'w50' },
        { node: c('Title header for keys table').t`Key type` },
        { node: c('Title header for keys table').t`Status` },
        { node: c('Title header for keys table').t`Actions` }
    ].map(({ node, className = '' }, i) => {
        return (
            <TableCell key={i.toString()} className={className} type="header">
                {node}
            </TableCell>
        );
    });

    return (

{headerCells}

            <TableBody colSpan={4}>
                {keys.map(({ ID, fingerprint, algorithm, isLoading, status, permissions }, idx) => {
                    return (
                        <TableRow
                            key={ID}
                            cells={[

                                    {fingerprint}
                                ,
                                algorithm,
                                <KeysStatus key={2} {...status} />,
                                <KeysActions
                                    key={3}
                                    loading={isLoading}
                                    onAction={(action) => onAction(action, idx)}
                                    {...permissions}
                                />
                            ]}
                        />
                    );
                })}
            </TableBody>

    );
};

KeysTable.propTypes = {
    keys: PropTypes.array,
    onAction: PropTypes.func.isRequired,
    loadingKeyID: PropTypes.bool
};

export default KeysTable;
<commit_msg>Show fingerprints in title and add a copy button (#395)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { Table, TableCell, TableRow, TableBody } from 'react-components';

import KeysActions from './KeysActions';
import KeysStatus from './KeysStatus';
import { Copy } from '../../components/button';

const KeysTable = ({ keys = [], onAction }) => {
    const headerCells = [
        { node: c('Title header for keys table').t`Fingerprint`, className: 'w50' },
        { node: c('Title header for keys table').t`Key type` },
        { node: c('Title header for keys table').t`Status` },
        { node: c('Title header for keys table').t`Actions` }
    ].map(({ node, className = '' }, i) => {
        return (
            <TableCell key={i.toString()} className={className} type="header">
                {node}
            </TableCell>
        );
    });

    return (

{headerCells}

            <TableBody colSpan={4}>
                {keys.map(({ ID, fingerprint, algorithm, isLoading, status, permissions }, idx) => {
                    return (
                        <TableRow
                            key={ID}
                            cells={[

                                    <Copy value={fingerprint} className="pm-button--small" />

                                        {fingerprint}

,
                                algorithm,
                                <KeysStatus key={2} {...status} />,
                                <KeysActions
                                    key={3}
                                    loading={isLoading}
                                    onAction={(action) => onAction(action, idx)}
                                    {...permissions}
                                />
                            ]}
                        />
                    );
                })}
            </TableBody>

    );
};

KeysTable.propTypes = {
    keys: PropTypes.array,
    onAction: PropTypes.func.isRequired,
    loadingKeyID: PropTypes.bool
};

export default KeysTable;
<|endoftext|>


<commit_before>$(document).ready(function() {
	$.ajax({
		type : 'get',
		dataType : 'json',
		url : '/ke/metrics/brokers/mbean/ajax',
		success : function(datas) {
			if (datas != null) {
				$("#kafka_metrics_tab").html("")
				var thead = "

Rate	Mean	1 Minute	5 Minute	15 Minute

";
				$("#kafka_metrics_tab").append(thead);
				var tbody = "
";
				var msg = brokerMetricData('Messages in /sec', datas.msg);

				msg += brokerMetricData('Bytes in /sec', datas.ins);

				msg += brokerMetricData('Bytes out /sec', datas.out);

				msg += brokerMetricData('Bytes rejected /sec', datas.rejected);

				msg += brokerMetricData('Failed fetch request /sec', datas.fetch);

				msg += brokerMetricData('Failed produce request /sec', datas.produce);

				msg += brokerMetricData('Total fetch requests /sec', datas.total_fetch_requests);

				msg += brokerMetricData('Total produce requests /sec', datas.total_produce_requests);

				msg += brokerMetricData('Replication byte in /sec', datas.replication_bytes_in);

				msg += brokerMetricData('Replication byte out /sec', datas.replication_bytes_out);

				msg += brokerMetricData('Produce message conversions /sec', datas.produce_message_conversions);

				tbody += msg + "
"
				$("#kafka_metrics_tab").append(tbody);
			}
		}
	});
});

function brokerMetricData(field, data) {
	var tr = '';
	if (data == null || data == undefined) {
		return tr;
	}

	console.log(field.toUpperCase());

	if (field.toUpperCase().indexOf("BYTE") > -1) {
		console.log("dsdsd");
		tr += "
" + field + "	" + data.meanRate + "	" + data.oneMinute + "	" + data.fiveMinute
				+ "	" + data.fifteenMinute + "
";
	} else {
		tr += "
" + field + "	" + data.meanRate.split("B")[0] + "	" + data.oneMinute.split("B")[0]
				+ "	" + data.fiveMinute.split("B")[0] + "	" + data.fifteenMinute.split("B")[0] + "
";
	}

	return tr;
}<commit_msg>remove print message<commit_after>$(document).ready(function() {
	$.ajax({
		type : 'get',
		dataType : 'json',
		url : '/ke/metrics/brokers/mbean/ajax',
		success : function(datas) {
			if (datas != null) {
				$("#kafka_metrics_tab").html("")
				var thead = "

Rate	Mean	1 Minute	5 Minute	15 Minute

";
				$("#kafka_metrics_tab").append(thead);
				var tbody = "
";
				var msg = brokerMetricData('Messages in /sec', datas.msg);

				msg += brokerMetricData('Bytes in /sec', datas.ins);

				msg += brokerMetricData('Bytes out /sec', datas.out);

				msg += brokerMetricData('Bytes rejected /sec', datas.rejected);

				msg += brokerMetricData('Failed fetch request /sec', datas.fetch);

				msg += brokerMetricData('Failed produce request /sec', datas.produce);

				msg += brokerMetricData('Total fetch requests /sec', datas.total_fetch_requests);

				msg += brokerMetricData('Total produce requests /sec', datas.total_produce_requests);

				msg += brokerMetricData('Replication byte in /sec', datas.replication_bytes_in);

				msg += brokerMetricData('Replication byte out /sec', datas.replication_bytes_out);

				msg += brokerMetricData('Produce message conversions /sec', datas.produce_message_conversions);

				tbody += msg + "
"
				$("#kafka_metrics_tab").append(tbody);
			}
		}
	});
});

function brokerMetricData(field, data) {
	var tr = '';
	if (data == null || data == undefined) {
		return tr;
	}

	if (field.toUpperCase().indexOf("BYTE") > -1) {
		console.log("dsdsd");
		tr += "
" + field + "	" + data.meanRate + "	" + data.oneMinute + "	" + data.fiveMinute
				+ "	" + data.fifteenMinute + "
";
	} else {
		tr += "
" + field + "	" + data.meanRate.split("B")[0] + "	" + data.oneMinute.split("B")[0]
				+ "	" + data.fiveMinute.split("B")[0] + "	" + data.fifteenMinute.split("B")[0] + "
";
	}

	return tr;
}<|endoftext|>


<commit_before>const getFiltersOnNumber = require('./getFiltersOnNumber')
const LATEST_INCOME_FIELD = 'income.latest.total'

const getIncomeFilters = income => {
  if (!income) return []

  const numericRange = income.latest && income.latest.total

  return getFiltersOnNumber(LATEST_INCOME_FIELD, numericRange)
}

module.exports = getIncomeFilters<commit_msg>fix(filters): amend latest income field<commit_after>const getFiltersOnNumber = require('./getFiltersOnNumber')
const LATEST_INCOME_FIELD = 'financial.latest.income'

const getIncomeFilters = income => {
  if (!income) return []

  const numericRange = income.latest && income.latest.total

  return getFiltersOnNumber(LATEST_INCOME_FIELD, numericRange)
}

module.exports = getIncomeFilters<|endoftext|>


<commit_before>require('dotenv').config();
var app = require('express')();
var ringcentral = require('ringcentral');

// Configure Mustache
var mustacheExpress = require('mustache-express');
app.engine('mustache', mustacheExpress());
app.set('view engine', 'mustache');
app.set('views', __dirname + '/views');

// Start HTTP server
var server = null;
var port = process.env.MY_APP_PORT;
var useTls = process.env.MY_APP_TLS_ENABLED > 0 ? true : false;

if (useTls) {
  var fs = require('fs');
  server = require('https')
    .createServer({
      key: fs.readFileSync(process.env.MY_APP_TLS_PRIVATE_KEY),
      cert: fs.readFileSync(process.env.MY_APP_TLS_PUBLIC_CERT)
    }, app)
    .listen(port, function() {
      console.log('LISTEN_HTTPS ' + port);
    });
} else {
  server = require('http')
    .Server(app)
    .listen(port, function() {
      console.log('LISTEN_HTTP ' + port);
    });
}

// Start RingCentral SDK
var rcsdk = new ringcentral({
  server: process.env.RC_APP_SERVER_URL,
  appKey: process.env.RC_APP_KEY,
  appSecret: process.env.RC_APP_SECRET
});

app.get('/', function(req, res) {
  // Get token for display after OAuth
  token = rcsdk.platform().auth().data();
  token_json = token['access_token'] ? JSON.stringify(token, null, ' ') : '';

  // Render home page with params
  res.render('index', {
    authorize_uri: rcsdk.platform().authUrl({
      brandId: process.env.RC_APP_BRAND_ID,
      redirectUri: process.env.RC_APP_REDIRECT_URL
    }),
    redirect_uri: process.env.RC_APP_REDIRECT_URL,
    token_json: token_json
  });
});

app.get('/callback', function(req, res) {
  if (req.query.code) {
    rcsdk.platform()
      .login({
        code: req.query.code,
        redirectUri: process.env.RC_APP_REDIRECT_URL
      })
      .then(function(response) {
        console.log('logged_in');
        res.send('');
      })
      .catch(function(e) {
        console.log('ERR ' + e.message  || 'Server cannot authorize user');
        res.send('');
      });
  } else {
    res.send('');
  }
});
<commit_msg>add comments<commit_after>require('dotenv').config();
var app = require('express')();
var ringcentral = require('ringcentral');

// Configure Mustache
var mustacheExpress = require('mustache-express');
app.engine('mustache', mustacheExpress());
app.set('view engine', 'mustache');
app.set('views', __dirname + '/views');

// Start HTTP server
var server = null;
var port = process.env.MY_APP_PORT;
var useTls = process.env.MY_APP_TLS_ENABLED > 0 ? true : false;

if (useTls) {
  var fs = require('fs');
  server = require('https')
    .createServer({
      key: fs.readFileSync(process.env.MY_APP_TLS_PRIVATE_KEY),
      cert: fs.readFileSync(process.env.MY_APP_TLS_PUBLIC_CERT)
    }, app)
    .listen(port, function() {
      console.log('LISTEN_HTTPS ' + port);
    });
} else {
  server = require('http')
    .Server(app)
    .listen(port, function() {
      console.log('LISTEN_HTTP ' + port);
    });
}

// Start RingCentral SDK
var rcsdk = new ringcentral({
  server: process.env.RC_APP_SERVER_URL,
  appKey: process.env.RC_APP_KEY,
  appSecret: process.env.RC_APP_SECRET
});

app.get('/', function(req, res) {
  // Get token for display after OAuth
  token = rcsdk.platform().auth().data();
  token_json = token['access_token'] ? JSON.stringify(token, null, ' ') : '';

  // Render home page with params
  res.render('index', {
    authorize_uri: rcsdk.platform().authUrl({
      brandId: process.env.RC_APP_BRAND_ID,        // optional
      redirectUri: process.env.RC_APP_REDIRECT_URL // optional if 1 configured
    }),
    redirect_uri: process.env.RC_APP_REDIRECT_URL,
    token_json: token_json
  });
});

app.get('/callback', function(req, res) {
  if (req.query.code) {
    rcsdk.platform()
      .login({
        code: req.query.code,
        redirectUri: process.env.RC_APP_REDIRECT_URL
      })
      .then(function(response) {
        console.log('logged_in');
        res.send('');
      })
      .catch(function(e) {
        console.log('ERR ' + e.message  || 'Server cannot authorize user');
        res.send('');
      });
  } else {
    res.send('');
  }
});
<|endoftext|>


<commit_before>var path = require('path');
var extend = require('extend-shallow');
var _ = require('lodash');
var objParser = require('l10n-tools/object-extractor');

module.exports = function(assemble) {
  //var mergeTranslated = require('../utils/merge-tranlated-dictionary');
  var parseFilePath = require('../utils/parse-file-path')(assemble);
  var extendFileData = require('../utils/extend-file-data')(assemble);
  var environment = assemble.option('environment');
  var websiteRoot = assemble.get('data.websiteRoot');
  var basename = assemble.get('data.basename');
  var locales = assemble.get('data.locales');

  return function mergeTranslatedData (file, next) {
    var lang = assemble.get('lang');
    var subfoldersRoot = assemble.get('data.subfoldersRoot');
    var pageData = assemble.get('pageData');
    var dicts = assemble.get('dicts');
    var locale, dataKey, localeData, parsedTranslations, filePathData, dictKey;

    //get keys for accessing dictionary and locale type
    filePathData = parseFilePath(file.path);
    locale = filePathData.locale;
    dataKey = filePathData.dataKey;

    //extend the file with the external YML content
    extendFileData(filePathData, file);

    //TODO: problem this won't work for modals because they are not scoped to the locale???
    //put in custom function for replacing translated array values
    if(filePathData.isSubfolder) {
      dictKey = locales[locale]; //this gives the dictionary key ex. de_DE from _assemble config

      /**
       *
       * Enter translation function here
       * on `file` object only need to parse HTML_page_content
       * on `file.data` object parse and replace all content with TR or MD key
       * must iterate through all keys as some TR/MD keys may be nested in non-TR/MD
       * we are not translating modals, layouts, or partials here -- only subfolders
       *
      **/

      //replace the content of the page if it has been flagged for translation
      if(file.HTML_page_content) {
        file.content = file.HTML_page_content;
        delete file.HTML_page_content;
      }
      file = objParser.translate(file, dicts[dictKey]);
    }

    next();
  };
};
<commit_msg>use objParser for extracting&translation<commit_after>var path = require('path');
var extend = require('extend-shallow');
var _ = require('lodash');
var objParser = require('l10n-tools/object-extractor');

module.exports = function(assemble) {
  //var mergeTranslated = require('../utils/merge-tranlated-dictionary');
  var parseFilePath = require('../utils/parse-file-path')(assemble);
  var extendFileData = require('../utils/extend-file-data')(assemble);
  var environment = assemble.option('environment');
  var websiteRoot = assemble.get('data.websiteRoot');
  var basename = assemble.get('data.basename');
  var locales = assemble.get('data.locales');

  return function mergeTranslatedData (file, next) {
    var lang = assemble.get('lang');
    var subfoldersRoot = assemble.get('data.subfoldersRoot');
    var pageData = assemble.get('pageData');
    var dicts = assemble.get('dicts');
    var locale, dataKey, localeData, parsedTranslations, filePathData, dictKey;

    //get keys for accessing dictionary and locale type
    filePathData = parseFilePath(file.path);
    locale = filePathData.locale;
    dataKey = filePathData.dataKey;

    //extend the file with the external YML content
    extendFileData(filePathData, file);

    //TODO: problem this won't work for modals because they are not scoped to the locale???
    //put in custom function for replacing translated array values
    if(filePathData.isSubfolder) {
      dictKey = locales[locale]; //this gives the dictionary key ex. de_DE from _assemble config

      /**
       *
       * Enter translation function here
       * on `file` object only need to parse HTML_page_content
       * on `file.data` object parse and replace all content with TR or MD key
       * must iterate through all keys as some TR/MD keys may be nested in non-TR/MD
       * we are not translating modals, layouts, or partials here -- only subfolders
       *
      **/

      //replace the content of the page if it has been flagged for translation
      if(file.HTML_page_content) {
        file.content = file.HTML_page_content;
        delete file.HTML_page_content;
      }
      // file.path should match value from smartling.js
      file = objParser.translate(file, dicts[dictKey][file.path]);
    }

    next();
  };
};
<|endoftext|>


<commit_before>//= require jquery
//= require esphinx/support/jquery
//= require esphinx/support/ajax

"use strict";

var
    jQuery;

(function ($) {

    $.prototype.autocomplete = function (obj, args, callback) {
        var
            found = [],
            self = $(this),
            domObjText,
            searchIndex,
            prevSliceTextNoSearch,
            sliceFound,
            remainderSliceTextNoSearch,
            spanSliceFound,
            copyng,
            jqObj,
            amountChar,
            tagName,

            prepare = function (obj, order) {
                if (!order) {
                    order = "asc";
                }
                order = order.toLocaleLowerCase();

                found = [];
                tagName = obj.prop("tagName").toLowerCase();
                if (tagName === "li") {
                    obj.sortByTextContent(order).each(function (i, domObj) {
                        domObjText = domObj.textContent.trim();
                        searchIndex = domObjText.toLowerCase()
                            .search(self.val().toLowerCase());
                        if (searchIndex > -1) {

                            prevSliceTextNoSearch = domObjText
                                .slice(0, searchIndex);

                            sliceFound = domObjText.slice(prevSliceTextNoSearch
                                .length, prevSliceTextNoSearch.length +
                                    self.val().length);

                            remainderSliceTextNoSearch = domObjText
                                .slice(prevSliceTextNoSearch.length +
                                    sliceFound.length, domObjText.length);

                            spanSliceFound = $("");

                            copyng = $(domObj.cloneNode());
                            copyng.append(prevSliceTextNoSearch);
                            copyng.append(spanSliceFound);
                            spanSliceFound.addClass("esphinx-ui-slice-found");
                            spanSliceFound.text(sliceFound);
                            copyng.append(remainderSliceTextNoSearch);

                            found.push(copyng.get(0));
                        }
                    });
                } // caso necessário, usar recursividade para reenviar formatado como li
                return $(found);
            };

        if (obj instanceof jQuery) {
            if (args.afterAmountChar) {
                amountChar = args.afterAmountChar;
            } else {
                amountChar = 1;
            }

            self.on("keyup", function (e) {
                if (self.val()) {
                    if (self.val().length >= amountChar) {
                        callback(e, prepare(obj, args.order));
                    }
                } else {
                    callback(e, []);
                }
            });
        } else if (obj instanceof Object) {

            callback = args;
            args = obj;

            if (args.afterAmountChar) {
                amountChar = args.afterAmountChar;
            } else {
                amountChar = 1;
            }

            // a consulta é renovada, para tal este evento não deve ser removido
            self.on("keyup", function (e) {
                if (self.val().length === amountChar) {
                    args.remote.query(e, function (q) {
                        Ajax({
                            url: args.remote.url,
                            params: q
                        })
                        .processing(function (xhr) {
                            if (args.remote.processing) {
                                args.remote.processing(xhr, e);
                            }
                            $(e.target).on("keypress", function (e) {
                                e.preventDefault();
                            });
                        })
                        .done(function (a) {
                            $(e.target).off("keypress");
                            if (callback instanceof Function) {
                                jqObj = $(a).find("li");
                                callback(e, prepare(jqObj, args.order));
                                if (jqObj.length) {
                                    self.autocomplete(jqObj, args, callback);
                                }
                            }
                        });
                    });
                }
            });
        }
    };

})(jQuery);
<commit_msg>muda renomeia método respondWith<commit_after>//= require jquery
//= require esphinx/support/jquery
//= require esphinx/support/ajax

"use strict";

var
    jQuery;

(function ($) {

    $.prototype.autocomplete = function (obj, args, callback) {
        var
            found = [],
            self = $(this),
            domObjText,
            searchIndex,
            prevSliceTextNoSearch,
            sliceFound,
            remainderSliceTextNoSearch,
            spanSliceFound,
            copyng,
            jqObj,
            amountChar,
            tagName,

            respondTo = function (obj, order) {
                if (!order) {
                    order = "asc";
                }
                order = order.toLocaleLowerCase();

                found = [];
                tagName = obj.prop("tagName").toLowerCase();
                if (tagName === "li") {
                    obj.sortByTextContent(order).each(function (i, domObj) {
                        domObjText = domObj.textContent.trim();
                        searchIndex = domObjText.toLowerCase()
                            .search(self.val().toLowerCase());
                        if (searchIndex > -1) {

                            prevSliceTextNoSearch = domObjText
                                .slice(0, searchIndex);

                            sliceFound = domObjText.slice(prevSliceTextNoSearch
                                .length, prevSliceTextNoSearch.length +
                                    self.val().length);

                            remainderSliceTextNoSearch = domObjText
                                .slice(prevSliceTextNoSearch.length +
                                    sliceFound.length, domObjText.length);

                            spanSliceFound = $("");

                            copyng = $(domObj.cloneNode());
                            copyng.append(prevSliceTextNoSearch);
                            copyng.append(spanSliceFound);
                            spanSliceFound.addClass("esphinx-ui-slice-found");
                            spanSliceFound.text(sliceFound);
                            copyng.append(remainderSliceTextNoSearch);

                            found.push(copyng.get(0));
                        }
                    });
                } // caso necessário, usar recursividade para reenviar formatado como li
                return $(found);
            };

        if (obj instanceof jQuery) {
            if (args.afterAmountChar) {
                amountChar = args.afterAmountChar;
            } else {
                amountChar = 1;
            }

            self.on("keyup", function (e) {
                if (self.val()) {
                    if (self.val().length >= amountChar) {
                        callback(e, respondTo(obj, args.order));
                    }
                } else {
                    callback(e, []);
                }
            });
        } else if (obj instanceof Object) {

            callback = args;
            args = obj;

            if (args.afterAmountChar) {
                amountChar = args.afterAmountChar;
            } else {
                amountChar = 1;
            }

            // a consulta é renovada, para tal este evento não deve ser removido
            self.on("keyup", function (e) {
                if (self.val().length === amountChar) {
                    args.remote.query(e, function (q) {
                        Ajax({
                            url: args.remote.url,
                            params: q
                        })
                        .processing(function (xhr) {
                            if (args.remote.processing) {
                                args.remote.processing(xhr, e);
                            }
                            $(e.target).on("keypress", function (e) {
                                e.preventDefault();
                            });
                        })
                        .done(function (a) {
                            $(e.target).off("keypress");
                            if (callback instanceof Function) {
                                jqObj = $(a).find("li");
                                callback(e, respondTo(jqObj, args.order));
                                if (jqObj.length) {
                                    self.autocomplete(jqObj, args, callback);
                                }
                            }
                        });
                    });
                }
            });
        }
    };

})(jQuery);
<|endoftext|>


<commit_before>var refresh_weather = function () {
  function set_weather_info (elem, info) {
    $(elem).html("
 "+info.fields.apparent_temperature+"°C");
  }

  function reset_weather_info() {
    $("#weather-general").html("");
  }
  $.get("/homecontroller/weather/get_json", function (data) {
    reset_weather_info();
    var first_date = moment(), plus_one = false;
    var hour = parseInt(first_date.format("H")) + 1;
    if (hour >= 23) {
      first_date = first_date.add(1, "days");
      plus_one = true;
      hour = 0;
    }
    var today = first_date.format("YYYY-MM-DD");
    $.each(data, function () {
      var this_data = this;
      if (this.fields.date == today) {
        // Current day
        if (this.fields.hour == hour) {
          set_weather_info("#weather-general", this_data);
          return false;
        }
      }
    });
  });
}
$(document).ready(function () {
  refresh_weather();
  setInterval(refresh_weather, 300000); // 5 minutes
});
<commit_msg>Always show current weather.<commit_after>var refresh_weather = function () {
  function set_weather_info (elem, info) {
    $(elem).html("
 "+info.fields.apparent_temperature+"°C");
  }

  function reset_weather_info() {
    $("#weather-general").html("");
  }
  $.get("/homecontroller/weather/get_json", function (data) {
    reset_weather_info();
    var current_time = moment().add(1, "hours");
    var today = current_time.format("YYYY-MM-DD");
    var hour = current_time.format("H")
    $.each(data, function () {
      var this_data = this;
      if (this.fields.date == today) {
        // Current day
        if (this.fields.hour == hour) {
          set_weather_info("#weather-general", this_data);
          return false;
        }
      }
    });
  });
}
$(document).ready(function () {
  refresh_weather();
  setInterval(refresh_weather, 300000); // 5 minutes
});
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

/* eslint-disable no-invalid-this */

'use strict';

// MODULES //

var logger = require( 'debug' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;

// VARIABLES //

var debug = logger( 'plot:set:symbols-size' );

// MAIN //

/**
* Sets the symbols size.
*
* @private
* @param {(NonNegativeInteger|Array<NonNegativeInteger>)} v - size
* @throws {TypeError} must be a nonnegative integer or nonnegative integer array
* @returns {void}
*/
function set( v ) {
	/* eslint-disable no-invalid-this */
	var isInt = isNonNegativeInteger( v );
	if (
		!isInt &&
		!isNonNegativeIntegerArray( v )
	) {
		throw new TypeError( 'invalid value. `symbolsSize` must be a nonnegative integer or nonnegative integer array. Value: `' + v + '.`' );
	}
	if ( isInt ) {
		v = [ v ];
	} else {
		v = v.slice();
	}
	debug( 'Current value: %s.', JSON.stringify( this._symbolsSize ) );

	this._symbolsSize = v;
	debug( 'New Value: %s.', JSON.stringify( this._symbolsSize ) );

	this.emit( 'change' );
}

// EXPORTS //

module.exports = set;
<commit_msg>Remove line breaks<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

/* eslint-disable no-invalid-this */

'use strict';

// MODULES //

var logger = require( 'debug' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;

// VARIABLES //

var debug = logger( 'plot:set:symbols-size' );

// MAIN //

/**
* Sets the symbols size.
*
* @private
* @param {(NonNegativeInteger|Array<NonNegativeInteger>)} v - size
* @throws {TypeError} must be a nonnegative integer or nonnegative integer array
* @returns {void}
*/
function set( v ) {
	/* eslint-disable no-invalid-this */
	var isInt = isNonNegativeInteger( v );
	if ( !isInt && !isNonNegativeIntegerArray( v ) ) {
		throw new TypeError( 'invalid value. `symbolsSize` must be a nonnegative integer or nonnegative integer array. Value: `' + v + '.`' );
	}
	if ( isInt ) {
		v = [ v ];
	} else {
		v = v.slice();
	}
	debug( 'Current value: %s.', JSON.stringify( this._symbolsSize ) );

	this._symbolsSize = v;
	debug( 'New Value: %s.', JSON.stringify( this._symbolsSize ) );

	this.emit( 'change' );
}

// EXPORTS //

module.exports = set;
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var isString = require( '@stdlib/utils/is-string' ).isPrimitive;

// MAIN //

/**
* Uncapitalizes the first character of a string.
*
* @param {string} str - input string
* @throws {TypeError} must provide a string primitive
* @returns {string} input string with first character converted lowercase
*
* @example
* var out = uncapitalize( 'Last man standing' );
* // returns  'last man standing'
* @example
* var out = uncapitalize( 'Presidential election' );
* // returns 'presidential Election'
* @example
* var out = uncapitalize( 'JavaScript' );
* // returns 'javaScript'
* @example
* var out = uncapitalize( 'Hidden Treasures' );
* // returns 'hidden Treasures';
*/
function uncapitalize( str ) {
	if ( !isString( str ) ) {
		throw new TypeError( 'invalid input argument. First argument must be a string primitive. Value: `' + str + '`.' );
	}
	if ( str === '' ) {
		return '';
	}
	return str.charAt( 0 ).toLowerCase() + str.slice( 1 );
} // end FUNCTION uncapitalize()

// EXPORTS //

module.exports = uncapitalize;
<commit_msg>Fix example<commit_after>'use strict';

// MODULES //

var isString = require( '@stdlib/utils/is-string' ).isPrimitive;

// MAIN //

/**
* Uncapitalizes the first character of a string.
*
* @param {string} str - input string
* @throws {TypeError} must provide a string primitive
* @returns {string} input string with first character converted lowercase
*
* @example
* var out = uncapitalize( 'Last man standing' );
* // returns  'last man standing'
* @example
* var out = uncapitalize( 'Presidential election' );
* // returns 'presidential election'
* @example
* var out = uncapitalize( 'JavaScript' );
* // returns 'javaScript'
* @example
* var out = uncapitalize( 'Hidden Treasures' );
* // returns 'hidden Treasures';
*/
function uncapitalize( str ) {
	if ( !isString( str ) ) {
		throw new TypeError( 'invalid input argument. First argument must be a string primitive. Value: `' + str + '`.' );
	}
	if ( str === '' ) {
		return '';
	}
	return str.charAt( 0 ).toLowerCase() + str.slice( 1 );
} // end FUNCTION uncapitalize()

// EXPORTS //

module.exports = uncapitalize;
<|endoftext|>


<commit_before>define(["dojo/_base/declare", "dojo/_base/lang", "dojo/_base/Deferred", "dojo/on", "put-selector/put", "./List"], function(declare, lang, Deferred, listen, put, List){
return declare([List], {
	create: function(params, srcNodeRef){
		this.inherited(arguments);
		this.dirty = {};
		var self = this;
		// check visibility on scroll events
		listen(this.bodyNode, "scroll", function(event){
			self.onscroll(event);
		});
	},
	queryOptions: null,
	query: null,
	store: null,
	minRowsPerPage: 25,
	maxRowsPerPage: 100,
	maxEmptySpace: 10000,
	// rows can be removed if they are this distance in pixels from the visible viewing area.
	// set this to infinity if you never want rows removed
	farOffRemoval: 4000,
	rowHeight: 22,

	constructor: function(){
		// Create empty query objects on each instance, not the prototype
		this.query || (this.query = {});
		this.queryOptions || (this.queryOptions = {});
	},

	renderQuery: function(query, preloadNode){
		// summary:
		//		Creates a preload node for rendering a query into, and executes the query
		//		for the first page of data. Subsequent data will be downloaded as it comes
		//		into view.
		if(!preloadNode){
			var topPreloadNode = put(this.contentNode, "div.dgrid-preload");
			topPreloadNode.preload = true;
			topPreloadNode.query = query;
			topPreloadNode.start = 0;
			topPreloadNode.count = 0;
			topPreloadNode.next =
				preloadNode = put(this.contentNode, "div.dgrid-preload");
			preloadNode.previous = topPreloadNode;
		}
		// this preload node is used to represent the area of the grid that hasn't been
		// downloaded yet
		preloadNode.preload = true;
		preloadNode.query = query;
		preloadNode.start = this.minRowsPerPage;
		preloadNode.count = 0;
		var priorPreload = this.preloadNode;
		if(priorPreload){
			// the preload nodes (if there are multiple) are represented as a linked list, need to insert it
			if((preloadNode.next = priorPreload.next)){
				var previous = preloadNode.next.previous;
			}
			preloadNode.previous = previous;
			preloadNode.next = preloadNode;
		}else{
			this.preloadNode = preloadNode;
		}
		var options = {start: 0, count: this.minRowsPerPage, query: query};
		// execute the query
		var results = query(options);
		var self = this;
		// render the result set
		return Deferred.when(this.renderArray(results, preloadNode, options), function(trs){
			return Deferred.when(results.total || results.length, function(total){
				// now we need to adjust the height and total count based on the first result set
				var trCount = trs.length;
				total = total || trCount;
				var height = 0;
				for(var i = 0; i < trCount; i++){
					height += trs[i].offsetHeight;
				}
				// only update rowHeight if we actually got results
				if(trCount){ self.rowHeight = height / trCount; }

				total -= trCount;
				preloadNode.count = total;
				preloadNode.start = trCount;
				if(total){
					preloadNode.style.height = Math.min(total * self.rowHeight, self.maxEmptySpace) + "px";
				}else{
					// if total is 0, IE quirks mode can't handle 0px height for some reason, I don't know why, but we are setting display: none for now
					preloadNode.style.display = "none";
				}
				self.onscroll(); // recheck the scroll position in case the query didn't fill the screen
				// can remove the loading node now
				return trs;
			});
		}, console.error);
	},
	sortOrder: null,
	sort: function(property, descending){
		// summary:
		//		Sort the content
		this.lastCollection = null;
		this.inherited(arguments);
	},
	refresh: function(){
		this.inherited(arguments);
		if(this.store){
			// render the query
			var self = this;
			this.renderQuery(function(queryOptions){
				queryOptions.sort = self.sortOrder;
				return self.store.query(self.query, queryOptions);
			});
		}
	},
	lastScrollTop: 0,
	onscroll: function(){
		// summary:
		//		Checks to make sure that everything in the viewable area has been
		// 		downloaded, and triggering a request for the necessary data when needed.
		var scrollNode = this.bodyNode;
		var transform = this.contentNode.style.webkitTransform;
		var visibleTop = scrollNode.scrollTop + (transform ? -transform.match(/translate[\w]*\(.*?,(.*?)px/)[1] : 0);
		var visibleBottom = scrollNode.offsetHeight + visibleTop;
		var priorPreload, preloadNode = this.preloadNode;
		var lastScrollTop = this.lastScrollTop;
		this.lastScrollTop = visibleTop;

		// there can be multiple preloadNodes (if they split, or multiple queries are created),
		//	so we can traverse them until we find whatever is in the current viewport, making
		//	sure we don't backtrack
		while(preloadNode && preloadNode != priorPreload){
			priorPreload = this.preloadNode;
			this.preloadNode = preloadNode;
			var preloadTop = preloadNode.offsetTop;
			var preloadHeight;
			function removeDistantNodes(grid, distanceOff, traversal, below){
				// we check to see the the nodes are "far off"
				var farOffRemoval = grid.farOffRemoval;
				// we check if it is twice as much as farOffRemoval and then prune down to farOffRemoval, we could make that configurable as well
				if(distanceOff > 2 * farOffRemoval){
					// ok, there is preloadNode that is far off, let's remove rows until we get to farOffRemoval
					var row, nextRow = preloadNode[traversal];
					var reclaimedHeight = 0;
					var count = 0;
					var toDelete = [];
					console.time("test");
					while(row = nextRow){ // intentional assignment
						var rowHeight = row.offsetHeight;
						if(reclaimedHeight + rowHeight + farOffRemoval > distanceOff){
							// we have reclaimed enough rows, let's call it good
							break;
						}
						count++;
						reclaimedHeight += rowHeight;
						var nextRow = row[traversal]; // have to do this before removing it
						delete grid._rowIdToObject[row.id]; // clear out of the lookup
						toDelete.push(row);
					}
					for(var i = 0; i < toDelete.length; i++){
						put(toDelete[i], "!"); // remove it from the DOM
					}
					console.timeEnd("test");
					// now adjust the preloadNode based on the reclaimed space
					if(below){
						preloadNode.start -= count;
					}
					preloadNode.count += count;
					preloadNode.style.height = Math.min(preloadNode.count * this.rowHeight, this.maxEmptySpace) + "px";
				}

			}

			if(visibleBottom < preloadTop){
				// the preload is below the line of sight
				removeDistantNodes(this, preloadTop - visibleBottom, 'previousSibling', true);
				preloadNode = preloadNode.previous;
			}else if(visibleTop > (preloadTop + (preloadHeight = preloadNode.offsetHeight))){
				// the preload is above the line of sight
				removeDistantNodes(this, preloadTop + preloadHeight, 'nextSibling');
				preloadNode = preloadNode.next;
			}else{
				// the preload node is visible, or close to visible, better show it
				var offset = (visibleTop - preloadTop) / this.rowHeight;
				var count = (visibleBottom - visibleTop) / this.rowHeight;
				// utilize momentum for predictions
				var momentum = Math.max(Math.min((visibleTop - lastScrollTop) * this.rowHeight, this.maxRowsPerPage/2), this.maxRowsPerPage/-2);
				count += Math.abs(momentum);
				if(momentum < 0){
					offset += momentum;
				}
				offset = Math.max(offset, 0);
				if(offset < 10 && offset > 0 && count + offset < this.maxRowsPerPage){
					// connect to the top of the preloadNode if possible to avoid splitting
					count += offset;
					offset = 0;
				}
				// TODO: do this for the bottom too
				count = Math.min(Math.max(count, this.minRowsPerPage),
									this.maxRowsPerPage, preloadNode.count);
				if(count == 0){
					return;
				}
				offset = Math.round(offset);
				count = Math.round(count);
				var options = this.queryOptions ? lang.delegate(this.queryOptions) : {};
				options.start = preloadNode.start + offset;
				options.count = count;
				if(offset > 0){
					if(offset + count > preloadNode.count){
						count = preloadNode.count - offset;
					}
					// need to do a split as we have scrolled far enough that we don't want to
					// load everything up to this point, just what is in visible range
					var newPreloadNode = preloadNode.cloneNode(false);
					put(preloadNode, "+", newPreloadNode);
					preloadNode.next = newPreloadNode;
					newPreloadNode.previous = preloadNode;
					newPreloadNode.start = options.start + count;
					newPreloadNode.count = preloadNode.count - offset;
					newPreloadNode.query = preloadNode.query;
					// adjust the original one now
					preloadNode.count = offset;
					preloadNode.style.height = offset * this.rowHeight + "px";
					// make the new one be the current preloadNode
					preloadNode = newPreloadNode;
				}else{
					// no split, just need to adjust the start (and the count/height below)
					preloadNode.start += count;
				}
				preloadNode.count -= count;
				preloadNode.style.height = Math.min(preloadNode.count * this.rowHeight, this.maxEmptySpace) + "px";
				// create a loading node as a placeholder while the data is loaded
				var loadingNode = put(preloadNode, "-tr.dgrid-loading[style=height:" + count * this.rowHeight + "px]");
				// use the query associated with the preload node to get the next "page"
				options.query = preloadNode.query;
				// query now to fill in these rows
				var results = preloadNode.query(options);
				Deferred.when(this.renderArray(results, loadingNode, options),
					function(){
						// can remove the loading node now
						loadingNode.parentNode.removeChild(loadingNode);
					}, console.error);
			}
		}
	},
	getBeforePut: true,
	save: function(){
		var store = this.store;
		var puts = [];
		for(var id in this.dirty){
			var put = (function(dirty){
				return function(object){
					// copy all the dirty properties onto the original
					for(key in dirty){
						object[key] = dirty[key];
					}
					// put it
					store.put(object);
				};
			})(this.dirty[id]);
			puts.push(this.getBeforePut ?
				// retrieve the full object from the store
				Deferred.when(store.get(id), put):
				// just use the cached object
				put(this.row(id).data));
		}
		this.dirty = {}; // clear it
		return puts;
	}
});

});<commit_msg>Oops, take out the timing test<commit_after>define(["dojo/_base/declare", "dojo/_base/lang", "dojo/_base/Deferred", "dojo/on", "put-selector/put", "./List"], function(declare, lang, Deferred, listen, put, List){
return declare([List], {
	create: function(params, srcNodeRef){
		this.inherited(arguments);
		this.dirty = {};
		var self = this;
		// check visibility on scroll events
		listen(this.bodyNode, "scroll", function(event){
			self.onscroll(event);
		});
	},
	queryOptions: null,
	query: null,
	store: null,
	minRowsPerPage: 25,
	maxRowsPerPage: 100,
	maxEmptySpace: 10000,
	// rows can be removed if they are this distance in pixels from the visible viewing area.
	// set this to infinity if you never want rows removed
	farOffRemoval: 4000,
	rowHeight: 22,

	constructor: function(){
		// Create empty query objects on each instance, not the prototype
		this.query || (this.query = {});
		this.queryOptions || (this.queryOptions = {});
	},

	renderQuery: function(query, preloadNode){
		// summary:
		//		Creates a preload node for rendering a query into, and executes the query
		//		for the first page of data. Subsequent data will be downloaded as it comes
		//		into view.
		if(!preloadNode){
			var topPreloadNode = put(this.contentNode, "div.dgrid-preload");
			topPreloadNode.preload = true;
			topPreloadNode.query = query;
			topPreloadNode.start = 0;
			topPreloadNode.count = 0;
			topPreloadNode.next =
				preloadNode = put(this.contentNode, "div.dgrid-preload");
			preloadNode.previous = topPreloadNode;
		}
		// this preload node is used to represent the area of the grid that hasn't been
		// downloaded yet
		preloadNode.preload = true;
		preloadNode.query = query;
		preloadNode.start = this.minRowsPerPage;
		preloadNode.count = 0;
		var priorPreload = this.preloadNode;
		if(priorPreload){
			// the preload nodes (if there are multiple) are represented as a linked list, need to insert it
			if((preloadNode.next = priorPreload.next)){
				var previous = preloadNode.next.previous;
			}
			preloadNode.previous = previous;
			preloadNode.next = preloadNode;
		}else{
			this.preloadNode = preloadNode;
		}
		var options = {start: 0, count: this.minRowsPerPage, query: query};
		// execute the query
		var results = query(options);
		var self = this;
		// render the result set
		return Deferred.when(this.renderArray(results, preloadNode, options), function(trs){
			return Deferred.when(results.total || results.length, function(total){
				// now we need to adjust the height and total count based on the first result set
				var trCount = trs.length;
				total = total || trCount;
				var height = 0;
				for(var i = 0; i < trCount; i++){
					height += trs[i].offsetHeight;
				}
				// only update rowHeight if we actually got results
				if(trCount){ self.rowHeight = height / trCount; }

				total -= trCount;
				preloadNode.count = total;
				preloadNode.start = trCount;
				if(total){
					preloadNode.style.height = Math.min(total * self.rowHeight, self.maxEmptySpace) + "px";
				}else{
					// if total is 0, IE quirks mode can't handle 0px height for some reason, I don't know why, but we are setting display: none for now
					preloadNode.style.display = "none";
				}
				self.onscroll(); // recheck the scroll position in case the query didn't fill the screen
				// can remove the loading node now
				return trs;
			});
		}, console.error);
	},
	sortOrder: null,
	sort: function(property, descending){
		// summary:
		//		Sort the content
		this.lastCollection = null;
		this.inherited(arguments);
	},
	refresh: function(){
		this.inherited(arguments);
		if(this.store){
			// render the query
			var self = this;
			this.renderQuery(function(queryOptions){
				queryOptions.sort = self.sortOrder;
				return self.store.query(self.query, queryOptions);
			});
		}
	},
	lastScrollTop: 0,
	onscroll: function(){
		// summary:
		//		Checks to make sure that everything in the viewable area has been
		// 		downloaded, and triggering a request for the necessary data when needed.
		var scrollNode = this.bodyNode;
		var transform = this.contentNode.style.webkitTransform;
		var visibleTop = scrollNode.scrollTop + (transform ? -transform.match(/translate[\w]*\(.*?,(.*?)px/)[1] : 0);
		var visibleBottom = scrollNode.offsetHeight + visibleTop;
		var priorPreload, preloadNode = this.preloadNode;
		var lastScrollTop = this.lastScrollTop;
		this.lastScrollTop = visibleTop;

		// there can be multiple preloadNodes (if they split, or multiple queries are created),
		//	so we can traverse them until we find whatever is in the current viewport, making
		//	sure we don't backtrack
		while(preloadNode && preloadNode != priorPreload){
			priorPreload = this.preloadNode;
			this.preloadNode = preloadNode;
			var preloadTop = preloadNode.offsetTop;
			var preloadHeight;
			function removeDistantNodes(grid, distanceOff, traversal, below){
				// we check to see the the nodes are "far off"
				var farOffRemoval = grid.farOffRemoval;
				// we check if it is twice as much as farOffRemoval and then prune down to farOffRemoval, we could make that configurable as well
				if(distanceOff > 2 * farOffRemoval){
					// ok, there is preloadNode that is far off, let's remove rows until we get to farOffRemoval
					var row, nextRow = preloadNode[traversal];
					var reclaimedHeight = 0;
					var count = 0;
					var toDelete = [];
					while(row = nextRow){ // intentional assignment
						var rowHeight = row.offsetHeight;
						if(reclaimedHeight + rowHeight + farOffRemoval > distanceOff){
							// we have reclaimed enough rows, let's call it good
							break;
						}
						count++;
						reclaimedHeight += rowHeight;
						var nextRow = row[traversal]; // have to do this before removing it
						delete grid._rowIdToObject[row.id]; // clear out of the lookup
						toDelete.push(row);
					}
					for(var i = 0; i < toDelete.length; i++){
						put(toDelete[i], "!"); // remove it from the DOM
					}
					// now adjust the preloadNode based on the reclaimed space
					if(below){
						preloadNode.start -= count;
					}
					preloadNode.count += count;
					preloadNode.style.height = Math.min(preloadNode.count * this.rowHeight, this.maxEmptySpace) + "px";
				}

			}

			if(visibleBottom < preloadTop){
				// the preload is below the line of sight
				removeDistantNodes(this, preloadTop - visibleBottom, 'previousSibling', true);
				preloadNode = preloadNode.previous;
			}else if(visibleTop > (preloadTop + (preloadHeight = preloadNode.offsetHeight))){
				// the preload is above the line of sight
				removeDistantNodes(this, preloadTop + preloadHeight, 'nextSibling');
				preloadNode = preloadNode.next;
			}else{
				// the preload node is visible, or close to visible, better show it
				var offset = (visibleTop - preloadTop) / this.rowHeight;
				var count = (visibleBottom - visibleTop) / this.rowHeight;
				// utilize momentum for predictions
				var momentum = Math.max(Math.min((visibleTop - lastScrollTop) * this.rowHeight, this.maxRowsPerPage/2), this.maxRowsPerPage/-2);
				count += Math.abs(momentum);
				if(momentum < 0){
					offset += momentum;
				}
				offset = Math.max(offset, 0);
				if(offset < 10 && offset > 0 && count + offset < this.maxRowsPerPage){
					// connect to the top of the preloadNode if possible to avoid splitting
					count += offset;
					offset = 0;
				}
				// TODO: do this for the bottom too
				count = Math.min(Math.max(count, this.minRowsPerPage),
									this.maxRowsPerPage, preloadNode.count);
				if(count == 0){
					return;
				}
				offset = Math.round(offset);
				count = Math.round(count);
				var options = this.queryOptions ? lang.delegate(this.queryOptions) : {};
				options.start = preloadNode.start + offset;
				options.count = count;
				if(offset > 0){
					if(offset + count > preloadNode.count){
						count = preloadNode.count - offset;
					}
					// need to do a split as we have scrolled far enough that we don't want to
					// load everything up to this point, just what is in visible range
					var newPreloadNode = preloadNode.cloneNode(false);
					put(preloadNode, "+", newPreloadNode);
					preloadNode.next = newPreloadNode;
					newPreloadNode.previous = preloadNode;
					newPreloadNode.start = options.start + count;
					newPreloadNode.count = preloadNode.count - offset;
					newPreloadNode.query = preloadNode.query;
					// adjust the original one now
					preloadNode.count = offset;
					preloadNode.style.height = offset * this.rowHeight + "px";
					// make the new one be the current preloadNode
					preloadNode = newPreloadNode;
				}else{
					// no split, just need to adjust the start (and the count/height below)
					preloadNode.start += count;
				}
				preloadNode.count -= count;
				preloadNode.style.height = Math.min(preloadNode.count * this.rowHeight, this.maxEmptySpace) + "px";
				// create a loading node as a placeholder while the data is loaded
				var loadingNode = put(preloadNode, "-tr.dgrid-loading[style=height:" + count * this.rowHeight + "px]");
				// use the query associated with the preload node to get the next "page"
				options.query = preloadNode.query;
				// query now to fill in these rows
				var results = preloadNode.query(options);
				Deferred.when(this.renderArray(results, loadingNode, options),
					function(){
						// can remove the loading node now
						loadingNode.parentNode.removeChild(loadingNode);
					}, console.error);
			}
		}
	},
	getBeforePut: true,
	save: function(){
		var store = this.store;
		var puts = [];
		for(var id in this.dirty){
			var put = (function(dirty){
				return function(object){
					// copy all the dirty properties onto the original
					for(key in dirty){
						object[key] = dirty[key];
					}
					// put it
					store.put(object);
				};
			})(this.dirty[id]);
			puts.push(this.getBeforePut ?
				// retrieve the full object from the store
				Deferred.when(store.get(id), put):
				// just use the cached object
				put(this.row(id).data));
		}
		this.dirty = {}; // clear it
		return puts;
	}
});

});<|endoftext|>


<commit_before>/* eslint-env mocha */
// Test of shallow rendering, without any supporting libraries.
import expect from 'expect'
import React, { PropTypes } from 'react'
import TestUtils from 'react-addons-test-utils'
import ReactDOM from 'react-dom'
import { IntlProvider } from 'react-intl'
import WorkSerie, { __RewireAPI__ as DefaultExportWorkRelationsRewireApi } from '../../src/frontend/components/work/fields/WorkSerie'

function setup (propOverrides) {
  const props = { ...propOverrides }

  const messages = {
    labelWorkSerie: {
      id: 'WorkSerie.labelWorkSerie',
      description: 'Label for work serie',
      defaultMessage: 'A part of serie'
    }
  }

  const output = TestUtils.renderIntoDocument(
    <IntlProvider locale="en" messages={messages}>
      <WorkSerie {...props} />
    </IntlProvider>
  )

  return {
    props: props,
    output: output,
    node: ReactDOM.findDOMNode(output)
  }
}

describe('components', () => {
  describe('WorkSerie', () => {
    before(() => {
      DefaultExportWorkRelationsRewireApi.__Rewire__('Link', React.createClass({
        propTypes: {
          to: PropTypes.string.isRequired,
          children: PropTypes.node
        },
        render () {
          return (
            {this.props.children}
          )
        }
      }))
    })

    after(() => {
      DefaultExportWorkRelationsRewireApi.__ResetDependency__('Link')
    })

    it('should render one work serie', () => {
      const { node } = setup({
        workserie: {
          mainTitle: 'mainTitle',
          relativeUri: 'relativeUri'
        }
      })

      const link = node.querySelector("[data-automation-id='work_series_link']")
      expect(link.textContent).toBe('mainTitle')
      expect(link.getAttribute('href')).toBe('/search?query=workSeries%3A"mainTitle"')
    })
  })
})
<commit_msg>patron-client: fix test<commit_after>/* eslint-env mocha */
// Test of shallow rendering, without any supporting libraries.
import expect from 'expect'
import React, { PropTypes } from 'react'
import TestUtils from 'react-addons-test-utils'
import ReactDOM from 'react-dom'
import { IntlProvider } from 'react-intl'
import WorkSerie, { __RewireAPI__ as DefaultExportWorkRelationsRewireApi } from '../../src/frontend/components/work/fields/WorkSerie'

function setup (propOverrides) {
  const props = { ...propOverrides }

  const messages = {
    labelWorkSerie: {
      id: 'WorkSerie.labelWorkSerie',
      description: 'Label for work serie',
      defaultMessage: 'A part of serie'
    }
  }

  const output = TestUtils.renderIntoDocument(
    <IntlProvider locale="en" messages={messages}>
      <WorkSerie {...props} />
    </IntlProvider>
  )

  return {
    props: props,
    output: output,
    node: ReactDOM.findDOMNode(output)
  }
}

describe('components', () => {
  describe('WorkSerie', () => {
    before(() => {
      DefaultExportWorkRelationsRewireApi.__Rewire__('Link', React.createClass({
        propTypes: {
          to: PropTypes.string.isRequired,
          children: PropTypes.node
        },
        render () {
          return (
            {this.props.children}
          )
        }
      }))
    })

    after(() => {
      DefaultExportWorkRelationsRewireApi.__ResetDependency__('Link')
    })

    it('should render one work serie', () => {
      const { node } = setup({
        workserie: {
          mainTitle: 'mainTitle',
          relativeUri: 'relativeUri'
        }
      })

      const link = node.querySelector("[data-automation-id='work_series_link']")
      expect(link.textContent).toBe('mainTitle')
      expect(link.getAttribute('href')).toBe('/search?query=series%3A"mainTitle"')
    })
  })
})
<|endoftext|>


<commit_before>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with: Peter Leong
// This challenge took me [3] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode
/* 1. Iterate through votes to access the president property of each sub-object.
2. Repeat for vicePresident, secretary, and treasurer.
3. For each property found, place property in voteCount, if property exists, increase by 1
4. Sort voteCount by value to find highest value.
5. Place property with highest value into officers.
*/

// __________________________________________
// Initial Solution

// // PRESIDENT

for (var voter in votes) {
    if (voteCount.president.hasOwnProperty(votes[voter].president)) {
      voteCount.president[votes[voter].president] ++;
    } else {
      voteCount.president[votes[voter].president] = 1;
    }
}

// // VICE PRESIDENT

for (var voter in votes) {
    if (voteCount.vicePresident.hasOwnProperty(votes[voter].vicePresident)) {
      voteCount.vicePresident[votes[voter].vicePresident] ++;
    } else {
      voteCount.vicePresident[votes[voter].vicePresident] = 1;
    }
}

// //Secretary

for (var voter in votes) {
    if (voteCount.secretary.hasOwnProperty(votes[voter].secretary)) {
      voteCount.secretary[votes[voter].secretary] ++;
    } else {
      voteCount.secretary[votes[voter].secretary] = 1;
    }
}

//Treasurer

for (var voter in votes) {
    if (voteCount.treasurer.hasOwnProperty(votes[voter].treasurer)) {
      voteCount.treasurer[votes[voter].treasurer] ++;
    } else {
      voteCount.treasurer[votes[voter].treasurer] = 1;
    }
}

// President Selection

var presidentVotes = [];
for (var candidate in voteCount.president) {
      presidentVotes.push([candidate,voteCount.president[candidate]]);
      presidentVotes.sort(function(a, b) {return b[1] - a[1]});
      officers.president = presidentVotes[0][0];
}

// Vice President Selection

var vicePresidentVotes = [];
for (var candidate in voteCount.vicePresident) {
      vicePresidentVotes.push([candidate,voteCount.vicePresident[candidate]]);
      vicePresidentVotes.sort(function(a, b) {return b[1] - a[1]});
      officers.vicePresident = vicePresidentVotes[0][0];
}

// Secretary Selection
var secretaryVotes = [];
for (var candidate in voteCount.secretary) {
      secretaryVotes.push([candidate,voteCount.secretary[candidate]]);
      secretaryVotes.sort(function(a, b) {return b[1] - a[1]});
      officers.secretary = secretaryVotes[0][0];
}

//Treasurer Selection

var treasurerVotes = [];
for (var candidate in voteCount.treasurer) {
      treasurerVotes.push([candidate,voteCount.treasurer[candidate]]);
      treasurerVotes.sort(function(a, b) {return b[1] - a[1]});
      officers.treasurer = treasurerVotes[0][0];
}

// __________________________________________
// Refactored Solution
/* This part works

// for (var officers in voteCount) {
//   for (var voters in votes){
//     if (voteCount[officers].hasOwnProperty(votes[voters][officers])) {
//       voteCount[officers][votes[voters][officers]] ++;
//     } else {
//       voteCount[officers][votes[voters][officers]] = 1;
//     }
//   }
// }

*/

/* This part doesnt
// var presidentVotes = [];
// for (var candidate in voteCount.president) {
//       presidentVotes.push([candidate,voteCount.president[candidate]]);
//       presidentVotes.sort(function(a, b) {return b[1] - a[1]});
//       officers.president = presidentVotes[0][0];
// }

// var voteArray = [];

// for (var key in voteCount) {
//     if (voteCount.hasOwnProperty(key)) {
//       voteArray.push(voteCount[key]);
//     }
// }
// for (var key in voteArray)
// voteArray[key].sort(function(a, b) {return b[1] - a[1]});
// console.log(voteArray)

// var chartData = []

// for(var key in voteCount) {
//     var properties = voteCount[key];

//     if(typeof properties === "object") {
//        var array = [];

//        for(var propKey in properties) {
//            array.push([propKey, properties[propKey]])
//        }

//        voteArray.push(array);
//     }
// }

// voteArray[0].sort(function(a, b) { return b[1] - a[1]});
// console.log(voteArray[0][0][0])
// officers.president = voteArray[0][0][0]

// for (var x in voteCount){
//   var officerVotes = [];

//   for (var candidate in voteCount[x]) {
//       officerVotes.push([candidate, voteCount[x][candidate]]);
//   };
//   console.log(officerVotes)

//       var sortedOfficerVotes = officerVotes.sort(function(a, b) {return b[1] - a[1]});
//       officers[x] = sortedOfficerVotes[0];
// }

*/
// __________________________________________
// Reflection
/*

*/
// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<commit_msg>Add reflection content<commit_after>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with: Peter Leong
// This challenge took me [3] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode
/* 1. Iterate through votes to access the president property of each sub-object.
2. Repeat for vicePresident, secretary, and treasurer.
3. For each property found, place property in voteCount, if property exists, increase by 1
4. Sort voteCount by value to find highest value.
5. Place property with highest value into officers.
*/

// __________________________________________
// Initial Solution

// // PRESIDENT

for (var voter in votes) {
    if (voteCount.president.hasOwnProperty(votes[voter].president)) {
      voteCount.president[votes[voter].president] ++;
    } else {
      voteCount.president[votes[voter].president] = 1;
    }
}

// // VICE PRESIDENT

for (var voter in votes) {
    if (voteCount.vicePresident.hasOwnProperty(votes[voter].vicePresident)) {
      voteCount.vicePresident[votes[voter].vicePresident] ++;
    } else {
      voteCount.vicePresident[votes[voter].vicePresident] = 1;
    }
}

// //Secretary

for (var voter in votes) {
    if (voteCount.secretary.hasOwnProperty(votes[voter].secretary)) {
      voteCount.secretary[votes[voter].secretary] ++;
    } else {
      voteCount.secretary[votes[voter].secretary] = 1;
    }
}

//Treasurer

for (var voter in votes) {
    if (voteCount.treasurer.hasOwnProperty(votes[voter].treasurer)) {
      voteCount.treasurer[votes[voter].treasurer] ++;
    } else {
      voteCount.treasurer[votes[voter].treasurer] = 1;
    }
}

// President Selection

var presidentVotes = [];
for (var candidate in voteCount.president) {
      presidentVotes.push([candidate,voteCount.president[candidate]]);
      presidentVotes.sort(function(a, b) {return b[1] - a[1]});
      officers.president = presidentVotes[0][0];
}

// Vice President Selection

var vicePresidentVotes = [];
for (var candidate in voteCount.vicePresident) {
      vicePresidentVotes.push([candidate,voteCount.vicePresident[candidate]]);
      vicePresidentVotes.sort(function(a, b) {return b[1] - a[1]});
      officers.vicePresident = vicePresidentVotes[0][0];
}

// Secretary Selection
var secretaryVotes = [];
for (var candidate in voteCount.secretary) {
      secretaryVotes.push([candidate,voteCount.secretary[candidate]]);
      secretaryVotes.sort(function(a, b) {return b[1] - a[1]});
      officers.secretary = secretaryVotes[0][0];
}

//Treasurer Selection

var treasurerVotes = [];
for (var candidate in voteCount.treasurer) {
      treasurerVotes.push([candidate,voteCount.treasurer[candidate]]);
      treasurerVotes.sort(function(a, b) {return b[1] - a[1]});
      officers.treasurer = treasurerVotes[0][0];
}

// __________________________________________
// Refactored Solution
/* This part - sort votes into voteCount object - works

// for (var officers in voteCount) {
//   for (var voters in votes){
//     if (voteCount[officers].hasOwnProperty(votes[voters][officers])) {
//       voteCount[officers][votes[voters][officers]] ++;
//     } else {
//       voteCount[officers][votes[voters][officers]] = 1;
//     }
//   }
// }

*/

/* This part - select officers from voteCount - doesnt work
// var presidentVotes = [];
// for (var candidate in voteCount.president) {
//       presidentVotes.push([candidate,voteCount.president[candidate]]);
//       presidentVotes.sort(function(a, b) {return b[1] - a[1]});
//       officers.president = presidentVotes[0][0];
// }

// var voteArray = [];

// for (var key in voteCount) {
//     if (voteCount.hasOwnProperty(key)) {
//       voteArray.push(voteCount[key]);
//     }
// }
// for (var key in voteArray)
// voteArray[key].sort(function(a, b) {return b[1] - a[1]});
// console.log(voteArray)

// var chartData = []

// for(var key in voteCount) {
//     var properties = voteCount[key];

//     if(typeof properties === "object") {
//        var array = [];

//        for(var propKey in properties) {
//            array.push([propKey, properties[propKey]])
//        }

//        voteArray.push(array);
//     }
// }

// voteArray[0].sort(function(a, b) { return b[1] - a[1]});
// console.log(voteArray[0][0][0])
// officers.president = voteArray[0][0][0]

// for (var x in voteCount){
//   var officerVotes = [];

//   for (var candidate in voteCount[x]) {
//       officerVotes.push([candidate, voteCount[x][candidate]]);
//   };
//   console.log(officerVotes)

//       var sortedOfficerVotes = officerVotes.sort(function(a, b) {return b[1] - a[1]});
//       officers[x] = sortedOfficerVotes[0];
// }

*/
// __________________________________________
// Reflection
/*
What did you learn about iterating over nested objects in JavaScript?
Iterating through nested objects is much more complicated in JS than in Ruby, because you have to make sure the objects are of the right filetype before running the functions, or it will usually silently fail, unlike Ruby. Also, JS requires the use of for... if loops, rather than just working with each with Ruby. Map exists and seems to behave like it does in Ruby, but I haven't tried it in JS yet.

Were you able to find useful methods to help you with this?
We were able to successfully got the problem to work our first time through, and as we were solving it, we started having some ideas come into our head for how to refactor it. However, as you see above, once we got past one or two steps in the refactored solution, everything stopped working, and we couldn't get the half-refactored and half -unrefactored solutions to communicate with each other, so in the end the refactored solution didn't work at all. Even in the refactored version we didn't use any fancy new JS functions, just another for...if loop to iterate one layer deeper on the object and then sort again.

What concepts were solidified in the process of working through this challenge?
Needing to pay attention to what type of object you're working with in JS became abundantly clear in this challenge. Related to this, I've also finally started printint out tests for my variables and code immediately as I write them, so that I know what type of object I'm working with. While with Ruby, if you pass in the wrong type it'll tell you and point out the error, JS will attempt to coerce the incorrect object into the type that it wants, but that usually ends up behaving in a way that doens't make sense to you and has your code either return something that you don't want, or it'll just silently break and you'll have to dig back through to find any mistakes.

*/
// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<|endoftext|>