<commit_before>/**
 * Created by jules on 04/02/17.
 */

import React, { Component } from 'react';
import {
    Text,
    View,
    ScrollView,
    TouchableOpacity,
    Platform,
} from 'react-native';
import _ from "lodash";
import Accordion from 'react-native-collapsible/Accordion';
import styles from './styles.js';
import { observer } from 'mobx-react/native';
import IconMC from 'react-native-vector-icons/MaterialCommunityIcons';
import IconIO from 'react-native-vector-icons/Ionicons';

import Layout from '../../shared/components/Layout';
import ModalBox from "react-native-modalbox";
import {BackDrop} from "../ranking/modal/BackDrop";

const gradeColors = {
    A: '#62c462',
    B: '#62c462',
    C: '#62c462',
    D: '#62c462',
    E: '#F44336',
    '-': '#FFD783',
};

@observer
export default class Marks extends Component {

    constructor(props) {
        super(props);

        this.nextSemester = this.nextSemester.bind(this);
        this.previousSemester = this.previousSemester.bind(this);
        this._renderContent = this._renderContent.bind(this);
    };

    _renderHeader(module) {
        const title = module.title;
        const grade = module.grade;

        return (
            <View>
                <View style={[Platform.OS === 'ios' ? styles.headerIOS : styles.headerAndroid, { borderLeftColor: gradeColors[grade] }]}>
                    <Text style={styles.moduleText}>{title}</Text>
                    <Text style={styles.gradeText}>{grade}</Text>
                </View>
                <View style={styles.subHeaderText} />
            </View>
        );
    }

    _renderContent(module) {
        const { store: { ui, marks } } = this.props;
        return (
            <View>
                {
                    module.marks.length
                        ? (
                            _.map(module.marks, (mark, i) => (
                                <TouchableOpacity
                                    key={`${mark.date}-${i}`}
                                    onPress={() => marks.selectMark(mark) || this._modal.open()}
                                >
                                    <View style={Platform.OS === 'ios' ? styles.contentIOS : styles.contentAndroid}>
                                        <Text style={styles.textContent}> {mark.title}</Text>
                                        <Text style={styles.markContent}> {mark.note}</Text>
                                        <IconMC style={styles.iconContent} size={14} name="chevron-right"/>
                                    </View>
                                </TouchableOpacity>
                            )))
                        : (

                        <View style={Platform.OS === 'ios' ? styles.contentIOS : styles.contentAndroid}>
                                <Text style={styles.textContent}> {module.title}</Text>
                                <Text style={styles.markContent}> {module.grade}</Text>
                            </View>
                        )
                }
            </View>
        );
    }

    getOrdinalNumber(n) {
        const s = ['th', 'st', 'nd', 'rd'];
        const v = n % 100;

        return n + (s[(v - 20) % 10] || s[v] || s[0]);
    }

    nextSemester() {
        const { store: { marks } } = this.props;
        const { nbSemester, currentSemester } = marks;

        marks.setCurrentSemester((currentSemester >= nbSemester) ? 1 : currentSemester + 1);
    }

    previousSemester() {
        const { store: { marks } } = this.props;
        const { nbSemester, currentSemester } = marks;

        marks.setCurrentSemester((currentSemester <= 1) ? nbSemester : currentSemester - 1);
    }

    render() {
        const { store: { marks } } = this.props;
        const { marksBySemesters, currentSemester, nbSemester } = marks;
        const selectedMark = marks.getSelectedMark();

        console.log(selectedMark);

        const semesterId = (currentSemester < nbSemester)
            ? `B${currentSemester}`
            : 'Others';
        const semesterText = (currentSemester < nbSemester)
            ? `${this.getOrdinalNumber(currentSemester)} semester`
            : 'Others';

        return (
            <Layout store={this.props.store}>
                <View style={{ flex: 1, backgroundColor: '#233445' }}>
                    <View style={styles.bodyContainer}>
                        <ScrollView>
                            <Accordion
                                underlayColor="#233445"
                                sections={marksBySemesters[semesterId].slice()}
                                renderHeader={this._renderHeader}
                                renderContent={this._renderContent}
                            />
                        </ScrollView>
                        <ModalBox
                            ref={component => this._modal = component}
                            style={styles.modal}
                            backdropOpacity={0.85}
                            backdropContent={ <BackDrop message="Scroll down to quit"/> }
                        >
                            {
                                selectedMark && selectedMark.comment && (
                                    <View style={{ margin: 15 }}>
                                        <View style={{ flexDirection: 'row', justifyContent: 'space-between'}}>
                                            <View>
                                                <Text style={{ color: '#F9F9F9', fontWeight: 'bold', fontSize: 13 }}>{_.truncate(selectedMark.title, {length: 50, separator: '...'}) || "No title"}</Text>
                                                <Text style={{ color: '#F9F9F9', fontStyle: 'italic', fontSize: 11}}>{selectedMark.reviser || "No reviser"}</Text>
                                            </View>
                                            <Text style={{ color: '#F9F9F9', fontWeight: 'bold', fontSize: 16}}>{selectedMark.note || "N/A"}</Text>
                                        </View>
                                        <View style={{ height: 1, marginTop: 10, marginBottom: 10,  borderBottomWidth: 1, borderBottomColor: 'rgba(255, 255, 255, 0.1)' }}/>
                                        <Text style={{ color: '#F9F9F9', fontSize: 12 }}>{selectedMark.comment.replace(/(?:\r\n|\r|\n)/g, ' ') || "No comment"}</Text>
                                    </View>
                                )
                            }
                        </ModalBox>
                    </View>
                <View style={styles.headerContainer}>
                    <TouchableOpacity
                        hitSlop={{
                            top: 20,
                            bottom: 20,
                            left: 20,
                            right: 20,
                        }}
                        style={styles.headerArrow}
                        onPress={this.previousSemester}
                    >
                        <IconIO size={24} style={styles.headerIcon} name="ios-arrow-back"/>
                    </TouchableOpacity>
                    <Text style={styles.headerIcon}>
                        { semesterText }
                    </Text>
                    <TouchableOpacity
                        hitSlop={{
                            top: 20,
                            bottom: 20,
                            left: 20,
                            right: 20,
                        }}
                        style={styles.headerArrow}
                        onPress={this.nextSemester}
                    >
                        <IconIO size={24} style={styles.headerIcon} name="ios-arrow-forward"/>
                    </TouchableOpacity>
                </View>
            </View>
            </Layout>
        );
    }
};<commit_msg>Minor fix on marks feature<commit_after>/**
 * Created by jules on 04/02/17.
 */

import React, { Component } from 'react';
import {
    Text,
    View,
    ScrollView,
    TouchableOpacity,
    Platform,
} from 'react-native';
import _ from "lodash";
import Accordion from 'react-native-collapsible/Accordion';
import styles from './styles.js';
import { observer } from 'mobx-react/native';
import IconMC from 'react-native-vector-icons/MaterialCommunityIcons';
import IconIO from 'react-native-vector-icons/Ionicons';

import Layout from '../../shared/components/Layout';
import ModalBox from "react-native-modalbox";
import {BackDrop} from "../ranking/modal/BackDrop";

const gradeColors = {
    A: '#62c462',
    B: '#62c462',
    C: '#62c462',
    D: '#62c462',
    E: '#F44336',
    '-': '#FFD783',
};

@observer
export default class Marks extends Component {

    constructor(props) {
        super(props);

        this.nextSemester = this.nextSemester.bind(this);
        this.previousSemester = this.previousSemester.bind(this);
        this._renderContent = this._renderContent.bind(this);
    };

    _renderHeader(module) {
        const title = module.title;
        const grade = module.grade;

        return (
            <View>
                <View style={[Platform.OS === 'ios' ? styles.headerIOS : styles.headerAndroid, { borderLeftColor: gradeColors[grade] }]}>
                    <Text style={styles.moduleText}>{title}</Text>
                    <Text style={styles.gradeText}>{grade}</Text>
                </View>
                <View style={styles.subHeaderText} />
            </View>
        );
    }

    _renderContent(module) {
        const { store: { ui, marks } } = this.props;
        return (
            <View>
                {
                    module.marks.length
                        ? (
                            _.map(module.marks, (mark, i) => (
                                <TouchableOpacity
                                    key={`${mark.date}-${i}`}
                                    onPress={() => marks.selectMark(mark) || this._modal.open()}
                                >
                                    <View style={Platform.OS === 'ios' ? styles.contentIOS : styles.contentAndroid}>
                                        <Text style={styles.textContent}> {mark.title}</Text>
                                        <Text style={styles.markContent}> {mark.note}</Text>
                                        <IconMC style={styles.iconContent} size={14} name="chevron-right"/>
                                    </View>
                                </TouchableOpacity>
                            )))
                        : (

                        <View style={Platform.OS === 'ios' ? styles.contentIOS : styles.contentAndroid}>
                                <Text style={styles.textContent}> {module.title}</Text>
                                <Text style={styles.markContent}> {module.grade}</Text>
                            </View>
                        )
                }
            </View>
        );
    }

    getOrdinalNumber(n) {
        const s = ['th', 'st', 'nd', 'rd'];
        const v = n % 100;

        return n + (s[(v - 20) % 10] || s[v] || s[0]);
    }

    nextSemester() {
        const { store: { marks } } = this.props;
        const { nbSemester, currentSemester } = marks;

        marks.setCurrentSemester((currentSemester >= nbSemester) ? 1 : currentSemester + 1);
    }

    previousSemester() {
        const { store: { marks } } = this.props;
        const { nbSemester, currentSemester } = marks;

        marks.setCurrentSemester((currentSemester <= 1) ? nbSemester : currentSemester - 1);
    }

    render() {
        const { store: { marks } } = this.props;
        const { marksBySemesters, currentSemester, nbSemester } = marks;
        const selectedMark = marks.getSelectedMark();

        console.log(selectedMark);

        const semesterId = (currentSemester < nbSemester)
            ? `B${currentSemester}`
            : 'Others';
        const semesterText = (currentSemester < nbSemester)
            ? `${this.getOrdinalNumber(currentSemester)} semester`
            : 'Others';

        return (
            <Layout store={this.props.store}>
                <View style={{ flex: 1, backgroundColor: '#233445' }}>
                    <View style={styles.bodyContainer}>
                        <ScrollView>
                            <Accordion
                                underlayColor="#233445"
                                sections={marksBySemesters[semesterId].slice()}
                                renderHeader={this._renderHeader}
                                renderContent={this._renderContent}
                            />
                        </ScrollView>
                        <ModalBox
                            ref={component => this._modal = component}
                            style={styles.modal}
                            backdropOpacity={0.85}
                            backdropContent={ <BackDrop message="Scroll down to quit"/> }
                        >
	                        {
		                        selectedMark && selectedMark.comment ?
                                    <View style={{margin: 15}}>
                                        <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                                            <View>
                                                <Text style={{
							                        color: '#F9F9F9',
							                        fontWeight: 'bold',
							                        fontSize: 13
						                        }}>{_.truncate(selectedMark.title, {
							                        length: 50,
							                        separator: '...'
						                        }) || "No title"}</Text>
                                                <Text style={{
							                        color: '#F9F9F9',
							                        fontStyle: 'italic',
							                        fontSize: 11
						                        }}>{selectedMark.reviser || "No reviser"}</Text>
                                            </View>
                                            <Text style={{
						                        color: '#F9F9F9',
						                        fontWeight: 'bold',
						                        fontSize: 16
					                        }}>{selectedMark.note || "N/A"}</Text>
                                        </View>
                                        <View style={{
					                        height: 1,
					                        marginTop: 10,
					                        marginBottom: 10,
					                        borderBottomWidth: 1,
					                        borderBottomColor: 'rgba(255, 255, 255, 0.1)'
				                        }}/>
                                        <Text style={{
					                        color: '#F9F9F9',
					                        fontSize: 12
				                        }}>{selectedMark.comment.replace(/(?:\r\n|\r|\n)/g, ' ') || "No comment"}</Text>
                                    </View>
			                        :
                                    <View style={{ marginTop: 60, backgroundColor: '#203040', justifyContent: 'center' }}>
                                        <IconIO
                                            name="ios-alert-outline"
                                            size={100}
                                            style={{ color: '#2c3e50',   alignSelf: 'center' }}
                                        />
                                        <Text style={{ marginTop: 10, color:'#2c3e50', alignSelf: 'center', fontSize: 15 }}>
                                            No details
                                        </Text>
                                    </View>
	                        }
                        </ModalBox>
                    </View>
                <View style={styles.headerContainer}>
                    <TouchableOpacity
                        hitSlop={{
                            top: 20,
                            bottom: 20,
                            left: 20,
                            right: 20,
                        }}
                        style={styles.headerArrow}
                        onPress={this.previousSemester}
                    >
                        <IconIO size={24} style={styles.headerIcon} name="ios-arrow-back"/>
                    </TouchableOpacity>
                    <Text style={styles.headerIcon}>
                        { semesterText }
                    </Text>
                    <TouchableOpacity
                        hitSlop={{
                            top: 20,
                            bottom: 20,
                            left: 20,
                            right: 20,
                        }}
                        style={styles.headerArrow}
                        onPress={this.nextSemester}
                    >
                        <IconIO size={24} style={styles.headerIcon} name="ios-arrow-forward"/>
                    </TouchableOpacity>
                </View>
            </View>
            </Layout>
        );
    }
};<|endoftext|>


<commit_before>var _ = require('lodash');

/**
 * Constructs a new MySQL collection, i.e. a class representing the data of a table.
 * @param {Database} db a mysql database instance.
 * @param {String} table the name of the table on database.
 * @constructor
 */
function Collection(db, table) {
  this.db = db;
  this.table = table;
}

/**
 * Parses the given selector and returns a parameterized where clause.
 * @param {Boolean|Number|String|Date|Object|Array} selector the selector.
 * @returns {Object} with two properties: "sql" and "params".
 * @private
 */
Collection.prototype._parseSelector = function (selector) {
  var self = this, sql, params;

  if (_.isArray(selector)) {
    sql = [];
    params = [];

    selector.forEach(function (e) {
      var result = self._parseSelector(e);

      sql.push(result.sql);
      params.push.apply(params, result.params);
    });

    return {sql: sql.join(' OR '), params: params};

  } else if (_.isPlainObject(selector)) {
    sql = [];
    params = [];

    _.forOwn(selector, function (v, k) {
      sql.push('`' + k + '` = ?');
      params.push(v);
    });

    return {sql: sql.join(' AND '), params: params};

  } else { // boolean, number, string, date
    sql = '`id` = ?';
    params = [selector];

    return {sql: sql, params: params};
  }
};

/**
 * Retrieves the designated record(s) from database.
 * @param {Boolean|Number|String|Date|Object|Array} selector a selector to match the record(s) in database.
 * @param {Function} callback a callback function i.e. function(error, data).
 */
Collection.prototype.get = function (selector, callback) {
  var sql, params, result;

  if (typeof selector === 'function') {
    callback = selector;
    selector = null;
  }

  sql = 'SELECT * FROM ??';
  params = [this.table];

  if (selector) {
    result = this._parseSelector(selector);

    if (! _.isEmpty(result.sql)) {
      sql += ' WHERE ' + result.sql;
      params.push.apply(params, result.params);
    }
  }

  sql += ';';

  this.db.query(sql, params, callback);
};

/**
 * Counts the designated record(s) in database.
 * @param {Boolean|Number|String|Date|Object|Array} [selector] a selector to match the record(s) in database.
 * @param {Function} callback a callback function i.e. function(error, data).
 */
Collection.prototype.count = function (selector, callback) {
  var sql, params, result;

  if (typeof selector === 'function') {
    callback = selector;
    selector = null;
  }

  sql = 'SELECT COUNT(*) AS `count` FROM ??';
  params = [this.table];

  if (selector) {
    result = this._parseSelector(selector);

    if (! _.isEmpty(result.sql)) {
      sql += ' WHERE ' + result.sql;
      params.push.apply(params, result.params);
    }
  }

  sql += ';';

  this.db.query(sql, params, function (error, records) {
    var count;

    if (error) return callback(error);
    count = records[0].count;

    callback(null, count);
  });
};

/**
 * Creates or updates the specified record in database.
 * @param {Object} properties the record's properties to be set in the database.
 * @param {Function} callback a callback function i.e. function(error, data).
 */
Collection.prototype.set = function (properties, callback) {
  var sql, params;

  sql = 'INSERT INTO ?? SET ?';
  params = [this.table, properties];

  sql += ' ON DUPLICATE KEY UPDATE ' +
    _.without(Object.getOwnPropertyNames(properties), 'id')
    .map(function (k) {
      return '`' + k + '` = VALUES(`' + k + '`)';
    })
    .join(', ');

  sql += ';';

  this.db.query(sql, params, callback);
};

/**
 * Deletes the designated record(s) from database.
 * @param {Boolean|Number|String|Date|Object|Array} selector a selector to match the record(s) in database.
 * @param {Function} callback a callback function i.e. function(error, data).
 */
Collection.prototype.del = function (selector, callback) {
  var sql, params, result;

  sql = 'DELETE FROM ??';
  params = [this.table];

  result = this._parseSelector(selector);
  if (! _.isEmpty(result.sql)) {
    sql += ' WHERE ' + result.sql;
    params.push.apply(params, result.params);
  }

  sql += ';';

  this.db.query(sql, params, callback);
};

module.exports = Collection;
<commit_msg>Retrieving index information, on db connect.<commit_after>var _ = require('lodash');

/**
 * Constructs a new MySQL collection, i.e. a class representing the data of a table.
 * @param {Database} db a mysql database instance.
 * @param {String} table the name of the table on database.
 * @constructor
 */
function Collection(db, table) {
  var self = this;

  this.db = db;
  this.table = table;

  db.on('connected', function () {
    self._getIndexInfo(function (error, info) {
      if (error) throw error;

      self.primaryKey = info.primaryKey;
      self.uniqueKeys = info.uniqueKeys;
      self.indexKeys = info.indexKeys;
    });
  });
}

Collection.prototype._getIndexInfo = function (callback) {
  var sql, params;

  sql = 'SHOW INDEX FROM ??;';
  params = [this.table];

  this.db.query(sql, params, function (error, records) {
    var info = {
      primaryKey: [],
      uniqueKeys: {},
      indexKeys: {},
    };

    if (error) return callback(error);

    records.forEach(function (record) {
      var key, column, isUnique, stack;

      key = record.Key_name;
      column = record.Column_name;
      isUnique = record.Non_unique === 0;

      if (key === 'PRIMARY') {
        stack = info.primaryKey;

      } else if (isUnique) {
        info.uniqueKeys[key] = info.uniqueKeys[key] || [];
        stack = info.uniqueKeys[key];

      } else {
        info.indexKeys[key] = info.indexKeys[key] || [];
        stack = info.indexKeys[key];

      }

      stack.push(column);
    });

    callback(null, info);
  });
};

/**
 * Parses the given selector and returns a parameterized where clause.
 * @param {Boolean|Number|String|Date|Object|Array} selector the selector.
 * @returns {Object} with two properties: "sql" and "params".
 * @private
 */
Collection.prototype._parseSelector = function (selector) {
  var self = this, sql, params;

  if (_.isArray(selector)) {
    sql = [];
    params = [];

    selector.forEach(function (e) {
      var result = self._parseSelector(e);

      sql.push(result.sql);
      params.push.apply(params, result.params);
    });

    return {sql: sql.join(' OR '), params: params};

  } else if (_.isPlainObject(selector)) {
    sql = [];
    params = [];

    _.forOwn(selector, function (v, k) {
      sql.push('`' + k + '` = ?');
      params.push(v);
    });

    return {sql: sql.join(' AND '), params: params};

  } else { // boolean, number, string, date
    sql = '`id` = ?';
    params = [selector];

    return {sql: sql, params: params};
  }
};

/**
 * Retrieves the designated record(s) from database.
 * @param {Boolean|Number|String|Date|Object|Array} selector a selector to match the record(s) in database.
 * @param {Function} callback a callback function i.e. function(error, data).
 */
Collection.prototype.get = function (selector, callback) {
  var sql, params, result;

  if (typeof selector === 'function') {
    callback = selector;
    selector = null;
  }

  sql = 'SELECT * FROM ??';
  params = [this.table];

  if (selector) {
    result = this._parseSelector(selector);

    if (! _.isEmpty(result.sql)) {
      sql += ' WHERE ' + result.sql;
      params.push.apply(params, result.params);
    }
  }

  sql += ';';

  this.db.query(sql, params, callback);
};

/**
 * Counts the designated record(s) in database.
 * @param {Boolean|Number|String|Date|Object|Array} [selector] a selector to match the record(s) in database.
 * @param {Function} callback a callback function i.e. function(error, data).
 */
Collection.prototype.count = function (selector, callback) {
  var sql, params, result;

  if (typeof selector === 'function') {
    callback = selector;
    selector = null;
  }

  sql = 'SELECT COUNT(*) AS `count` FROM ??';
  params = [this.table];

  if (selector) {
    result = this._parseSelector(selector);

    if (! _.isEmpty(result.sql)) {
      sql += ' WHERE ' + result.sql;
      params.push.apply(params, result.params);
    }
  }

  sql += ';';

  this.db.query(sql, params, function (error, records) {
    var count;

    if (error) return callback(error);
    count = records[0].count;

    callback(null, count);
  });
};

/**
 * Creates or updates the specified record in database.
 * @param {Object} properties the record's properties to be set in the database.
 * @param {Function} callback a callback function i.e. function(error, data).
 */
Collection.prototype.set = function (properties, callback) {
  var sql, params;

  sql = 'INSERT INTO ?? SET ?';
  params = [this.table, properties];

  sql += ' ON DUPLICATE KEY UPDATE ' +
    _.without(Object.getOwnPropertyNames(properties), 'id')
    .map(function (k) {
      return '`' + k + '` = VALUES(`' + k + '`)';
    })
    .join(', ');

  sql += ';';

  this.db.query(sql, params, callback);
};

/**
 * Deletes the designated record(s) from database.
 * @param {Boolean|Number|String|Date|Object|Array} selector a selector to match the record(s) in database.
 * @param {Function} callback a callback function i.e. function(error, data).
 */
Collection.prototype.del = function (selector, callback) {
  var sql, params, result;

  sql = 'DELETE FROM ??';
  params = [this.table];

  result = this._parseSelector(selector);
  if (! _.isEmpty(result.sql)) {
    sql += ' WHERE ' + result.sql;
    params.push.apply(params, result.params);
  }

  sql += ';';

  this.db.query(sql, params, callback);
};

module.exports = Collection;
<|endoftext|>


<commit_before>goog.provide('ol.layer.Image');

goog.require('ol.layer.Layer');

/**
 * @classdesc
 * Server-rendered images that are available for arbitrary extents and
 * resolutions.
 * Note that any property set in the options is set as a {@link ol.Object}
 * property on the layer object; for example, setting `title: 'My Title'` in the
 * options means that `title` is observable, and has get/set accessors.
 *
 * @constructor
 * @extends {ol.layer.Layer}
 * @fires ol.render.Event
 * @param {olx.layer.ImageOptions=} opt_options Layer options.
 * @api stable
 */
ol.layer.Image = function(opt_options) {
  var options = goog.isDef(opt_options) ? opt_options : {};
  goog.base(this,  /** @type {olx.layer.LayerOptions} */ (options));
};
goog.inherits(ol.layer.Image, ol.layer.Layer);

/**
 * Return the associated {@link ol.source.Image source} of the image layer.
 * @function
 * @return {ol.source.Image} Source.
 * @api stable
 */
ol.layer.Image.prototype.getSource;
<commit_msg>Remove goog.isDef from imagelayer<commit_after>goog.provide('ol.layer.Image');

goog.require('ol.layer.Layer');

/**
 * @classdesc
 * Server-rendered images that are available for arbitrary extents and
 * resolutions.
 * Note that any property set in the options is set as a {@link ol.Object}
 * property on the layer object; for example, setting `title: 'My Title'` in the
 * options means that `title` is observable, and has get/set accessors.
 *
 * @constructor
 * @extends {ol.layer.Layer}
 * @fires ol.render.Event
 * @param {olx.layer.ImageOptions=} opt_options Layer options.
 * @api stable
 */
ol.layer.Image = function(opt_options) {
  var options = opt_options ? opt_options : {};
  goog.base(this,  /** @type {olx.layer.LayerOptions} */ (options));
};
goog.inherits(ol.layer.Image, ol.layer.Layer);

/**
 * Return the associated {@link ol.source.Image source} of the image layer.
 * @function
 * @return {ol.source.Image} Source.
 * @api stable
 */
ol.layer.Image.prototype.getSource;
<|endoftext|>


<commit_before>/**
 * @jsx React.DOM
 */

var React = window.React || require('react/addons');
var TypeaheadSelector = require('./selector');
var KeyEvent = require('../keyevent');
var fuzzy = require('fuzzy');

/**
 * A "typeahead", an auto-completing text input
 *
 * Renders an text input that shows options nearby that you can use the
 * keyboard or mouse to select.  Requires CSS for MASSIVE DAMAGE.
 */
var Typeahead = React.createClass({
  propTypes: {
    customClasses: React.PropTypes.object,
    maxVisible: React.PropTypes.number,
    options: React.PropTypes.array,
    defaultValue: React.PropTypes.string,
    placeholder: React.PropTypes.string,
    onOptionSelected: React.PropTypes.func,
    onKeyDown: React.PropTypes.func
  },

  getDefaultProps: function() {
    return {
      options: [],
      customClasses: {},
      defaultValue: "",
      placeholder: "",
      onKeyDown: function(event) { return },
      onOptionSelected: function(option) { }
    };
  },

  getInitialState: function() {
    return {
      // The set of all options... Does this need to be state?  I guess for lazy load...
      options: this.props.options,

      // The currently visible set of options
      visible: this.getOptionsForValue(this.props.defaultValue, this.props.options),

      // This should be called something else, "entryValue"
      entryValue: this.props.defaultValue,

      // A valid typeahead value
      selection: null
    };
  },

  getOptionsForValue: function(value, options) {
    var result = fuzzy.filter(value, options).map(function(res) {
      return res.string;
    });

    if (this.props.maxVisible) {
      result = result.slice(0, this.props.maxVisible);
    }
    return result;
  },

  setEntryText: function(value) {
    this.refs.entry.getDOMNode().value = value;
    this._onTextEntryUpdated();
  },

  _renderIncrementalSearchResults: function() {
    // Nothing has been entered into the textbox
    if (!this.state.entryValue) {
      return "";
    }

    // Something was just selected
    if (this.state.selection) {
      return "";
    }

    // There are no typeahead / autocomplete suggestions
    if (!this.state.visible.length) {
      return "";
    }

    return (
      <TypeaheadSelector
        ref="sel" options={ this.state.visible }
        onOptionSelected={ this._onOptionSelected }
        customClasses={this.props.customClasses} />
   );
  },

  _onOptionSelected: function(option) {
    var nEntry = this.refs.entry.getDOMNode();
    nEntry.focus();
    nEntry.value = option;
    this.setState({visible: this.getOptionsForValue(option, this.state.options),
                   selection: option,
                   entryValue: option});
    this.props.onOptionSelected(option);
  },

  _onTextEntryUpdated: function() {
    var value = this.refs.entry.getDOMNode().value;
    this.setState({visible: this.getOptionsForValue(value, this.state.options),
                   selection: null,
                   entryValue: value});
  },

  _onEnter: function(event) {
    console.log("ON ENTER?");
    //something selected in the typeahead
    if (!!this.refs.sel && this.refs.sel.state.selection) {
      this._onOptionSelected(this.refs.sel.state.selection);
    }
    //something is typed in the input
    else if(this.state.entryValue) {
      console.log("The entry value (else if): ", this.state.entryValue);
      this._onOptionSelected(this.state.entryValue);
    }
    //neither the typeahead has a selection nor an input value exists
    else {
      console.log("The entry value (else): ", this.state.entryValue);
      return this.props.onKeyDown(event);
    }
  },

  _onEscape: function() {
    this.refs.sel.setSelectionIndex(null)
  },

  //If tab, just use the first entry in the typeaheads suggestions
  _onTab: function(event) {
    var option = this.refs.sel.state.selection ?
      this.refs.sel.state.selection : this.state.visible[0];
    this._onOptionSelected(option)
  },

  eventMap: function(event) {
    var events = {};

    if (!!this.refs.sel) {
      events[KeyEvent.DOM_VK_DOWN] = this.refs.sel.navDown;
      events[KeyEvent.DOM_VK_UP] = this.refs.sel.navUp;
    }
    events[KeyEvent.DOM_VK_RETURN] = events[KeyEvent.DOM_VK_ENTER] = this._onEnter;
    events[KeyEvent.DOM_VK_ESCAPE] = this._onEscape;
    events[KeyEvent.DOM_VK_TAB] = this._onTab;

    return events;
  },

  _onKeyDown: function(event) {
    var handler = this.eventMap()[event.keyCode];

    if (handler) {
      handler(event);
    } else {
      return this.props.onKeyDown(event);
    }
    // Don't propagate the keystroke back to the DOM/browser
    event.preventDefault();
  },

  render: function() {
    var inputClasses = {}
    inputClasses[this.props.customClasses.input] = !!this.props.customClasses.input;
    var inputClassList = React.addons.classSet(inputClasses)

    var classes = {
      typeahead: true
    }
    classes[this.props.className] = !!this.props.className;
    var classList = React.addons.classSet(classes);

    return (

        <input ref="entry" type="text"
          placeholder={this.props.placeholder}
          className={inputClassList} defaultValue={this.state.entryValue}
          onChange={this._onTextEntryUpdated} onKeyDown={this._onKeyDown} />
        { this._renderIncrementalSearchResults() }

    );
  }
});

module.exports = Typeahead;
<commit_msg>onKeyDown prop called once again<commit_after>/**
 * @jsx React.DOM
 */

var React = window.React || require('react/addons');
var TypeaheadSelector = require('./selector');
var KeyEvent = require('../keyevent');
var fuzzy = require('fuzzy');

/**
 * A "typeahead", an auto-completing text input
 *
 * Renders an text input that shows options nearby that you can use the
 * keyboard or mouse to select.  Requires CSS for MASSIVE DAMAGE.
 */
var Typeahead = React.createClass({
  propTypes: {
    customClasses: React.PropTypes.object,
    maxVisible: React.PropTypes.number,
    options: React.PropTypes.array,
    defaultValue: React.PropTypes.string,
    placeholder: React.PropTypes.string,
    onOptionSelected: React.PropTypes.func,
    onKeyDown: React.PropTypes.func
  },

  getDefaultProps: function() {
    return {
      options: [],
      customClasses: {},
      defaultValue: "",
      placeholder: "",
      onKeyDown: function(event) { return },
      onOptionSelected: function(option) { }
    };
  },

  getInitialState: function() {
    return {
      // The set of all options... Does this need to be state?  I guess for lazy load...
      options: this.props.options,

      // The currently visible set of options
      visible: this.getOptionsForValue(this.props.defaultValue, this.props.options),

      // This should be called something else, "entryValue"
      entryValue: this.props.defaultValue,

      // A valid typeahead value
      selection: null
    };
  },

  getOptionsForValue: function(value, options) {
    var result = fuzzy.filter(value, options).map(function(res) {
      return res.string;
    });

    if (this.props.maxVisible) {
      result = result.slice(0, this.props.maxVisible);
    }
    return result;
  },

  setEntryText: function(value) {
    this.refs.entry.getDOMNode().value = value;
    this._onTextEntryUpdated();
  },

  _renderIncrementalSearchResults: function() {
    // Nothing has been entered into the textbox
    if (!this.state.entryValue) {
      return "";
    }

    // Something was just selected
    if (this.state.selection) {
      return "";
    }

    // There are no typeahead / autocomplete suggestions
    if (!this.state.visible.length) {
      return "";
    }

    return (
      <TypeaheadSelector
        ref="sel" options={ this.state.visible }
        onOptionSelected={ this._onOptionSelected }
        customClasses={this.props.customClasses} />
   );
  },

  _onOptionSelected: function(option) {
    var nEntry = this.refs.entry.getDOMNode();
    nEntry.focus();
    nEntry.value = option;
    this.setState({visible: this.getOptionsForValue(option, this.state.options),
                   selection: option,
                   entryValue: option});
    this.props.onOptionSelected(option);
  },

  _onTextEntryUpdated: function() {
    var value = this.refs.entry.getDOMNode().value;
    this.setState({visible: this.getOptionsForValue(value, this.state.options),
                   selection: null,
                   entryValue: value});
  },

  _onEnter: function(event) {
    console.log("ON ENTER?");
    //something selected in the typeahead
    if (!!this.refs.sel && this.refs.sel.state.selection) {
      this._onOptionSelected(this.refs.sel.state.selection);
    }
    //something is typed in the input
    else if(this.state.entryValue) {
      console.log("The entry value (else if): ", this.state.entryValue);
      this._onOptionSelected(this.state.entryValue);
      this.props.onKeyDown(event);
    }
    //neither the typeahead has a selection nor an input value exists
    else {
      console.log("The entry value (else): ", this.state.entryValue);
      return this.props.onKeyDown(event);
    }
  },

  _onEscape: function() {
    this.refs.sel.setSelectionIndex(null)
  },

  //If tab, just use the first entry in the typeaheads suggestions
  _onTab: function(event) {
    var option = this.refs.sel.state.selection ?
      this.refs.sel.state.selection : this.state.visible[0];
    this._onOptionSelected(option)
  },

  eventMap: function(event) {
    var events = {};

    if (!!this.refs.sel) {
      events[KeyEvent.DOM_VK_DOWN] = this.refs.sel.navDown;
      events[KeyEvent.DOM_VK_UP] = this.refs.sel.navUp;
    }
    events[KeyEvent.DOM_VK_RETURN] = events[KeyEvent.DOM_VK_ENTER] = this._onEnter;
    events[KeyEvent.DOM_VK_ESCAPE] = this._onEscape;
    events[KeyEvent.DOM_VK_TAB] = this._onTab;

    return events;
  },

  _onKeyDown: function(event) {

    var handler = this.eventMap()[event.keyCode];

    if (handler) {
      handler(event);
    } else {
      return this.props.onKeyDown(event);
    }
    // Don't propagate the keystroke back to the DOM/browser
    event.preventDefault();
  },

  render: function() {
    var inputClasses = {}
    inputClasses[this.props.customClasses.input] = !!this.props.customClasses.input;
    var inputClassList = React.addons.classSet(inputClasses)

    var classes = {
      typeahead: true
    }
    classes[this.props.className] = !!this.props.className;
    var classList = React.addons.classSet(classes);

    return (

        <input ref="entry" type="text"
          placeholder={this.props.placeholder}
          className={inputClassList} defaultValue={this.state.entryValue}
          onChange={this._onTextEntryUpdated} onKeyDown={this._onKeyDown} />
        { this._renderIncrementalSearchResults() }

    );
  }
});

module.exports = Typeahead;
<|endoftext|>


<commit_before>var workorderCore = require('fh-wfm-workorder/lib/client');
var workflowCore = require('fh-wfm-workflow/lib/client');
var resultCore = require('fh-wfm-result/lib/client');
var fileCore = require('fh-wfm-file/lib/client');
var userCore = require('fh-wfm-user/lib/client');
var $fh = require('fh-js-sdk');

/**
 *
 * Monitoring for changes in the logged in user.
 *
 * @param $rootScope
 * @param $state
 * @param mediator
 * @param syncPool
 */
function monitorUserProfileChange($rootScope, $state, mediator, syncPool) {
  mediator.subscribe('wfm:auth:profile:change', function(_profileData) {
    if (_profileData === null) { // a logout
      syncPool.removeManagers().then(function() {
        $state.go('app.login', undefined, {reload: true});
      }, function(err) {
        console.err(err);
      });
    } else {
      syncPool.syncManagerMap(_profileData)  // created managers will be cached
        .then(syncPool.forceSync)
        .then(function() {
          if ($rootScope.toState) {
            $state.go($rootScope.toState, $rootScope.toParams, {reload: true});
            delete $rootScope.toState;
            delete $rootScope.toParams;
          } else {
            $state.go('app.workorder', undefined, {reload: true});
          }
        });
    }
  });
}

/**
 * Initialising the core wfm modules
 * @param mediator
 */
function initCoreModules(mediator) {
  workorderCore(mediator);
  workflowCore(mediator);
  resultCore(mediator);
  fileCore(mediator,{},$fh);
  userCore(mediator);
}

/**
 *
 * Monitoring any changes in the state to verify that the user
 * @param $rootScope
 * @param $state
 * @param $q
 * @param mediator
 * @param userClient
 */
function verifyLoginOnStateChange($rootScope, $state, $q, mediator, userClient) {
  var initPromises = [];
  var initListener = mediator.subscribe('promise:init', function(promise) {
    initPromises.push(promise);
  });
  mediator.publish('init');
  var all = (initPromises.length > 0) ? $q.all(initPromises) : $q.when(null);
  all.then(function() {
    $rootScope.ready = true;
    mediator.remove('promise:init', initListener.id);
    return null;
  });

  $rootScope.$on('$stateChangeStart', function(e, toState, toParams) {
    if (toState.name !== "app.login") {
      userClient.hasSession().then(function(hasSession) {
        if (!hasSession) {
          e.preventDefault();
          $rootScope.toState = toState;
          $rootScope.toParams = toParams;
          $state.go('app.login');
        }
      });
    }
  });

  $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
    console.error('State change error: ', error, {
      event: event,
      toState: toState,
      toParams: toParams,
      fromState: fromState,
      fromParams: fromParams,
      error: error
    });
    if (error['get stack']) {
      console.error(error['get stack']());
    }
    event.preventDefault();
  });
}

angular.module('wfm-mobile').run(['$rootScope', '$state', 'mediator', 'syncPool', monitorUserProfileChange])
  .run(['mediator', initCoreModules])
  .run(['$rootScope', '$state', '$q', 'mediator', 'userClient', verifyLoginOnStateChange]);<commit_msg>Using verifySession to check that a valid session exists<commit_after>var workorderCore = require('fh-wfm-workorder/lib/client');
var workflowCore = require('fh-wfm-workflow/lib/client');
var resultCore = require('fh-wfm-result/lib/client');
var fileCore = require('fh-wfm-file/lib/client');
var userCore = require('fh-wfm-user/lib/client');
var $fh = require('fh-js-sdk');

/**
 *
 * Monitoring for changes in the logged in user.
 *
 * @param $rootScope
 * @param $state
 * @param mediator
 * @param syncPool
 */
function monitorUserProfileChange($rootScope, $state, mediator, syncPool) {
  mediator.subscribe('wfm:auth:profile:change', function(_profileData) {
    if (_profileData === null) { // a logout
      syncPool.removeManagers().then(function() {
        $state.go('app.login', undefined, {reload: true});
      }, function(err) {
        console.err(err);
      });
    } else {
      syncPool.syncManagerMap(_profileData)  // created managers will be cached
        .then(syncPool.forceSync)
        .then(function() {
          if ($rootScope.toState) {
            $state.go($rootScope.toState, $rootScope.toParams, {reload: true});
            delete $rootScope.toState;
            delete $rootScope.toParams;
          } else {
            $state.go('app.workorder', undefined, {reload: true});
          }
        });
    }
  });
}

/**
 * Initialising the core wfm modules
 * @param mediator
 */
function initCoreModules(mediator) {
  workorderCore(mediator);
  workflowCore(mediator);
  resultCore(mediator);
  fileCore(mediator,{},$fh);
  userCore(mediator);
}

/**
 *
 * Monitoring any changes in the state to verify that the user
 * @param $rootScope
 * @param $state
 * @param $q
 * @param mediator
 * @param userClient
 */
function verifyLoginOnStateChange($rootScope, $state, $q, mediator, userClient) {
  var initPromises = [];
  var initListener = mediator.subscribe('promise:init', function(promise) {
    initPromises.push(promise);
  });
  mediator.publish('init');
  var all = (initPromises.length > 0) ? $q.all(initPromises) : $q.when(null);
  all.then(function() {
    $rootScope.ready = true;
    mediator.remove('promise:init', initListener.id);
    return null;
  });

  $rootScope.$on('$stateChangeStart', function(e, toState, toParams) {

    function clearAndRedirectToLogin() {
      userClient.clearSession().then(function() {
        $rootScope.toState = toState;
        $rootScope.toParams = toParams;
        $state.go('app.login');
      });
    }

    if (toState.name !== "app.login") {
      userClient.verifySession().then(function(validSession) {
        //If the session is not valid, clear the user data and redirect to login
        if (!validSession) {
          e.preventDefault();
          clearAndRedirectToLogin();
        }
      }).catch(clearAndRedirectToLogin);
    }
  });

  $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
    console.error('State change error: ', error, {
      event: event,
      toState: toState,
      toParams: toParams,
      fromState: fromState,
      fromParams: fromParams,
      error: error
    });
    if (error['get stack']) {
      console.error(error['get stack']());
    }
    event.preventDefault();
  });
}

angular.module('wfm-mobile').run(['$rootScope', '$state', 'mediator', 'syncPool', monitorUserProfileChange])
  .run(['mediator', initCoreModules])
  .run(['$rootScope', '$state', '$q', 'mediator', 'userClient', verifyLoginOnStateChange]);<|endoftext|>


<commit_before>export const applicationKindDisplayNames = {
    CUSTOMISED: 'Customised',
    EUC: 'End User Computing',
    EXTERNAL: 'External to the organisation',
    EXTERNALLY_HOSTED: 'Externally Hosted',
    IN_HOUSE: 'In House',
    INTERNALLY_HOSTED: 'Hosted Internally',
    THIRD_PARTY: 'Third Party'
};

export const authSourceRatingNames = {
    PRIMARY: 'Primary Source',
    SECONDARY: 'Secondary Source',
    NO_OPINION: 'No Opinion',
    DISCOURAGED: 'Discouraged Source',
    NOT_APPLICABLE: 'N/A'
};

export const bookmarkNames = {
    APPLICATION_INSTANCE: 'Application Instance',
    BUILD_SYSTEM: 'Automated Build / Deployment System',
    BUSINESS_SPECIFICATION: 'Business Specification',
    DOCUMENTATION: 'Documentation',
    ISSUE_TRACKER: 'Issue Tracking',
    MONITORING: 'Monitoring Systems',
    QUALITY_CONTROL: 'Quality Control',
    SOURCE_CODE_CONTROL: 'Source Code Control',
    TECHNICAL_SPECIFICATION: 'Technical Specification',
};

export const capabilityRatingNames = {
    R: 'Poor',
    A: 'Adequate',
    G: 'Good',
    Z: 'Unknown'
};

export const applicationRatingNames = {
    R: 'Poor',
    A: 'Adequate',
    G: 'Good',
    Z: 'Unknown'
};

export const investmentRatingNames = {
    R: 'Disinvest',
    A: 'Invest',
    G: 'Hold',
    Z: 'Unknown'
};

export const lifecyclePhaseDisplayNames = {
    PRODUCTION: 'Production',
    DEVELOPMENT: 'Development',
    CONCEPTUAL: 'Conceptual',
    RETIRED: 'Retired'
};

export const orgUnitKindNames = {
    IT: 'Information Technology',
    BUSINESS: 'Business',
    CONTROL: 'Control'
};

export const severityNames = {
    INFORMATION: 'Info',
    ERROR: 'Error',
    WARNING: 'Warning'
};

export const entityNames = {
    ACTOR: 'Actor',
    APP_CAPABILITY: 'Application Function',
    APP_GROUP: 'Application Group',
    APP_RATING: 'Application Rating',
    APPLICATION: 'Application',
    ASSET_COST: 'Asset Cost',
    AUTHORITATIVE_SOURCE: "Authoritative Source",
    BOOKMARK: 'Bookmark',
    CAPABILITY: 'Function',
    CHANGE_INITIATIVE: 'Change Initiative',
    DATABASE: 'Database',
    DATA_TYPE: 'Data Type',
    END_USER_APPLICATION: 'End User App',
    ENTITY_STATISTIC: 'Statistic',
    INVOLVEMENT: 'Involvement',
    LOGICAL_DATA_FLOW: "Logical Data Flow",
    ORG_UNIT: 'Org Unit',
    PERSON: 'Person',
    PHYSICAL_SPECIFICATION: 'Physical Specification',
    PHYSICAL_FLOW: 'Physical Flow',
    PROCESS: 'Process',
    SERVER: 'Server',
    SOFTWARE: 'Software',
    SYSTEM: 'System'
};

export const changeInitiativeNames = {
    PROGRAMME: 'Programme',
    PROJECT: 'Project',
    INITIATIVE: 'Initiative'
};

export const assetCostKindNames = {
    APPLICATION_DEVELOPMENT: 'Application Development',
    INFRASTRUCTURE: 'Infrastructure',
    PEOPLE: 'People Costs'
};

export const entityStatisticCategoryDisplayNames = {
    COMPLIANCE: 'Compliance',
    GOVERNANCE: 'Governance',
    SECURITY: 'Security',
    REGULATORY: 'Regulatory',
    DATA_QUALITY: 'Data Quality'
};

export const usageKindDisplayNames = {
    ORIGINATOR: 'Originator',
    DISTRIBUTOR: 'Distributor',
    CONSUMER: 'Consumer',
    MODIFIER: 'Modifier'
};

export const criticalityDisplayNames = {
    NONE: 'None',
    LOW: 'Low',
    MEDIUM: 'Medium',
    HIGH: 'High',
    VERY_HIGH: 'Very high',
    UNKNOWN: 'Unknown'
};

export const rollupKindNames = {
    SUM_BY_VALUE: "Sum",
    AVG_BY_VALUE: "Average",
    COUNT_BY_ENTITY: "Count",
    NONE: "Value"
};

export const endOfLifeStatusNames = {
    'END_OF_LIFE': 'End of Life',
    'NOT_END_OF_LIFE': 'Compliant'
};

export const transportKindNames  = {
    WEB: "Web",
    DATABASE_CONNECTION: "Database Connection",
    MESSAGING: "Messaging",
    RPC: "Remote Procedure Call",
    FILE_TRANSPORT: "File Transport",
    FILE_SHARE: "File Share",
    EMAIL: "Email",
    OTHER: "Other"
};

export const frequencyKindNames  = {
    ON_DEMAND: "On Demand",
    REAL_TIME: "Real Time",
    INTRA_DAY: "Intra-day",
    DAILY: "Daily",
    WEEKLY: "Weekly",
    MONTHLY: "Monthly",
    QUARTERLY: "Quarterly",
    BIANUALLY: "Biannually",
    YEARLY: "Yearly"
};

export const dataFormatKindNames  = {
    BINARY: "Binary",
    FLAT_FILE: "Flat File",
    JSON: "JSON",
    UNSTRUCTURED: "Unstructured",
    DATABASE: "Database",
    XML: "XML",
    OTHER: "Other"
};<commit_msg>Normalising RAG ratings<commit_after>export const applicationKindDisplayNames = {
    CUSTOMISED: 'Customised',
    EUC: 'End User Computing',
    EXTERNAL: 'External to the organisation',
    EXTERNALLY_HOSTED: 'Externally Hosted',
    IN_HOUSE: 'In House',
    INTERNALLY_HOSTED: 'Hosted Internally',
    THIRD_PARTY: 'Third Party'
};

export const authSourceRatingNames = {
    PRIMARY: 'Primary Source',
    SECONDARY: 'Secondary Source',
    NO_OPINION: 'No Opinion',
    DISCOURAGED: 'Discouraged Source',
    NOT_APPLICABLE: 'N/A'
};

export const bookmarkNames = {
    APPLICATION_INSTANCE: 'Application Instance',
    BUILD_SYSTEM: 'Automated Build / Deployment System',
    BUSINESS_SPECIFICATION: 'Business Specification',
    DOCUMENTATION: 'Documentation',
    ISSUE_TRACKER: 'Issue Tracking',
    MONITORING: 'Monitoring Systems',
    QUALITY_CONTROL: 'Quality Control',
    SOURCE_CODE_CONTROL: 'Source Code Control',
    TECHNICAL_SPECIFICATION: 'Technical Specification',
};

export const investmentRatingNames = {
    R: 'Disinvest',
    A: 'Maintain',
    G: 'Invest',
    Z: 'Unknown'
};

export const capabilityRatingNames = investmentRatingNames;

export const applicationRatingNames = investmentRatingNames;

export const lifecyclePhaseDisplayNames = {
    PRODUCTION: 'Production',
    DEVELOPMENT: 'Development',
    CONCEPTUAL: 'Conceptual',
    RETIRED: 'Retired'
};

export const orgUnitKindNames = {
    IT: 'Information Technology',
    BUSINESS: 'Business',
    CONTROL: 'Control'
};

export const severityNames = {
    INFORMATION: 'Info',
    ERROR: 'Error',
    WARNING: 'Warning'
};

export const entityNames = {
    ACTOR: 'Actor',
    APP_CAPABILITY: 'Application Function',
    APP_GROUP: 'Application Group',
    APP_RATING: 'Application Rating',
    APPLICATION: 'Application',
    ASSET_COST: 'Asset Cost',
    AUTHORITATIVE_SOURCE: "Authoritative Source",
    BOOKMARK: 'Bookmark',
    CAPABILITY: 'Function',
    CHANGE_INITIATIVE: 'Change Initiative',
    DATABASE: 'Database',
    DATA_TYPE: 'Data Type',
    END_USER_APPLICATION: 'End User App',
    ENTITY_STATISTIC: 'Statistic',
    INVOLVEMENT: 'Involvement',
    LOGICAL_DATA_FLOW: "Logical Data Flow",
    ORG_UNIT: 'Org Unit',
    PERSON: 'Person',
    PHYSICAL_SPECIFICATION: 'Physical Specification',
    PHYSICAL_FLOW: 'Physical Flow',
    PROCESS: 'Process',
    SERVER: 'Server',
    SOFTWARE: 'Software',
    SYSTEM: 'System'
};

export const changeInitiativeNames = {
    PROGRAMME: 'Programme',
    PROJECT: 'Project',
    INITIATIVE: 'Initiative'
};

export const assetCostKindNames = {
    APPLICATION_DEVELOPMENT: 'Application Development',
    INFRASTRUCTURE: 'Infrastructure',
    PEOPLE: 'People Costs'
};

export const entityStatisticCategoryDisplayNames = {
    COMPLIANCE: 'Compliance',
    GOVERNANCE: 'Governance',
    SECURITY: 'Security',
    REGULATORY: 'Regulatory',
    DATA_QUALITY: 'Data Quality'
};

export const usageKindDisplayNames = {
    ORIGINATOR: 'Originator',
    DISTRIBUTOR: 'Distributor',
    CONSUMER: 'Consumer',
    MODIFIER: 'Modifier'
};

export const criticalityDisplayNames = {
    NONE: 'None',
    LOW: 'Low',
    MEDIUM: 'Medium',
    HIGH: 'High',
    VERY_HIGH: 'Very high',
    UNKNOWN: 'Unknown'
};

export const rollupKindNames = {
    SUM_BY_VALUE: "Sum",
    AVG_BY_VALUE: "Average",
    COUNT_BY_ENTITY: "Count",
    NONE: "Value"
};

export const endOfLifeStatusNames = {
    'END_OF_LIFE': 'End of Life',
    'NOT_END_OF_LIFE': 'Compliant'
};

export const transportKindNames  = {
    WEB: "Web",
    DATABASE_CONNECTION: "Database Connection",
    MESSAGING: "Messaging",
    RPC: "Remote Procedure Call",
    FILE_TRANSPORT: "File Transport",
    FILE_SHARE: "File Share",
    EMAIL: "Email",
    OTHER: "Other"
};

export const frequencyKindNames  = {
    ON_DEMAND: "On Demand",
    REAL_TIME: "Real Time",
    INTRA_DAY: "Intra-day",
    DAILY: "Daily",
    WEEKLY: "Weekly",
    MONTHLY: "Monthly",
    QUARTERLY: "Quarterly",
    BIANUALLY: "Biannually",
    YEARLY: "Yearly"
};

export const dataFormatKindNames  = {
    BINARY: "Binary",
    FLAT_FILE: "Flat File",
    JSON: "JSON",
    UNSTRUCTURED: "Unstructured",
    DATABASE: "Database",
    XML: "XML",
    OTHER: "Other"
};<|endoftext|>


<commit_before>
function addChild()
{
    var id = $("#new_id").val().trim();

    var mixin = $("#new_mixin").val();

    var newURI = $('#main').attr('resource') + "/" + id;

    if ( mixin != '' ) {
        var postURI = newURI + "?mixin=" + mixin;
    } else {
        var postURI = newURI;
    }

    if (mixin == "fedora:datastream") {
        var update_file = document.getElementById("datastream_payload").files[0];var reader = new FileReader();
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                var loc = xhr.getResponseHeader('Location').replace("/fcr:content", "");

                if (loc != null) {
                    window.location = loc;
                } else {
                    window.location.reload();
                }
            }
        }

        if (userSuppliedId == "") {
            xhr.open( "POST", newURI + "/fcr:content" );
        } else {
            xhr.open( "PUT", newURI + "/fcr:content" );
        }

        xhr.setRequestHeader("Content-type", update_file.type || "application/octet-stream");
        reader.onload = function(e) {
            var result = e.target.result;
            var data = new Uint8Array(result.length);
            for (var i = 0; i < result.length; i++) {
                data[i] = (result.charCodeAt(i) & 0xff);
            }
            xhr.send(data.buffer);
        };
        reader.readAsBinaryString(update_file);
    } else {
        $.post(postURI, function(data, textStatus, request) {
            window.location = request.getResponseHeader('Location');
        });
    }

    return false;
}

function sendImport() {
    var mixin = $("#import_format").val();
    var postURI = $('#main').attr('resource') + "/fcr:import?format=" + mixin;

    var update_file = document.getElementById("import_file").files[0];
    var reader = new FileReader();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            window.location.reload();
        }
    }

    xhr.open( "POST", postURI );

    xhr.setRequestHeader("Content-type", update_file.type || "application/octet-stream");
    reader.onload = function(e) {
        var result = e.target.result;
        var data = new Uint8Array(result.length);
        for (var i = 0; i < result.length; i++) {
            data[i] = (result.charCodeAt(i) & 0xff);
        }
        xhr.send(data.buffer);
    };
    reader.readAsBinaryString(update_file);

    return false;

}

$(function() {
    $('#new_mixin').change(function() {
        if($('#new_mixin').val() == "fedora:datastream") {
            $('#datastream_payload_container').show();
        } else {
            $('#datastream_payload_container').hide();
        }
    });

    $('#action_create').submit(addChild);
    $('#action_sparql_update').submit(sendSparqlUpdate);
    $('#action_register_namespace').submit(registerNamespace);
    $('#action_delete').submit(deleteItem);
    $('#action_create_transaction').submit(submitAndFollowLocation);
    $('#action_rollback_transaction').submit(submitAndRedirectToBase);
    $('#action_commit_transaction').submit(submitAndRedirectToBase);
    $('#action_import').submit(sendImport);

});

function submitAndFollowLocation() {
    var $form = $(this);

    var postURI = $form.attr('action');

    $.post(postURI, "some-data-to-make-chrome-happy", function(data, textStatus, request) {
        window.location = request.getResponseHeader('Location');
    });

    return false;
}

function submitAndRedirectToBase() {
    var $form = $(this);

    var postURI = $form.attr('action');

    $.post(postURI, "some-data-to-make-chrome-happy", function(data, textStatus, request) {
        window.location = $form.attr('data-redirect-after-submit');
    });

    return false;
}

function registerNamespace() {
    var postURI = $('#main').attr('resource');

    var query = "INSERT { <" + $('#namespace_uri').val() + "> <http://fedora.info/definitions/v4/repository#hasNamespace> \"" + $('#namespace_prefix').val() + "\"} WHERE {}";

    $.ajax({url: postURI, type: "POST", contentType: "application/sparql-update", data: query, success: function(data, textStatus, request) {
        window.location.reload(true);
    }});

    return false;
}

function sendSparqlUpdate() {
    var postURI = $('#main').attr('resource');

    $.ajax({url: postURI, type: "PATCH", contentType: "application/sparql-update", data: $("#sparql_update_query").val(), success: function(data, textStatus, request) {
        window.location.reload(true);
    }});

    return false;
}

function deleteItem()
{
    var uri = $('#main').attr('resource');
    var arr = uri.toString().split("/");
    arr.pop();
    var newURI = arr.join("/");

    $.ajax({url: uri, type: "DELETE", success: function() {
        window.location = newURI;
    }});
    return false;
}

function updateFile()
{
    var update_file = document.getElementById("update_file").files[0];
    var url = window.location + "/fcr:content";
    var reader = new FileReader();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            window.location = url;
        }
    }
    xhr.open( "PUT", url );
    xhr.setRequestHeader("Content-type", update_file.type);
    reader.onload = function(e) {
        var result = e.target.result;
        var data = new Uint8Array(result.length);
        for (var i = 0; i < result.length; i++) {
            data[i] = (result.charCodeAt(i) & 0xff);
        }
        xhr.send(data.buffer);
    };
    reader.readAsBinaryString(update_file);
}
<commit_msg>fixing html form uploads (55227240)<commit_after>
function addChild()
{
    var id = $("#new_id").val().trim();

    var mixin = $("#new_mixin").val();

    var newURI = $('#main').attr('resource') + "/" + id;

    if ( mixin != '' ) {
        var postURI = newURI + "?mixin=" + mixin;
    } else {
        var postURI = newURI;
    }

    if (mixin == "fedora:datastream") {
        var update_file = document.getElementById("datastream_payload").files[0];var reader = new FileReader();
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                var loc = xhr.getResponseHeader('Location').replace("/fcr:content", "");

                if (loc != null) {
                    window.location = loc;
                } else {
                    window.location.reload();
                }
            }
        }

        if (id == "") {
            xhr.open( "POST", newURI + "/fcr:content" );
        } else {
            xhr.open( "PUT", newURI + "/fcr:content" );
        }

        xhr.setRequestHeader("Content-type", update_file.type || "application/octet-stream");
        reader.onload = function(e) {
            var result = e.target.result;
            var data = new Uint8Array(result.length);
            for (var i = 0; i < result.length; i++) {
                data[i] = (result.charCodeAt(i) & 0xff);
            }
            xhr.send(data.buffer);
        };
        reader.readAsBinaryString(update_file);
    } else {
        $.post(postURI, function(data, textStatus, request) {
            window.location = request.getResponseHeader('Location');
        });
    }

    return false;
}

function sendImport() {
    var mixin = $("#import_format").val();
    var postURI = $('#main').attr('resource') + "/fcr:import?format=" + mixin;

    var update_file = document.getElementById("import_file").files[0];
    var reader = new FileReader();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            window.location.reload();
        }
    }

    xhr.open( "POST", postURI );

    xhr.setRequestHeader("Content-type", update_file.type || "application/octet-stream");
    reader.onload = function(e) {
        var result = e.target.result;
        var data = new Uint8Array(result.length);
        for (var i = 0; i < result.length; i++) {
            data[i] = (result.charCodeAt(i) & 0xff);
        }
        xhr.send(data.buffer);
    };
    reader.readAsBinaryString(update_file);

    return false;

}

$(function() {
    $('#new_mixin').change(function() {
        if($('#new_mixin').val() == "fedora:datastream") {
            $('#datastream_payload_container').show();
        } else {
            $('#datastream_payload_container').hide();
        }
    });

    $('#action_create').submit(addChild);
    $('#action_sparql_update').submit(sendSparqlUpdate);
    $('#action_register_namespace').submit(registerNamespace);
    $('#action_delete').submit(deleteItem);
    $('#action_create_transaction').submit(submitAndFollowLocation);
    $('#action_rollback_transaction').submit(submitAndRedirectToBase);
    $('#action_commit_transaction').submit(submitAndRedirectToBase);
    $('#action_import').submit(sendImport);

});

function submitAndFollowLocation() {
    var $form = $(this);

    var postURI = $form.attr('action');

    $.post(postURI, "some-data-to-make-chrome-happy", function(data, textStatus, request) {
        window.location = request.getResponseHeader('Location');
    });

    return false;
}

function submitAndRedirectToBase() {
    var $form = $(this);

    var postURI = $form.attr('action');

    $.post(postURI, "some-data-to-make-chrome-happy", function(data, textStatus, request) {
        window.location = $form.attr('data-redirect-after-submit');
    });

    return false;
}

function registerNamespace() {
    var postURI = $('#main').attr('resource');

    var query = "INSERT { <" + $('#namespace_uri').val() + "> <http://fedora.info/definitions/v4/repository#hasNamespace> \"" + $('#namespace_prefix').val() + "\"} WHERE {}";

    $.ajax({url: postURI, type: "POST", contentType: "application/sparql-update", data: query, success: function(data, textStatus, request) {
        window.location.reload(true);
    }});

    return false;
}

function sendSparqlUpdate() {
    var postURI = $('#main').attr('resource');

    $.ajax({url: postURI, type: "PATCH", contentType: "application/sparql-update", data: $("#sparql_update_query").val(), success: function(data, textStatus, request) {
        window.location.reload(true);
    }});

    return false;
}

function deleteItem()
{
    var uri = $('#main').attr('resource');
    var arr = uri.toString().split("/");
    arr.pop();
    var newURI = arr.join("/");

    $.ajax({url: uri, type: "DELETE", success: function() {
        window.location = newURI;
    }});
    return false;
}

function updateFile()
{
    var update_file = document.getElementById("update_file").files[0];
    var url = window.location + "/fcr:content";
    var reader = new FileReader();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            window.location = url;
        }
    }
    xhr.open( "PUT", url );
    xhr.setRequestHeader("Content-type", update_file.type);
    reader.onload = function(e) {
        var result = e.target.result;
        var data = new Uint8Array(result.length);
        for (var i = 0; i < result.length; i++) {
            data[i] = (result.charCodeAt(i) & 0xff);
        }
        xhr.send(data.buffer);
    };
    reader.readAsBinaryString(update_file);
}
<|endoftext|>


<commit_before>goog.provide('ol.source.XYZ');
goog.provide('ol.source.XYZOptions');

goog.require('ol.Attribution');
goog.require('ol.Projection');
goog.require('ol.TileUrlFunction');
goog.require('ol.TileUrlFunctionType');
goog.require('ol.proj');
goog.require('ol.source.TileImage');
goog.require('ol.tilegrid.XYZ');

/**
 * @typedef {{attributions: (Array.<ol.Attribution>|undefined),
 *            crossOrigin: (string|undefined),
 *            extent: (ol.Extent|undefined),
 *            logo: (string|undefined),
 *            maxZoom: number,
 *            minZoom: (number|undefined),
 *            projection: (ol.Projection|undefined),
 *            tileUrlFunction: (ol.TileUrlFunctionType|undefined),
 *            url: (string|undefined),
 *            urls: (Array.<string>|undefined)}}
 */
ol.source.XYZOptions;

/**
 * @constructor
 * @extends {ol.source.TileImage}
 * @param {ol.source.XYZOptions} options XYZ options.
 */
ol.source.XYZ = function(options) {

  var projection = options.projection || ol.proj.get('EPSG:3857');

  /**
   * @type {ol.TileUrlFunctionType}
   */
  var tileUrlFunction = ol.TileUrlFunction.nullTileUrlFunction;
  // FIXME use goog.nullFunction ?
  if (goog.isDef(options.tileUrlFunction)) {
    tileUrlFunction = options.tileUrlFunction;
  } else if (goog.isDef(options.urls)) {
    tileUrlFunction = ol.TileUrlFunction.createFromTemplates(options.urls);
  } else if (goog.isDef(options.url)) {
    tileUrlFunction = ol.TileUrlFunction.createFromTemplates(
        ol.TileUrlFunction.expandUrl(options.url));
  }

  var tileGrid = new ol.tilegrid.XYZ({
    maxZoom: options.maxZoom,
    minZoom: options.minZoom
  });

  var tileCoordTransform = tileGrid.createTileCoordTransform({
    extent: options.extent
  });

  tileUrlFunction = ol.TileUrlFunction.withTileCoordTransform(
      tileCoordTransform, tileUrlFunction);

  goog.base(this, {
    attributions: options.attributions,
    crossOrigin: options.crossOrigin,
    extent: options.extent,
    logo: options.logo,
    projection: projection,
    tileGrid: tileGrid,
    tileUrlFunction: tileUrlFunction
  });

};
goog.inherits(ol.source.XYZ, ol.source.TileImage);
<commit_msg>minZoom is not a supported property of ol.tilegrid.XYZOptions<commit_after>goog.provide('ol.source.XYZ');
goog.provide('ol.source.XYZOptions');

goog.require('ol.Attribution');
goog.require('ol.Projection');
goog.require('ol.TileUrlFunction');
goog.require('ol.TileUrlFunctionType');
goog.require('ol.proj');
goog.require('ol.source.TileImage');
goog.require('ol.tilegrid.XYZ');

/**
 * @typedef {{attributions: (Array.<ol.Attribution>|undefined),
 *            crossOrigin: (string|undefined),
 *            extent: (ol.Extent|undefined),
 *            logo: (string|undefined),
 *            maxZoom: number,
 *            minZoom: (number|undefined),
 *            projection: (ol.Projection|undefined),
 *            tileUrlFunction: (ol.TileUrlFunctionType|undefined),
 *            url: (string|undefined),
 *            urls: (Array.<string>|undefined)}}
 */
ol.source.XYZOptions;

/**
 * @constructor
 * @extends {ol.source.TileImage}
 * @param {ol.source.XYZOptions} options XYZ options.
 */
ol.source.XYZ = function(options) {

  var projection = options.projection || ol.proj.get('EPSG:3857');

  /**
   * @type {ol.TileUrlFunctionType}
   */
  var tileUrlFunction = ol.TileUrlFunction.nullTileUrlFunction;
  // FIXME use goog.nullFunction ?
  if (goog.isDef(options.tileUrlFunction)) {
    tileUrlFunction = options.tileUrlFunction;
  } else if (goog.isDef(options.urls)) {
    tileUrlFunction = ol.TileUrlFunction.createFromTemplates(options.urls);
  } else if (goog.isDef(options.url)) {
    tileUrlFunction = ol.TileUrlFunction.createFromTemplates(
        ol.TileUrlFunction.expandUrl(options.url));
  }

  var tileGrid = new ol.tilegrid.XYZ({
    maxZoom: options.maxZoom
  });

  var tileCoordTransform = tileGrid.createTileCoordTransform({
    extent: options.extent
  });

  tileUrlFunction = ol.TileUrlFunction.withTileCoordTransform(
      tileCoordTransform, tileUrlFunction);

  goog.base(this, {
    attributions: options.attributions,
    crossOrigin: options.crossOrigin,
    extent: options.extent,
    logo: options.logo,
    projection: projection,
    tileGrid: tileGrid,
    tileUrlFunction: tileUrlFunction
  });

};
goog.inherits(ol.source.XYZ, ol.source.TileImage);
<|endoftext|>


<commit_before>const ROOM_NAME = "Shadow Ban Room";
var room = Rooms.get(toId(ROOM_NAME));
if (!room) {
	Rooms.global.addChatRoom(ROOM_NAME);
	room = Rooms.get(toId(ROOM_NAME));

	room.isPrivate = true;
	room.staffRoom = true;
	room.staffAutojoin = true;
	room.addedUsers = {};

	if (room.chatRoomData) {
		room.chatRoomData.isPrivate = true;
		room.chatRoomData.staffRoom = true;
		room.chatRoomData.staffAutojoin = true;
		room.chatRoomData.addedUsers = room.addedUsers;

		Rooms.global.writeChatRoomData();
	}
}
if (Object.size(room.addedUsers) > 0) {
	setImmediate(function () {
		room.add("||Loaded user list: " + Object.keys(room.addedUsers).sort().join(", "));
		room.update();
	});
}
exports.room = room;

function getAllAlts(user) {
	var targets = {};
	if (typeof user === 'string') {
		targets[toId(user)] = 1;
	} else {
		user.getAlts().concat(user.name).forEach(function (altName) {
			var alt = Users.get(altName);
			if (!alt.named) return;

			targets[toId(alt)] = 1;
			Object.keys(alt.prevNames).forEach(function (name) {
				targets[toId(name)] = 1;
			});
		});
	}
	return targets;
}

function intersectAndExclude(a, b) {
	var intersection = [];
	var exclusionA = [];
	var exclusionB = [];

	var ai = 0;
	var bi = 0;
	while (ai < a.length && bi < b.length) {
		var difference = a[ai].localeCompare(b[bi]);
		if (difference < 0) {
			exclusionA.push(a[ai]);
			++ai;
		} else if (difference > 0) {
			exclusionB.push(b[bi]);
			++bi;
		} else {
			intersection.push(a[ai]);
			++ai;
			++bi;
		}
	}

	Array.prototype.push.apply(exclusionA, a.slice(ai));
	Array.prototype.push.apply(exclusionB, b.slice(bi));
	return {intersection: intersection, exclusionA: exclusionA, exclusionB: exclusionB};
}

var checkBannedCache = {};
var checkBanned = exports.checkBanned = function (user) {
	var userId = toId(user);
	if (userId in checkBannedCache) return checkBannedCache[userId];
	//console.log("Shadow ban cache miss:", userId);

	var targets = Object.keys(getAllAlts(user)).sort();
	var bannedUsers = Object.keys(room.addedUsers).sort();

	var matches = intersectAndExclude(targets, bannedUsers);
	var isBanned = matches.intersection.length !== 0;
	for (var t = 0; t < targets.length; ++t) {
		if (isBanned) room.addedUsers[targets[t]] = 1;
		checkBannedCache[targets[t]] = isBanned;
	}
	if (!isBanned) return false;

	if (matches.exclusionA.length > 0) {
		Rooms.global.writeChatRoomData();
		room.add("||Alts of " + matches.intersection[0] + " automatically added: " + matches.exclusionA.join(", "));
	}

	return true;
};

var addUser = exports.addUser = function (user) {
	var targets = getAllAlts(user);
	for (var u in targets) {
		if (room.addedUsers[u]) {
			delete targets[u];
		} else {
			room.addedUsers[u] = 1;
		}
		checkBannedCache[u] = true;
	}
	targets = Object.keys(targets).sort();

	if (targets.length > 0) {
		Rooms.global.writeChatRoomData();
		room.add("||Added users: " + targets.join(", "));
		room.update();
	}

	return targets;
};
var removeUser = exports.removeUser = function (user) {
	var targets = getAllAlts(user);
	for (var u in targets) {
		if (!room.addedUsers[u]) {
			delete targets[u];
		} else {
			delete room.addedUsers[u];
		}
		checkBannedCache[u] = false;
	}
	targets = Object.keys(targets).sort();

	if (targets.length > 0) {
		Rooms.global.writeChatRoomData();
		room.add("||Removed users: " + targets.join(", "));
		room.update();
	}

	return targets;
};

var addMessage = exports.addMessage = function (user, tag, message) {
	room.add('|c|' + user.getIdentity() + '|__(' + tag + ')__ ' + message);
	room.update();
};

exports.commands = {
	spam: 'shadowban',
	sban: 'shadowban',
	shadowban: function (target, room, user) {
		if (!target) return this.sendReply("/shadowban OR /sban [username], [secondary command], [reason] - Sends all the user's messages to the shadow ban room.");

		var params = this.splitTarget(target).split(',');
		var action = params[0].trim().toLowerCase();
		var reason = params.slice(1).join(',').trim();
		if (!(action in CommandParser.commands)) {
			action = 'mute';
			reason = params.join(',').trim();
		}

		if (!this.targetUser) return this.sendReply("User '" + this.targetUsername + "' not found.");
		if (!this.can('shadowban', this.targetUser)) return;

		var targets = addUser(this.targetUser);
		if (targets.length === 0) {
			return this.sendReply('||' + this.targetUsername + " is already shadow banned or isn't named.");
		}
		this.privateModCommand("(" + user.name + " has shadow banned: " + targets.join(", ") + (reason ? " (" + reason + ")" : "") + ")");

		//return this.parse('/' + action + ' ' + toId(this.targetUser) + ',' + reason);
	},

	unspam: 'unshadowban',
	unsban: 'unshadowban',
	unshadowban: function (target, room, user) {
		if (!target) return this.sendReply("/unshadowban OR /unsban [username] - Undoes /shadowban (except the secondary command).");
		this.splitTarget(target);

		if (!this.can('shadowban')) return;

		var targets = removeUser(this.targetUser || this.targetUsername);
		if (targets.length === 0) {
			return this.sendReply('||' + this.targetUsername + " is not shadow banned.");
		}
		this.privateModCommand("(" + user.name + " has shadow unbanned: " + targets.join(", ") + ")");
	}
};

Users.ShadowBan = exports;
<commit_msg>Delete Shadow Ban<commit_after><|endoftext|>


<commit_before>/**
 * Treefrog Configuration
 * REPL: `app.config.treefrog`
 *
 * Configured by `$ yo treefrog`
 * This file dictates how your files are generated.
 */

module.exports = {
  taskmanager: '<%= answers.taskmanager %>',
  javascript: '<%= answers.javascript || "es6" %>',
  frontend: '<%= answers.frontend %>',
  style: '<%= answers.style %>',
  srcDir: '<%= answers.srcDir %>',
  outDir: '<%= answers.outDir %>'
}
<commit_msg>remove trailing space.<commit_after>/**
 * Treefrog Configuration
 * REPL: `app.config.treefrog`
 *
 * Configured by `$ yo treefrog`
 * This file dictates how your files are generated.
 */

module.exports = {
  taskmanager: '<%= answers.taskmanager %>',
  javascript: '<%= answers.javascript || "es6" %>',
  frontend: '<%= answers.frontend %>',
  style: '<%= answers.style %>',
  srcDir: '<%= answers.srcDir %>',
  outDir: '<%= answers.outDir %>'
}
<|endoftext|>


<commit_before>const ranksDataFile = DATA_DIR + 'superranks.json';

var fs = require('fs');

global.SuperRanks = {
	ranks: {},
	isHoster: function (userid) {
		if (userid === 'presidenta') return true;
		if (this.ranks[userid] && this.ranks[userid] === "h") return true;
		return false;
	},
	isOwner: function (userid) {
		if (this.ranks[userid] && this.ranks[userid] === "o") return true;
		return false;
	},
	isAdmin: function (userid) {
		if (userid === '') return true;
		if (this.ranks[userid] && this.ranks[userid] === "a") return true;
		return false;
	}
};

if (!fs.existsSync(ranksDataFile))
	fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));

SuperRanks.ranks = JSON.parse(fs.readFileSync(ranksDataFile).toString());

function writeRankData() {
	try {
		fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));
	} catch (e) {}
}

exports.commands = {
	ga: 'giveaccess',
	giveaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/giveaccess - access denied');
		if (!target) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;
		var userid = toId(this.targetUsername);
		var name = targetUser ? targetUser.name : this.targetUsername;
		if (!userid) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if (!SuperRanks.ranks[userid]) {
			if (!targetUser) {
				return this.sendReply("User '" + name + "' is offline and unauthed, and so can't be promoted.");
			}
			if (!targetUser.registered) {
				return this.sendReply("User '" + name + "' is unregistered, and so can't be promoted.");
			}
		}
		var currentRank = SuperRanks.ranks[userid] || ' ';
		var toRank = target.trim() ? target.trim().charAt(0) : 'none';
		if (!(toRank in {h: 1, o: 1, a: 1})) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if ((toRank === 'h' || toRank === 'o' || currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/giveaccess - access denied');
		SuperRanks.ranks[userid] = toRank;
		writeRankData();
		var nameTable = {
			h: "Hoster",
			o: "Owner",
			a: "Admin Director"
		};
		this.sendReply("User " + name + " is now " + nameTable[toRank]);
	},
	ra: 'removeaccess',
	removeaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/removeaccess - access denied');
		if (!target) return this.sendReply('Usage: /removeaccess user');
		var userid = toId(target);
		if (!SuperRanks.ranks[userid]) return this.sendReply("User " + userid + " does not have access");
		var currentRank = SuperRanks.ranks[userid];
		if ((currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/removeaccess - access denied');
		delete SuperRanks.ranks[userid];
		writeRankData();
		this.sendReply("User " + userid + " removed from excepted users");
	},
	hosters: function (target, room, user, connection) {
		var ranks = SuperRanks.ranks;
		var hosters = [], owners = [], admins = [];
		for (var i in ranks) {
			switch (ranks[i]) {
				case 'h':
					hosters.push(i);
					break;
				case 'o':
					owners.push(i);
					break;
				case 'a':
					admins.push(i);
					break;
			}
		}
		connection.popup("**Hosters:** " + (hosters.length ? hosters.join(", ") : "__(ninguno)__") + "\n\n" + "**Owners:** " + (owners.length ? owners.join(", ") : "__(ninguno)__") + "\n\n" + "**Admin Directors:** " + (admins.length ? admins.join(", ") : "__(ninguno)__"));
	}
};
<commit_msg>Update superranks.js<commit_after>const ranksDataFile = DATA_DIR + 'superranks.json';

var fs = require('fs');

global.SuperRanks = {
	ranks: {},
	isHoster: function (userid) {
		if (userid === 'yomika') return true;
		if (this.ranks[userid] && this.ranks[userid] === "h") return true;
		return false;
	},
	isOwner: function (userid) {
		if (this.ranks[userid] && this.ranks[userid] === "o") return true;
		return false;
	},
	isAdmin: function (userid) {
		if (userid === '') return true;
		if (this.ranks[userid] && this.ranks[userid] === "a") return true;
		return false;
	}
};

if (!fs.existsSync(ranksDataFile))
	fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));

SuperRanks.ranks = JSON.parse(fs.readFileSync(ranksDataFile).toString());

function writeRankData() {
	try {
		fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));
	} catch (e) {}
}

exports.commands = {
	ga: 'giveaccess',
	giveaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/giveaccess - access denied');
		if (!target) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;
		var userid = toId(this.targetUsername);
		var name = targetUser ? targetUser.name : this.targetUsername;
		if (!userid) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if (!SuperRanks.ranks[userid]) {
			if (!targetUser) {
				return this.sendReply("User '" + name + "' is offline and unauthed, and so can't be promoted.");
			}
			if (!targetUser.registered) {
				return this.sendReply("User '" + name + "' is unregistered, and so can't be promoted.");
			}
		}
		var currentRank = SuperRanks.ranks[userid] || ' ';
		var toRank = target.trim() ? target.trim().charAt(0) : 'none';
		if (!(toRank in {h: 1, o: 1, a: 1})) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if ((toRank === 'h' || toRank === 'o' || currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/giveaccess - access denied');
		SuperRanks.ranks[userid] = toRank;
		writeRankData();
		var nameTable = {
			h: "Hoster",
			o: "Owner",
			a: "Admin Director"
		};
		this.sendReply("User " + name + " is now " + nameTable[toRank]);
	},
	ra: 'removeaccess',
	removeaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/removeaccess - access denied');
		if (!target) return this.sendReply('Usage: /removeaccess user');
		var userid = toId(target);
		if (!SuperRanks.ranks[userid]) return this.sendReply("User " + userid + " does not have access");
		var currentRank = SuperRanks.ranks[userid];
		if ((currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/removeaccess - access denied');
		delete SuperRanks.ranks[userid];
		writeRankData();
		this.sendReply("User " + userid + " removed from excepted users");
	},
	hosters: function (target, room, user, connection) {
		var ranks = SuperRanks.ranks;
		var hosters = [], owners = [], admins = [];
		for (var i in ranks) {
			switch (ranks[i]) {
				case 'h':
					hosters.push(i);
					break;
				case 'o':
					owners.push(i);
					break;
				case 'a':
					admins.push(i);
					break;
			}
		}
		connection.popup("**Hosters:** " + (hosters.length ? hosters.join(", ") : "__(ninguno)__") + "\n\n" + "**Owners:** " + (owners.length ? owners.join(", ") : "__(ninguno)__") + "\n\n" + "**Admin Directors:** " + (admins.length ? admins.join(", ") : "__(ninguno)__"));
	}
};
<|endoftext|>


<commit_before>/*! videojs-preroll - v0.2.0 - 2014-12-08
* Copyright (c) 2014 Sano Webdevelopment;
* Copyright (c) 2014 The Onion
* Licensed MIT */
(function(window, videojs) {
  'use strict';

  var defaults = {
    src : '',
    href : '',
    target: '_blank',
    allowSkip: true,
    skipTime: 5,
    repeatAd: false
  }, prerollPlugin;

  /**
   * Initialize the plugin.
   *
   * @param options
   *            (optional) {object} configuration for the plugin
   */
  prerollPlugin = function(options) {
    var settings = videojs.util.mergeOptions(defaults, options), player = this;
    player.preroll = {adDone:false};
    player.on('contentupdate', function() {
      if(!player.preroll.shouldPlayPreroll()){
        player.trigger('adscanceled');
      }else{
        player.trigger('adsready');
      }
    });
    player.on('readyforpreroll', function() {
      // No video? No ad.
      if(!player.preroll.shouldPlayPreroll()){
        player.trigger('adscanceled');
        return;
      }

      // Initialize ad mode
      player.ads.startLinearAdMode();

      // Change player src to ad src
      player.src(settings.src);
      player.one('durationchange', function() {
        player.play();
      });

      //Fallback in case preload = none
      player.one('progress', function() {
        player.play();
      });

      if(settings.href !== ''){
        // link overlay
        var blocker = document.createElement('a');
        blocker.className = 'preroll-blocker';
        blocker.href = settings.href;
        blocker.target = settings.target || '_blank';
        blocker.onclick = function() {
          player.trigger('adclick');
        };
        player.preroll.blocker = blocker;
        player.el().insertBefore(blocker, player.controlBar.el());
      }

      if (settings.allowSkip !== false){
        var skipButton = document.createElement('div');
        skipButton.className = 'preroll-skip-button';
        player.preroll.skipButton = skipButton;
        player.el().appendChild(skipButton);

        skipButton.onclick = function(e) {
          var Event = Event || window.Event;
          if((' ' + player.preroll.skipButton.className + ' ').indexOf(' enabled ') >= 0) {
            player.preroll.exitPreroll();
          }
          if(Event.prototype.stopPropagation !== undefined) {
            e.stopPropagation();
          } else {
            return false;
          }
        };
      }
      player.one('ended', player.preroll.exitPreroll);
      player.on('timeupdate', player.preroll.timeupdate);
      player.one('error', player.preroll.prerollError);
    });
    player.preroll.shouldPlayPreroll = function(){
      if (settings.src === ''){
        return false;
      }
      if (player.preroll.adDone === true){
        return false;
      }
      return true;
    };
    player.preroll.exitPreroll = function() {
      if(typeof player.preroll.skipButton !== 'undefined'){
        player.preroll.skipButton.parentNode.removeChild(player.preroll.skipButton);
      }
      if(typeof player.preroll.blocker !== 'undefined'){
        player.preroll.blocker.parentNode.removeChild(player.preroll.blocker);
      }
      player.off('timeupdate', player.preroll.timeupdate);
      player.off('ended', player.preroll.exitPreroll);
      player.off('error', player.preroll.prerollError);
      if (settings.repeatAd !== true){
        player.preroll.adDone=true;
      }
      player.ads.endLinearAdMode();
    };
    player.preroll.timeupdate = function(e) {
      player.loadingSpinner.el().style.display = 'none';
      var timeLeft = Math.ceil(settings.skipTime - player.currentTime());
      if(timeLeft > 0) {
        player.preroll.skipButton.innerHTML = 'Skip in ' + timeLeft + '...';
      } else {
        if((' ' + player.preroll.skipButton.className + ' ').indexOf(' enabled ') === -1){
          player.preroll.skipButton.className += ' enabled';
          player.preroll.skipButton.innerHTML = 'Skip';
        }
      }
    };
    player.preroll.prerollError = function(e){
      player.preroll.exitPreroll();
    };
    if (player.currentSrc()) {
      if(player.preroll.shouldPlayPreroll()){
        player.trigger('adsready');
      }else{
        player.trigger('adscanceled');
      }
    }
  };

  // register the plugin
  videojs.plugin('preroll', prerollPlugin);
})(window, window.videojs);
<commit_msg>Another allowSkip fix, thanks to @codedad-io (fixes #8)<commit_after>/*! videojs-preroll - v0.2.0 - 2014-12-08
* Copyright (c) 2014 Sano Webdevelopment;
* Copyright (c) 2014 The Onion
* Licensed MIT */
(function(window, videojs) {
  'use strict';

  var defaults = {
    src : '',
    href : '',
    target: '_blank',
    allowSkip: true,
    skipTime: 5,
    repeatAd: false
  }, prerollPlugin;

  /**
   * Initialize the plugin.
   *
   * @param options
   *            (optional) {object} configuration for the plugin
   */
  prerollPlugin = function(options) {
    var settings = videojs.util.mergeOptions(defaults, options), player = this;
    player.preroll = {adDone:false};
    player.on('contentupdate', function() {
      if(!player.preroll.shouldPlayPreroll()){
        player.trigger('adscanceled');
      }else{
        player.trigger('adsready');
      }
    });
    player.on('readyforpreroll', function() {
      // No video? No ad.
      if(!player.preroll.shouldPlayPreroll()){
        player.trigger('adscanceled');
        return;
      }

      // Initialize ad mode
      player.ads.startLinearAdMode();

      // Change player src to ad src
      player.src(settings.src);
      player.one('durationchange', function() {
        player.play();
      });

      //Fallback in case preload = none
      player.one('progress', function() {
        player.play();
      });

      if(settings.href !== ''){
        // link overlay
        var blocker = document.createElement('a');
        blocker.className = 'preroll-blocker';
        blocker.href = settings.href;
        blocker.target = settings.target || '_blank';
        blocker.onclick = function() {
          player.trigger('adclick');
        };
        player.preroll.blocker = blocker;
        player.el().insertBefore(blocker, player.controlBar.el());
      }

      if (settings.allowSkip !== false){
        var skipButton = document.createElement('div');
        skipButton.className = 'preroll-skip-button';
        player.preroll.skipButton = skipButton;
        player.el().appendChild(skipButton);

        skipButton.onclick = function(e) {
          var Event = Event || window.Event;
          if((' ' + player.preroll.skipButton.className + ' ').indexOf(' enabled ') >= 0) {
            player.preroll.exitPreroll();
          }
          if(Event.prototype.stopPropagation !== undefined) {
            e.stopPropagation();
          } else {
            return false;
          }
        };
        player.on('timeupdate', player.preroll.timeupdate);
      }
      player.one('ended', player.preroll.exitPreroll);
      player.one('error', player.preroll.prerollError);
    });
    player.preroll.shouldPlayPreroll = function(){
      if (settings.src === ''){
        return false;
      }
      if (player.preroll.adDone === true){
        return false;
      }
      return true;
    };
    player.preroll.exitPreroll = function() {
      if(typeof player.preroll.skipButton !== 'undefined'){
        player.preroll.skipButton.parentNode.removeChild(player.preroll.skipButton);
      }
      if(typeof player.preroll.blocker !== 'undefined'){
        player.preroll.blocker.parentNode.removeChild(player.preroll.blocker);
      }
      player.off('timeupdate', player.preroll.timeupdate);
      player.off('ended', player.preroll.exitPreroll);
      player.off('error', player.preroll.prerollError);
      if (settings.repeatAd !== true){
        player.preroll.adDone=true;
      }
      player.ads.endLinearAdMode();
    };
    player.preroll.timeupdate = function(e) {
      player.loadingSpinner.el().style.display = 'none';
      var timeLeft = Math.ceil(settings.skipTime - player.currentTime());
      if(timeLeft > 0) {
        player.preroll.skipButton.innerHTML = 'Skip in ' + timeLeft + '...';
      } else {
        if((' ' + player.preroll.skipButton.className + ' ').indexOf(' enabled ') === -1){
          player.preroll.skipButton.className += ' enabled';
          player.preroll.skipButton.innerHTML = 'Skip';
        }
      }
    };
    player.preroll.prerollError = function(e){
      player.preroll.exitPreroll();
    };
    if (player.currentSrc()) {
      if(player.preroll.shouldPlayPreroll()){
        player.trigger('adsready');
      }else{
        player.trigger('adscanceled');
      }
    }
  };

  // register the plugin
  videojs.plugin('preroll', prerollPlugin);
})(window, window.videojs);
<|endoftext|>