<commit_before>'use strict';

const {
  GraphQLObjectType,
  GraphQLList,
  GraphQLID,
  GraphQLInt,
  GraphQLFloat,
  GraphQLBoolean,
  GraphQLString,
  GraphQLNonNull,
} = require('graphql');
const { mapValues } = require('lodash');

const { EngineError } = require('../../../../error');
const { getTypeName } = require('./name');
const { getModelsByMethod, findOperations } = require('./models');
const { getDescription, getDeprecationReason } = require('./description');

// Retrieves the GraphQL type for a given IDL definition
const getType = function (def, opts) {
  return getField(def, opts).type;
};

// Retrieves a GraphQL field info for a given IDL definition, i.e. an object that can be passed to new GraphQLObjectType({ fields })
// Includes return type, resolve function, arguments, etc.
const getField = function (def, opts) {
  // Add field description|deprecation_reason, taken from IDL definition
  let description = getDescription({ def, prefix: opts.operation, multiple: def.items !== undefined });
  let deprecationReason = getDeprecationReason({ def });

  // Done so that children can get a cached reference of parent type, while avoiding infinite recursion
  // Only cache schemas that have a model name, because they are the only one that can recurse
  // Namespace by operation, because operations can have slightly different types
  const modelName = def.model;
  const key = modelName && `field/${modelName}/${opts.operation}`;
  if (key && opts.cache.exists(key)) {
    const cachedDef = opts.cache.get(key);
    // Sub-models can override top-level models descriptions
    description = description || cachedDef.description;
    deprecationReason = deprecationReason || cachedDef.deprecationReason;
    return Object.assign({}, cachedDef, { description, deprecationReason });
  }

  // Retrieves correct field
  const fieldInfo = graphQLFieldsInfo.find(possibleType => possibleType.condition(def, opts));
  if (!fieldInfo) {
    throw new EngineError(`Could not parse property into a GraphQL type: ${JSON.stringify(def)}`, { reason: 'GRAPHQL_WRONG_DEFINITION' });
  }
  // Retrieves field information
  const field = fieldInfo.value(def, opts);
  // The field description|deprecationReason is type-agnostic, so is not inside `fieldInfo.value()`
  Object.assign(field, { description, deprecationReason });

  if (key) {
    opts.cache.set(key, field);
  }
  return field;
};

/**
 * Maps an IDL definition into a GraphQL field information, including type
 * The first matching one will be used, i.e. order matters: required modifier, then array modifier come first
 */
const graphQLFieldsInfo = [

  {
    condition: def => def.required,
    value(def, opts) {
      // Goal is to avoid infinite recursion, i.e. without modification the same graphQLFieldsInfo would be hit again
      const modifiedDef = Object.assign({}, def, { required: false });
      const subType = getType(modifiedDef, opts);
      const type = new GraphQLNonNull(subType);
      return { type };
    },
  },

  {
    condition: def => def.type === 'array' && typeof def.items === 'object',
    value(def, opts) {
      const subDef = def.items;
      const subType = getType(subDef, opts);
      const type = new GraphQLList(subType);
      const fieldInfo = { type };

      // If this is a top-level model, assign resolver
      if (subDef.model) {
        Object.assign(fieldInfo, {
          args: {
            id: {
              type: GraphQLInt,
              //description: 'id to look at',
              defaultValue: 10
            },
          },
          async resolve(_, args, { callback }) {
            const operation = findOperations({ prefix: opts.operation, multiple: true });
            return await executeOperation({ operation, args, callback });
          },
        });
      }

      return fieldInfo;
    },
  },

  // Top-level method, e.g. 'Query' or 'Mutation'
  {
    condition: (_, { isMethod }) => isMethod,
    value(def, opts) {
      // Do this only at top-level
      opts.isMethod = false;

      // Retrieve the top-level operations
      const methodModels = getModelsByMethod(opts.methodName, opts);

      const fields = methodModels.reduce((fields, model) => {
        // Pass current operation down to sub-fields
        const operation = model.operation;
        // Keep models as options, so that sub-models can point to them, but only for current operation
        const operationsModels = methodModels.filter(methodModel => methodModel.operation === operation);
        opts = Object.assign({}, opts, { operation, operationsModels });

        fields[model.operationName] = getField(model, opts);
        return fields;
      }, {});

      const name = getTypeName(def);
      const description = getDescription({ def, prefix: opts.operation });

      const type = new GraphQLObjectType({
        name,
        description,
        fields,
      });

      const fieldInfo = { type };
      return fieldInfo;
    }
  },

  {
    condition: def => def.type === 'object',
    value(def, opts) {
      // If this definition points to a top-level model, use that model instead
      const operationsModels = opts.operationsModels;
      if (def.model && operationsModels) {
        def = operationsModels.find(operationsModel => operationsModel.model === def.model) || def;
      }

      const name = getTypeName(def, opts.operation);
      const description = getDescription({ def, prefix: opts.operation });

      const type = new GraphQLObjectType({
        name,
        description,

        // This needs to be function, otherwise we run in an infinite recursion,
        // if the children try to reference a parent type
        fields() {
          // Recurse over children
          return mapValues(def.properties, childDef => {
            const field = getField(childDef, opts);
            //console.log(def.model, JSON.stringify(field), JSON.stringify(childDef));
            return field;
          });
        },
      });

      let fieldInfo = { type };

      // If this is a top-level model, assign resolver
      if (def.model) {
        Object.assign(fieldInfo, {
          async resolve(_, args, { callback }) {
            const operation = findOperations({ prefix: opts.operation, multiple: false });
            return await executeOperation({ operation, args, callback });
          },
        });
      }

      return fieldInfo;
    },
  },

  {
    condition: def => def.type === 'integer' && def.format === 'id',
    value: () => ({ type: GraphQLID }),
  },

  {
    condition: def => def.type === 'integer',
    value: () => ({ type: GraphQLInt }),
  },

  {
    condition: def => def.type === 'number',
    value: () => ({ type: GraphQLFloat }),
  },

  {
    condition: def => def.type === 'string',
    value: () => ({ type: GraphQLString }),
  },

  {
    condition: def => def.type === 'boolean',
    value: () => ({ type: GraphQLBoolean }),
  },

];

const executeOperation = async function ({ operation, args = {}, callback }) {
  const response = await callback({ operation, args });
  return response;
};

module.exports = {
  getType,
};
<commit_msg>Simplify code<commit_after>'use strict';

const {
  GraphQLObjectType,
  GraphQLList,
  GraphQLID,
  GraphQLInt,
  GraphQLFloat,
  GraphQLBoolean,
  GraphQLString,
  GraphQLNonNull,
} = require('graphql');
const { mapValues, defaults } = require('lodash');

const { EngineError } = require('../../../../error');
const { getTypeName } = require('./name');
const { getModelsByMethod, findOperations } = require('./models');
const { getDescription, getDeprecationReason } = require('./description');

// Retrieves the GraphQL type for a given IDL definition
const getType = function (def, opts) {
  return getField(def, opts).type;
};

// Retrieves a GraphQL field info for a given IDL definition, i.e. an object that can be passed to new GraphQLObjectType({ fields })
// Includes return type, resolve function, arguments, etc.
const getField = function (def, opts) {
  // Add field description|deprecation_reason, taken from IDL definition
  const description = getDescription({ def, prefix: opts.operation, multiple: def.items !== undefined });
  const deprecationReason = getDeprecationReason({ def });

  // Done so that children can get a cached reference of parent type, while avoiding infinite recursion
  // Only cache schemas that have a model name, because they are the only one that can recurse
  // Namespace by operation, because operations can have slightly different types
  const modelName = def.model;
  const key = modelName && `field/${modelName}/${opts.operation}`;
  if (key && opts.cache.exists(key)) {
    const cachedDef = opts.cache.get(key);
    // Sub-models can override top-level models descriptions
    return defaults({}, cachedDef, { description, deprecationReason });
  }

  // Retrieves correct field
  const fieldInfo = graphQLFieldsInfo.find(possibleType => possibleType.condition(def, opts));
  if (!fieldInfo) {
    throw new EngineError(`Could not parse property into a GraphQL type: ${JSON.stringify(def)}`, { reason: 'GRAPHQL_WRONG_DEFINITION' });
  }
  // Retrieves field information
  const field = fieldInfo.value(def, opts);
  // The field description|deprecationReason is type-agnostic, so is not inside `fieldInfo.value()`
  Object.assign(field, { description, deprecationReason });

  if (key) {
    opts.cache.set(key, field);
  }
  return field;
};

/**
 * Maps an IDL definition into a GraphQL field information, including type
 * The first matching one will be used, i.e. order matters: required modifier, then array modifier come first
 */
const graphQLFieldsInfo = [

  {
    condition: def => def.required,
    value(def, opts) {
      // Goal is to avoid infinite recursion, i.e. without modification the same graphQLFieldsInfo would be hit again
      const modifiedDef = Object.assign({}, def, { required: false });
      const subType = getType(modifiedDef, opts);
      const type = new GraphQLNonNull(subType);
      return { type };
    },
  },

  {
    condition: def => def.type === 'array' && typeof def.items === 'object',
    value(def, opts) {
      const subDef = def.items;
      const subType = getType(subDef, opts);
      const type = new GraphQLList(subType);
      const fieldInfo = { type };

      // If this is a top-level model, assign resolver
      if (subDef.model) {
        Object.assign(fieldInfo, {
          args: {
            id: {
              type: GraphQLInt,
              //description: 'id to look at',
              defaultValue: 10
            },
          },
          async resolve(_, args, { callback }) {
            const operation = findOperations({ prefix: opts.operation, multiple: true });
            return await executeOperation({ operation, args, callback });
          },
        });
      }

      return fieldInfo;
    },
  },

  // Top-level method, e.g. 'Query' or 'Mutation'
  {
    condition: (_, { isMethod }) => isMethod,
    value(def, opts) {
      // Do this only at top-level
      opts.isMethod = false;

      // Retrieve the top-level operations
      const methodModels = getModelsByMethod(opts.methodName, opts);

      const fields = methodModels.reduce((fields, model) => {
        // Pass current operation down to sub-fields
        const operation = model.operation;
        // Keep models as options, so that sub-models can point to them, but only for current operation
        const operationsModels = methodModels.filter(methodModel => methodModel.operation === operation);
        opts = Object.assign({}, opts, { operation, operationsModels });

        fields[model.operationName] = getField(model, opts);
        return fields;
      }, {});

      const name = getTypeName(def);
      const description = getDescription({ def, prefix: opts.operation });

      const type = new GraphQLObjectType({
        name,
        description,
        fields,
      });

      const fieldInfo = { type };
      return fieldInfo;
    }
  },

  {
    condition: def => def.type === 'object',
    value(def, opts) {
      // If this definition points to a top-level model, use that model instead
      const operationsModels = opts.operationsModels;
      if (def.model && operationsModels) {
        def = operationsModels.find(operationsModel => operationsModel.model === def.model) || def;
      }

      const name = getTypeName(def, opts.operation);
      const description = getDescription({ def, prefix: opts.operation });

      const type = new GraphQLObjectType({
        name,
        description,

        // This needs to be function, otherwise we run in an infinite recursion,
        // if the children try to reference a parent type
        fields() {
          // Recurse over children
          return mapValues(def.properties, childDef => {
            const field = getField(childDef, opts);
            //console.log(def.model, JSON.stringify(field), JSON.stringify(childDef));
            return field;
          });
        },
      });

      let fieldInfo = { type };

      // If this is a top-level model, assign resolver
      if (def.model) {
        Object.assign(fieldInfo, {
          async resolve(_, args, { callback }) {
            const operation = findOperations({ prefix: opts.operation, multiple: false });
            return await executeOperation({ operation, args, callback });
          },
        });
      }

      return fieldInfo;
    },
  },

  {
    condition: def => def.type === 'integer' && def.format === 'id',
    value: () => ({ type: GraphQLID }),
  },

  {
    condition: def => def.type === 'integer',
    value: () => ({ type: GraphQLInt }),
  },

  {
    condition: def => def.type === 'number',
    value: () => ({ type: GraphQLFloat }),
  },

  {
    condition: def => def.type === 'string',
    value: () => ({ type: GraphQLString }),
  },

  {
    condition: def => def.type === 'boolean',
    value: () => ({ type: GraphQLBoolean }),
  },

];

const executeOperation = async function ({ operation, args = {}, callback }) {
  const response = await callback({ operation, args });
  return response;
};

module.exports = {
  getType,
};
<|endoftext|>


<commit_before>import $ from 'jquery';
// import $ from 'bootstrap';

$(() => {

    // Execute code if the page is completely loaded...

});
<commit_msg>Remove unused boilerplate JS<commit_after><|endoftext|>


<commit_before>const hasMediaStates = ['playing', 'paused', 'unknown'];

export default class MediaPlayer {
  constructor(hass, stateObj) {
    this.serviceActions = hass.serviceActions;
    this.stateObj = stateObj;
  }

  get isOff() {
    return this.stateObj.state === 'off';
  }

  get isIdle() {
    return this.stateObj.state === 'idle';
  }

  get isMuted() {
    return this.stateObj.attributes.is_volume_muted;
  }

  get isPaused() {
    return this.stateObj.state === 'paused';
  }

  get isPlaying() {
    return this.stateObj.state === 'playing';
  }

  get isMusic() {
    return this.stateObj.attributes.media_content_type === 'music';
  }

  get isTVShow() {
    return this.stateObj.attributes.media_content_type === 'tvshow';
  }

  get hasMediaControl() {
    return hasMediaStates.indexOf(this.stateObj.state) !== -1;
  }

  get volumeSliderValue() {
    return this.stateObj.attributes.volume_level * 100;
  }

  get showProgress() {
    return (
      (this.isPlaying || this.isPaused) &&
      'media_position' in this.stateObj.attributes &&
      'media_position_updated_at' in this.stateObj.attributes);
  }

  get currentProgress() {
    return (
      this.stateObj.attributes.media_position +
      ((Date.now() -
        new Date(this.stateObj.attributes.media_position_updated_at)) / 1000));
  }

  /* eslint-disable no-bitwise */

  get supportsPause() {
    return (this.stateObj.attributes.supported_media_commands & 1) !== 0;
  }

  get supportsVolumeSet() {
    return (this.stateObj.attributes.supported_media_commands & 4) !== 0;
  }

  get supportsVolumeMute() {
    return (this.stateObj.attributes.supported_media_commands & 8) !== 0;
  }

  get supportsPreviousTrack() {
    return (this.stateObj.attributes.supported_media_commands & 16) !== 0;
  }

  get supportsNextTrack() {
    return (this.stateObj.attributes.supported_media_commands & 32) !== 0;
  }

  get supportsTurnOn() {
    return (this.stateObj.attributes.supported_media_commands & 128) !== 0;
  }

  get supportsTurnOff() {
    return (this.stateObj.attributes.supported_media_commands & 256) !== 0;
  }

  get supportsVolumeButtons() {
    return (this.stateObj.attributes.supported_media_commands & 1024) !== 0;
  }

  /* eslint-enable no-bitwise */

  get primaryText() {
    return this.stateObj.attributes.media_title ||
           this.stateObj.stateDisplay;
  }

  get secondaryText() {
    if (this.isMusic) {
      return this.stateObj.attributes.media_artist;
    } else if (this.isTVShow) {
      let text = this.stateObj.attributes.media_series_title;

      if (this.stateObj.attributes.media_season) {
        text += ` S${this.stateObj.attributes.media_season}`;

        if (this.stateObj.attributes.media_episode) {
          text += `E${this.stateObj.attributes.media_episode}`;
        }
      }

      return text;
    } else if (this.stateObj.attributes.app_name) {
      return this.stateObj.attributes.app_name;
    }
    return '';
  }

  mediaPlayPause() {
    this.callService('media_play_pause');
  }

  nextTrack() {
    this.callService('media_next_track');
  }

  playbackControl() {
    this.callService('media_play_pause');
  }

  previousTrack() {
    this.callService('media_previous_track');
  }

  setVolume(volume) {
    this.callService('volume_set', { volume_level: volume });
  }

  togglePower() {
    if (this.isOff) {
      this.turnOn();
    } else {
      this.turnOff();
    }
  }

  turnOff() {
    this.callService('turn_off');
  }

  turnOn() {
    this.callService('turn_on');
  }

  volumeDown() {
    this.callService('volume_down');
  }

  volumeMute(mute) {
    if (!this.supportsVolumeMute) {
      throw new Error('Muting volume not supported');
    }
    this.callService('volume_mute', { is_volume_muted: mute });
  }

  volumeUp() {
    this.callService('volume_down');
  }

  // helper method

  callService(service, data) {
    const serviceData = data || {};
    serviceData.entity_id = this.stateObj.entityId;
    this.serviceActions.callService('media_player', service, serviceData);
  }
}
<commit_msg>Media player: add supportsPlayMedia<commit_after>const hasMediaStates = ['playing', 'paused', 'unknown'];

export default class MediaPlayer {
  constructor(hass, stateObj) {
    this.serviceActions = hass.serviceActions;
    this.stateObj = stateObj;
  }

  get isOff() {
    return this.stateObj.state === 'off';
  }

  get isIdle() {
    return this.stateObj.state === 'idle';
  }

  get isMuted() {
    return this.stateObj.attributes.is_volume_muted;
  }

  get isPaused() {
    return this.stateObj.state === 'paused';
  }

  get isPlaying() {
    return this.stateObj.state === 'playing';
  }

  get isMusic() {
    return this.stateObj.attributes.media_content_type === 'music';
  }

  get isTVShow() {
    return this.stateObj.attributes.media_content_type === 'tvshow';
  }

  get hasMediaControl() {
    return hasMediaStates.indexOf(this.stateObj.state) !== -1;
  }

  get volumeSliderValue() {
    return this.stateObj.attributes.volume_level * 100;
  }

  get showProgress() {
    return (
      (this.isPlaying || this.isPaused) &&
      'media_position' in this.stateObj.attributes &&
      'media_position_updated_at' in this.stateObj.attributes);
  }

  get currentProgress() {
    return (
      this.stateObj.attributes.media_position +
      ((Date.now() -
        new Date(this.stateObj.attributes.media_position_updated_at)) / 1000));
  }

  /* eslint-disable no-bitwise */

  get supportsPause() {
    return (this.stateObj.attributes.supported_media_commands & 1) !== 0;
  }

  get supportsVolumeSet() {
    return (this.stateObj.attributes.supported_media_commands & 4) !== 0;
  }

  get supportsVolumeMute() {
    return (this.stateObj.attributes.supported_media_commands & 8) !== 0;
  }

  get supportsPreviousTrack() {
    return (this.stateObj.attributes.supported_media_commands & 16) !== 0;
  }

  get supportsNextTrack() {
    return (this.stateObj.attributes.supported_media_commands & 32) !== 0;
  }

  get supportsTurnOn() {
    return (this.stateObj.attributes.supported_media_commands & 128) !== 0;
  }

  get supportsTurnOff() {
    return (this.stateObj.attributes.supported_media_commands & 256) !== 0;
  }

  get supportsPlayMedia() {
    return (this.stateObj.attributes.supported_media_commands & 512) !== 0;
  }

  get supportsVolumeButtons() {
    return (this.stateObj.attributes.supported_media_commands & 1024) !== 0;
  }

  /* eslint-enable no-bitwise */

  get primaryText() {
    return this.stateObj.attributes.media_title ||
           this.stateObj.stateDisplay;
  }

  get secondaryText() {
    if (this.isMusic) {
      return this.stateObj.attributes.media_artist;
    } else if (this.isTVShow) {
      let text = this.stateObj.attributes.media_series_title;

      if (this.stateObj.attributes.media_season) {
        text += ` S${this.stateObj.attributes.media_season}`;

        if (this.stateObj.attributes.media_episode) {
          text += `E${this.stateObj.attributes.media_episode}`;
        }
      }

      return text;
    } else if (this.stateObj.attributes.app_name) {
      return this.stateObj.attributes.app_name;
    }
    return '';
  }

  mediaPlayPause() {
    this.callService('media_play_pause');
  }

  nextTrack() {
    this.callService('media_next_track');
  }

  playbackControl() {
    this.callService('media_play_pause');
  }

  previousTrack() {
    this.callService('media_previous_track');
  }

  setVolume(volume) {
    this.callService('volume_set', { volume_level: volume });
  }

  togglePower() {
    if (this.isOff) {
      this.turnOn();
    } else {
      this.turnOff();
    }
  }

  turnOff() {
    this.callService('turn_off');
  }

  turnOn() {
    this.callService('turn_on');
  }

  volumeDown() {
    this.callService('volume_down');
  }

  volumeMute(mute) {
    if (!this.supportsVolumeMute) {
      throw new Error('Muting volume not supported');
    }
    this.callService('volume_mute', { is_volume_muted: mute });
  }

  volumeUp() {
    this.callService('volume_down');
  }

  // helper method

  callService(service, data) {
    const serviceData = data || {};
    serviceData.entity_id = this.stateObj.entityId;
    this.serviceActions.callService('media_player', service, serviceData);
  }
}
<|endoftext|>


<commit_before>import { serviceActions } from '../util/home-assistant-js-instance';

import Polymer from '../polymer';

export default new Polymer({
  is: 'more-info-alarm_control_panel',
  handleDisarmTap() {
    this.callService('alarm_disarm', {code: this.enteredCode});
  },
  handleHomeTap() {
    this.callService('alarm_arm_home', {code: this.enteredCode});
  },
  handleAwayTap() {
    this.callService('alarm_arm_away', {code: this.enteredCode});
  },
  properties: {
    stateObj: {
      type: Object,
      observer: 'stateObjChanged',
    },
    enteredCode: {
      type: String,
      value: '',
    },
    disarmButtonVisible: {
      type: Boolean,
      value: false,
    },
    armHomeButtonVisible: {
      type: Boolean,
      value: false,
    },
    armAwayButtonVisible: {
      type: Boolean,
      value: false,
    },
    codeInputVisible: {
      type: Boolean,
      value: false,
    },
    codeInputEnabled: {
      type: Boolean,
      value: false,
    },
    codeFormat: {
      type: String,
      value: '',
    },
    codeValid: {
      type: Boolean,
      computed: 'validateCode(enteredCode, codeFormat)',
    },
  },
  validateCode(code, format) {
    const re = new RegExp(format);
    if (format === null) {
      return true;
    }
    return re.test(code);
  },
  stateObjChanged(newVal) {
    if (newVal) {
      this.codeFormat = newVal.attributes.code_format;
      this.codeInputVisible = this.codeFormat !== null;
      this.codeInputEnabled = (
        newVal.state === 'armed_home' ||
	newVal.state === 'armed_away' ||
	newVal.state === 'disarmed');
      this.disarmButtonVisible = (
	newVal.state === 'armed_home' ||
	newVal.state === 'armed_away');
      this.armHomeButtonVisible = newVal.state === 'disarmed';
      this.armAwayButtonVisible = newVal.state === 'disarmed';
    }
    this.async(() => this.fire('iron-resize'), 500);
  },
  callService(service, data) {
    const serviceData = data || {};
    serviceData.entity_id = this.stateObj.entityId;
    serviceActions.callService('alarm_control_panel', service, serviceData);
  },
});
<commit_msg>prepare alarm for new states<commit_after>import { serviceActions } from '../util/home-assistant-js-instance';

import Polymer from '../polymer';

export default new Polymer({
  is: 'more-info-alarm_control_panel',
  handleDisarmTap() {
    this.callService('alarm_disarm', {code: this.enteredCode});
  },
  handleHomeTap() {
    this.callService('alarm_arm_home', {code: this.enteredCode});
  },
  handleAwayTap() {
    this.callService('alarm_arm_away', {code: this.enteredCode});
  },
  properties: {
    stateObj: {
      type: Object,
      observer: 'stateObjChanged',
    },
    enteredCode: {
      type: String,
      value: '',
    },
    disarmButtonVisible: {
      type: Boolean,
      value: false,
    },
    armHomeButtonVisible: {
      type: Boolean,
      value: false,
    },
    armAwayButtonVisible: {
      type: Boolean,
      value: false,
    },
    codeInputVisible: {
      type: Boolean,
      value: false,
    },
    codeInputEnabled: {
      type: Boolean,
      value: false,
    },
    codeFormat: {
      type: String,
      value: '',
    },
    codeValid: {
      type: Boolean,
      computed: 'validateCode(enteredCode, codeFormat)',
    },
  },
  validateCode(code, format) {
    const re = new RegExp(format);
    if (format === null) {
      return true;
    }
    return re.test(code);
  },
  stateObjChanged(newVal) {
    if (newVal) {
      this.codeFormat = newVal.attributes.code_format;
      this.codeInputVisible = this.codeFormat !== null;
      this.codeInputEnabled = (
        newVal.state === 'armed_home' ||
	newVal.state === 'armed_away' ||
	newVal.state === 'disarmed' ||
	newVal.state === 'pending' ||
	newVal.state === 'triggered');
      this.disarmButtonVisible = (
	newVal.state === 'armed_home' ||
	newVal.state === 'armed_away' ||
	newVal.state === 'pending' ||
	newVal.state === 'triggered');
      this.armHomeButtonVisible = newVal.state === 'disarmed';
      this.armAwayButtonVisible = newVal.state === 'disarmed';
    }
    this.async(() => this.fire('iron-resize'), 500);
  },
  callService(service, data) {
    const serviceData = data || {};
    serviceData.entity_id = this.stateObj.entityId;
    serviceActions.callService('alarm_control_panel', service, serviceData);
  },
});
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function() {

	'use strict';

	/**
	 * @ngdoc directive
	 * @restrict A
	 * @name openlmis-form.directive:positiveInteger
	 *
	 * @description
	 * Restricts the ngModel to only allow positive integers.
	 *
	 * @example
	 * Extend the input element to force it to only accept positive integers as values.
	 * ```
	 * <input ng-model="someModel" positive-integer>
	 * ```
	 */
	angular
		.module('openlmis-form')
		.directive('positiveInteger', positiveInteger);

	function positiveInteger() {
		var directive = {
			require: 'ngModel',
			link: link
		};
		return directive;

		function link(scope, element, attrs, modelCtrl) {

			element.attr('type', 'number');
			element.addClass('number');

			var keyCode = [69, 190, 107, 109];
	        element.bind('keydown', function(event) {
	            if ($.inArray(event.which, keyCode) !== -1) {
	                event.preventDefault();
	            }
	        });
		}
	}
})();
<commit_msg>Revert "OLMIS-1447: positiveInteger will now prevent - + from being entered"<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function() {

	'use strict';

	/**
	 * @ngdoc directive
	 * @restrict A
	 * @name openlmis-form.directive:positiveInteger
	 *
	 * @description
	 * Restricts the ngModel to only allow positive integers.
	 *
	 * @example
	 * Extend the input element to force it to only accept positive integers as values.
	 * ```
	 * <input ng-model="someModel" positive-integer>
	 * ```
	 */
	angular
		.module('openlmis-form')
		.directive('positiveInteger', positiveInteger);

	function positiveInteger() {
		var directive = {
			require: 'ngModel',
			link: link
		};
		return directive;

		function link(scope, element, attrs, modelCtrl) {

			element.attr('type', 'number');
			element.addClass('number');

			var keyCode = [69, 190];
	        element.bind('keydown', function(event) {
	            if ($.inArray(event.which, keyCode) !== -1) {
	                event.preventDefault();
	            }
	        });
		}
	}
})();
<|endoftext|>


<commit_before>;(function() {
  'use strict';

  sigma.utils.pkg('sigma.webgl.edges');

  /**
   * This edge renderer will display edges as polylines using a vertex shader.
   * This should be faster than rendering lines as triangles and supports
   * thickness better than gl.LINES.
   *
   * This should also pave the way towards easy and efficient curved edges
   * rendering later.
   */
  sigma.webgl.edges.shader = {
    POINTS: 4,
    ATTRIBUTES: 6,
    addEdge: function(edge, source, target, data, i, prefix, settings) {
      var thickness = (edge[prefix + 'size'] || 1),
          x1 = source[prefix + 'x'],
          y1 = source[prefix + 'y'],
          x2 = target[prefix + 'x'],
          y2 = target[prefix + 'y'],
          color = edge.color;

      if (!color)
        switch (settings('edgeColor')) {
          case 'source':
            color = source.color || settings('defaultNodeColor');
            break;
          case 'target':
            color = target.color || settings('defaultNodeColor');
            break;
          default:
            color = settings('defaultEdgeColor');
            break;
        }

      // Normalize color:
      color = sigma.utils.floatColor(color);

      // Computing normals:
      var dx = x2 - x1,
          dy = y2 - y1,
          len = dx * dx + dy * dy;

      len = 1 / Math.sqrt(len);

      var normals = [
        dx * len,
        dy * len
      ];

      // First point
      data[i++] = x1;
      data[i++] = y1;
      data[i++] = normals[0];
      data[i++] = normals[1];
      data[i++] = thickness;
      data[i++] = color;

      // First point flipped
      data[i++] = x1;
      data[i++] = y1;
      data[i++] = normals[1];
      data[i++] = normals[0];
      data[i++] = thickness;
      data[i++] = color;

      // Second point
      data[i++] = x2;
      data[i++] = y2;
      data[i++] = normals[0];
      data[i++] = normals[1];
      data[i++] = thickness;
      data[i++] = color;

      // Second point flipped
      data[i++] = x2;
      data[i++] = y2;
      data[i++] = normals[1];
      data[i++] = normals[0];
      data[i++] = thickness;
      data[i++] = color;
    },
    render: function(gl, program, data, params) {
      var buffer;

      // Define attributes:
      var positionLocation =
            gl.getAttribLocation(program, 'a_position'),
          normalLocation =
            gl.getAttribLocation(program, 'a_normal'),
          thicknessLocation =
            gl.getAttribLocation(program, 'a_thickness'),
          colorLocation =
            gl.getAttribLocation(program, 'a_color'),
          resolutionLocation =
            gl.getUniformLocation(program, 'u_resolution'),
          matrixLocation =
            gl.getUniformLocation(program, 'u_matrix');

      buffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
      gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW);

      gl.uniform2f(resolutionLocation, params.width, params.height);
      gl.uniformMatrix3fv(matrixLocation, false, params.matrix);

      gl.enableVertexAttribArray(positionLocation);
      gl.enableVertexAttribArray(normalLocation);
      gl.enableVertexAttribArray(thicknessLocation);
      gl.enableVertexAttribArray(colorLocation);

      gl.vertexAttribPointer(positionLocation,
        2,
        gl.FLOAT,
        false,
        this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
        0
      );
      gl.vertexAttribPointer(normalLocation,
        2,
        gl.FLOAT,
        false,
        this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
        8
      );
      gl.vertexAttribPointer(thicknessLocation,
        1,
        gl.FLOAT,
        false,
        this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
        16
      );
      gl.vertexAttribPointer(colorLocation,
        1,
        gl.FLOAT,
        false,
        this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
        20
      );

      gl.drawArrays(
        gl.TRIANGLES,
        params.start || 0,
        params.count || (data.length / this.ATTRIBUTES)
      );
    },
    initProgram: function(gl) {
      var vertexShader,
          fragmentShader,
          program;

      vertexShader = sigma.utils.loadShader(
        gl,
        [
          'attribute vec2 a_position;',
          'attribute vec2 a_normal;',
          'attribute float a_thickness;',
          'attribute float a_color;',

          'uniform vec2 u_resolution;',
          'uniform mat3 u_matrix;',

          'varying vec4 v_color;',

          'void main() {',

            // Push the point along its normal by half thickness
            'vec2 position = (u_matrix * vec3(a_position, 1)).xy;',
            'position = position.xy + vec2(a_normal * a_thickness / 2.0);',
            'position = (position / u_resolution * 2.0 - 1.0) * vec2(1, -1);',

            // Applying
            'gl_Position = vec4(position, 0, 1);',

            // Extract the color:
            'float c = a_color;',
            'v_color.b = mod(c, 256.0); c = floor(c / 256.0);',
            'v_color.g = mod(c, 256.0); c = floor(c / 256.0);',
            'v_color.r = mod(c, 256.0); c = floor(c / 256.0); v_color /= 255.0;',
            'v_color.a = 1.0;',
          '}'
        ].join('\n'),
        gl.VERTEX_SHADER
      );

      fragmentShader = sigma.utils.loadShader(
        gl,
        [
          'precision mediump float;',

          'varying vec4 v_color;',

          'void main(void) {',
            'gl_FragColor = v_color;',
          '}'
        ].join('\n'),
        gl.FRAGMENT_SHADER
      );

      program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]);

      return program;
    }
  };
})();
<commit_msg>Adding ratio<commit_after>;(function() {
  'use strict';

  sigma.utils.pkg('sigma.webgl.edges');

  /**
   * This edge renderer will display edges as polylines using a vertex shader.
   * This should be faster than rendering lines as triangles and supports
   * thickness better than gl.LINES.
   *
   * This should also pave the way towards easy and efficient curved edges
   * rendering later.
   */
  sigma.webgl.edges.shader = {
    POINTS: 4,
    ATTRIBUTES: 6,
    addEdge: function(edge, source, target, data, i, prefix, settings) {
      var thickness = (edge[prefix + 'size'] || 1),
          x1 = source[prefix + 'x'],
          y1 = source[prefix + 'y'],
          x2 = target[prefix + 'x'],
          y2 = target[prefix + 'y'],
          color = edge.color;

      if (!color)
        switch (settings('edgeColor')) {
          case 'source':
            color = source.color || settings('defaultNodeColor');
            break;
          case 'target':
            color = target.color || settings('defaultNodeColor');
            break;
          default:
            color = settings('defaultEdgeColor');
            break;
        }

      // Normalize color:
      color = sigma.utils.floatColor(color);

      // Computing normals:
      var dx = x2 - x1,
          dy = y2 - y1,
          len = dx * dx + dy * dy;

      len = 1 / Math.sqrt(len);

      var normals = [
        dx * len,
        dy * len
      ];

      // First point
      data[i++] = x1;
      data[i++] = y1;
      data[i++] = normals[0];
      data[i++] = normals[1];
      data[i++] = thickness;
      data[i++] = color;

      // First point flipped
      data[i++] = x1;
      data[i++] = y1;
      data[i++] = normals[1];
      data[i++] = normals[0];
      data[i++] = thickness;
      data[i++] = color;

      // Second point
      data[i++] = x2;
      data[i++] = y2;
      data[i++] = normals[0];
      data[i++] = normals[1];
      data[i++] = thickness;
      data[i++] = color;

      // Second point flipped
      data[i++] = x2;
      data[i++] = y2;
      data[i++] = normals[1];
      data[i++] = normals[0];
      data[i++] = thickness;
      data[i++] = color;
    },
    render: function(gl, program, data, params) {
      var buffer;

      // Define attributes:
      var positionLocation =
            gl.getAttribLocation(program, 'a_position'),
          normalLocation =
            gl.getAttribLocation(program, 'a_normal'),
          thicknessLocation =
            gl.getAttribLocation(program, 'a_thickness'),
          colorLocation =
            gl.getAttribLocation(program, 'a_color'),
          resolutionLocation =
            gl.getUniformLocation(program, 'u_resolution'),
          ratioLocation =
            gl.getUniformLocation(program, 'u_ratio'),
          matrixLocation =
            gl.getUniformLocation(program, 'u_matrix');

      buffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
      gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW);

      gl.uniform2f(resolutionLocation, params.width, params.height);
      gl.uniform1f(
        ratioLocation,
        params.ratio / Math.pow(params.ratio, params.settings('edgesPowRatio'))
      );

      gl.uniformMatrix3fv(matrixLocation, false, params.matrix);

      gl.enableVertexAttribArray(positionLocation);
      gl.enableVertexAttribArray(normalLocation);
      gl.enableVertexAttribArray(thicknessLocation);
      gl.enableVertexAttribArray(colorLocation);

      gl.vertexAttribPointer(positionLocation,
        2,
        gl.FLOAT,
        false,
        this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
        0
      );
      gl.vertexAttribPointer(normalLocation,
        2,
        gl.FLOAT,
        false,
        this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
        8
      );
      gl.vertexAttribPointer(thicknessLocation,
        1,
        gl.FLOAT,
        false,
        this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
        16
      );
      gl.vertexAttribPointer(colorLocation,
        1,
        gl.FLOAT,
        false,
        this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT,
        20
      );

      gl.drawArrays(
        gl.TRIANGLES,
        params.start || 0,
        params.count || (data.length / this.ATTRIBUTES)
      );
    },
    initProgram: function(gl) {
      var vertexShader,
          fragmentShader,
          program;

      vertexShader = sigma.utils.loadShader(
        gl,
        [
          'attribute vec2 a_position;',
          'attribute vec2 a_normal;',
          'attribute float a_thickness;',
          'attribute float a_color;',

          'uniform vec2 u_resolution;',
          'uniform float u_ratio;',
          'uniform mat3 u_matrix;',

          'varying vec4 v_color;',

          'void main() {',

            // Push the point along its normal by half thickness
            'vec2 position = (u_matrix * vec3(a_position, 1)).xy;',
            'position = position.xy + vec2(a_normal * a_thickness / 2.0 * u_ratio);',
            'position = (position / u_resolution * 2.0 - 1.0) * vec2(1, -1);',

            // Applying
            'gl_Position = vec4(position, 0, 1);',

            // Extract the color:
            'float c = a_color;',
            'v_color.b = mod(c, 256.0); c = floor(c / 256.0);',
            'v_color.g = mod(c, 256.0); c = floor(c / 256.0);',
            'v_color.r = mod(c, 256.0); c = floor(c / 256.0); v_color /= 255.0;',
            'v_color.a = 1.0;',
          '}'
        ].join('\n'),
        gl.VERTEX_SHADER
      );

      fragmentShader = sigma.utils.loadShader(
        gl,
        [
          'precision mediump float;',

          'varying vec4 v_color;',

          'void main(void) {',
            'gl_FragColor = v_color;',
          '}'
        ].join('\n'),
        gl.FRAGMENT_SHADER
      );

      program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]);

      return program;
    }
  };
})();
<|endoftext|>


<commit_before>import './ResultsListItem.css';
import React, { Component, PropTypes } from 'react';
import shallowCompare from 'react-addons-shallow-compare';
import { Link } from 'react-router';
import ago from 's-ago';
import uniq from 'lodash/uniq';
import Gravatar from 'react-gravatar';
import PackageScore from 'shared/components/package-score/PackageScore';
import PackageFlags from 'shared/components/package-flags/PackageFlags';
import Tooltip from 'shared/components/tooltip/Tooltip';
import MaterialIcon from 'shared/components/icon/MaterialIcon';
import SvgIcon from 'shared/components/icon/SvgIcon';

class ResultsListItem extends Component {
    shouldComponentUpdate(nextProps, nextState) {
        return shallowCompare(this, nextProps, nextState);
    }

    render() {
        return (

                { /* Headline */ }

                    { this.props.package.name }
                    ({ this.props.package.version })

                    <PackageScore score={ this.props.score } />

                { /* Description */ }
                { this.props.package.description ?

                        { this.props.flags ? <PackageFlags package={ this.props.package } flags={ this.props.flags } /> : '' }
                        { this.props.package.description }

 :
                    '' }

                { /* Keywords */ }
                { this._renderKeywords() }

                { /* Updated by.. */ }
                { this._renderPublisherInfo() }

                { /* Useful links */ }
                { this._renderLinks() }

        );
    }

    _renderKeywords() {
        const keywords = uniq(this.props.package.keywords);  // Remove duplicates because we use keywords as React keys
        const keywordsCount = keywords && keywords.length;

        if (!keywordsCount) {
            return '';
        }

        return (

                <MaterialIcon id="local_offer" />
                { keywords.map((keyword, index) =>

                        <Link to={ `/search?q=${encodeURIComponent(keyword)}` }>{ keyword }</Link>
                        { index < keywordsCount - 1 ? ', ' : '' }

                ) }

        );
    }

    _renderPublisherInfo() {
        const hasPublisher = !!(this.props.package.publisher && this.props.package.publisher.username);
        const hasDate = !!(this.props.package.date);

        if (!hasPublisher && !hasDate) {
            return '';
        }

        return (

                updated
                { hasDate ? { ago(new Date(this.props.package.date)) } : '' }

                { hasPublisher ?  by  : '' }
                { hasPublisher ? <a href={ `https://npmjs.com/~${encodeURIComponent(this.props.package.publisher.username)}` }
                    target="_blank" className="publisher-name">{ this.props.package.publisher.username } : '' }
                { hasPublisher ?
                    <Gravatar size={ 20 } email={ this.props.package.publisher.email || 'n/a' }
                        onLoad={ (e) => this._onGravatarLoad(e) } /> : '' }

        );
    }

    _renderLinks() {
        return (

                <Tooltip placement="top" trigger={ ['hover'] } overlay="View this package analysis">
                    <a className="analysis-link" href={ `${this.props.apiUrl}/package/${encodeURIComponent(this.props.package.name)}` }
                        target="_blank">
                        <MaterialIcon id="timeline" />

                </Tooltip>

                <Tooltip placement="top" trigger={ ['hover'] } overlay="View this package in npmjs.org">

                        <SvgIcon id={ SvgIcon.npm } />

                </Tooltip>

                <Tooltip placement="top" trigger={ ['hover'] } overlay="Try this package in RunKit">
                    <a className="runkit-link" href={ `https://runkit.com/npm/${encodeURIComponent(this.props.package.name)}` }
                        target="_blank">
                        <SvgIcon id={ SvgIcon.runkit } />

                </Tooltip>

        );
    }

    _onGravatarLoad(e) {
        e.target.style.opacity = '1';
    }
}

ResultsListItem.propTypes = {
    package: PropTypes.object.isRequired,
    flags: PropTypes.object,
    score: PropTypes.object.isRequired,
    apiUrl: PropTypes.string,
};

ResultsListItem.defaultProps = {
    apiUrl: 'https://api.npms.io',
};

export default ResultsListItem;
<commit_msg>Update overlay text of npmjs.com link (#136)<commit_after>import './ResultsListItem.css';
import React, { Component, PropTypes } from 'react';
import shallowCompare from 'react-addons-shallow-compare';
import { Link } from 'react-router';
import ago from 's-ago';
import uniq from 'lodash/uniq';
import Gravatar from 'react-gravatar';
import PackageScore from 'shared/components/package-score/PackageScore';
import PackageFlags from 'shared/components/package-flags/PackageFlags';
import Tooltip from 'shared/components/tooltip/Tooltip';
import MaterialIcon from 'shared/components/icon/MaterialIcon';
import SvgIcon from 'shared/components/icon/SvgIcon';

class ResultsListItem extends Component {
    shouldComponentUpdate(nextProps, nextState) {
        return shallowCompare(this, nextProps, nextState);
    }

    render() {
        return (

                { /* Headline */ }

                    { this.props.package.name }
                    ({ this.props.package.version })

                    <PackageScore score={ this.props.score } />

                { /* Description */ }
                { this.props.package.description ?

                        { this.props.flags ? <PackageFlags package={ this.props.package } flags={ this.props.flags } /> : '' }
                        { this.props.package.description }

 :
                    '' }

                { /* Keywords */ }
                { this._renderKeywords() }

                { /* Updated by.. */ }
                { this._renderPublisherInfo() }

                { /* Useful links */ }
                { this._renderLinks() }

        );
    }

    _renderKeywords() {
        const keywords = uniq(this.props.package.keywords);  // Remove duplicates because we use keywords as React keys
        const keywordsCount = keywords && keywords.length;

        if (!keywordsCount) {
            return '';
        }

        return (

                <MaterialIcon id="local_offer" />
                { keywords.map((keyword, index) =>

                        <Link to={ `/search?q=${encodeURIComponent(keyword)}` }>{ keyword }</Link>
                        { index < keywordsCount - 1 ? ', ' : '' }

                ) }

        );
    }

    _renderPublisherInfo() {
        const hasPublisher = !!(this.props.package.publisher && this.props.package.publisher.username);
        const hasDate = !!(this.props.package.date);

        if (!hasPublisher && !hasDate) {
            return '';
        }

        return (

                updated
                { hasDate ? { ago(new Date(this.props.package.date)) } : '' }

                { hasPublisher ?  by  : '' }
                { hasPublisher ? <a href={ `https://npmjs.com/~${encodeURIComponent(this.props.package.publisher.username)}` }
                    target="_blank" className="publisher-name">{ this.props.package.publisher.username } : '' }
                { hasPublisher ?
                    <Gravatar size={ 20 } email={ this.props.package.publisher.email || 'n/a' }
                        onLoad={ (e) => this._onGravatarLoad(e) } /> : '' }

        );
    }

    _renderLinks() {
        return (

                <Tooltip placement="top" trigger={ ['hover'] } overlay="View this package analysis">
                    <a className="analysis-link" href={ `${this.props.apiUrl}/package/${encodeURIComponent(this.props.package.name)}` }
                        target="_blank">
                        <MaterialIcon id="timeline" />

                </Tooltip>

                <Tooltip placement="top" trigger={ ['hover'] } overlay="View this package on npmjs.com">

                        <SvgIcon id={ SvgIcon.npm } />

                </Tooltip>

                <Tooltip placement="top" trigger={ ['hover'] } overlay="Try this package in RunKit">
                    <a className="runkit-link" href={ `https://runkit.com/npm/${encodeURIComponent(this.props.package.name)}` }
                        target="_blank">
                        <SvgIcon id={ SvgIcon.runkit } />

                </Tooltip>

        );
    }

    _onGravatarLoad(e) {
        e.target.style.opacity = '1';
    }
}

ResultsListItem.propTypes = {
    package: PropTypes.object.isRequired,
    flags: PropTypes.object,
    score: PropTypes.object.isRequired,
    apiUrl: PropTypes.string,
};

ResultsListItem.defaultProps = {
    apiUrl: 'https://api.npms.io',
};

export default ResultsListItem;
<|endoftext|>


<commit_before>
$(function() {
  var latlng = new google.maps.LatLng(35.0, 135.0);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  google.maps.event.addListener(map, "click", function() {
    alert("click");
  });
});
<commit_msg>エンコード処理の呼び出し処理を追加<commit_after>
$(function() {
  var latlng = new google.maps.LatLng(35.0, 135.0);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  google.maps.event.addListener(map, "click", function(e) {
    //alert("click lat:" + e.latLng.lat() + " lng:" + e.latLng.lng());
    var params = {
      lat: e.latLng.lat(),
      lng: e.latLng.lng(),
      level: 1
    }
    $.get("/api/encode", params, function(data) {
      alert("ret code:" + data.response.code);
    });
  });
});
<|endoftext|>


<commit_before>import {
  ruleTester,
  warningFreeBasics
} from "../../../testUtils"
import rule, { ruleName, messages } from ".."

const testRule = ruleTester(rule, ruleName)

testRule([
  "transform",
  "background-size",
], tr => {
  warningFreeBasics(tr)

  tr.ok("a { background-size: cover; }")
  tr.ok("a { transform: scale(1); }")
  tr.ok("a { -webkit-transform: scale(1); }")
  tr.ok("a { transform: scale(1); background-size: cover; }")
  tr.ok("a { transform: scale(1); -webkit-transform: scale(1); background-size: cover; }")

  tr.notOk("a { color: pink; }", messages.rejected("color"))
  tr.notOk("a { overflow: hidden; background-size: cover; }", messages.rejected("overflow"))
  tr.notOk("a { color: orange; -webkit-transform: scale(1); }", messages.rejected("color"))

})
<commit_msg>Add accuracy for property-whitelist<commit_after>import {
  ruleTester,
  warningFreeBasics
} from "../../../testUtils"
import rule, { ruleName, messages } from ".."

const testRule = ruleTester(rule, ruleName)

testRule([
  "transform",
  "background-size",
], tr => {
  warningFreeBasics(tr)

  tr.ok("a { background-size: cover; }")
  tr.ok("a { transform: scale(1); }")
  tr.ok("a { -webkit-transform: scale(1); }")
  tr.ok("a { transform: scale(1); background-size: cover; }")
  tr.ok("a { transform: scale(1); -webkit-transform: scale(1); background-size: cover; }")

  tr.notOk("a { color: pink; }", {
    message: messages.rejected("color"),
    line: 1,
    column: 5,
  })
  tr.notOk("a { overflow: hidden; background-size: cover; }", {
    message: messages.rejected("overflow"),
    line: 1,
    column: 5,
  })
  tr.notOk("a { color: orange; -webkit-transform: scale(1); }", {
    message: messages.rejected("color"),
    line: 1,
    column: 5,
  })

})
<|endoftext|>


<commit_before>'use strict';

var express = require('express')
	, fs = require('fs')
	, vhost = require('vhost')
	, path = require('path')

	, lib = path.join(__dirname, 'lib')

	, autoload = require( path.join(lib, 'autoload') )
	, errorHandler = require( path.join(lib, 'errorHandler') )
	, U = require( path.join(lib, 'utils'))

	, M = express()
;

M.set('port', ( process.env.PORT || 3000) );

M.set('dirs', {
	'hosts' : path.join(process.cwd(), 'hosts')
});

M.set('defaultHost', {
		development: 'http://localhost:' + M.get('port')
	, production : 'https://jaeh.at/'
} );

autoload(M);

M.on('mount', function (parent) {
	U.log('M mounted');

	M.use(errorHandler);

	M.use(function(req, res, next) {
		res.redirect(M.get('defaultHost')[M.get('env')]);
	});

	M.listen(M.get('port'), function() {
		U.log( 'M listening to port:', M.get('port') );
	});
});

module.exports = M;
<commit_msg>fixed indent<commit_after>'use strict';

var express = require('express')
  , fs = require('fs')
  , vhost = require('vhost')
  , path = require('path')

  , lib = path.join(__dirname, 'lib')

  , autoload = require( path.join(lib, 'autoload') )
  , errorHandler = require( path.join(lib, 'errorHandler') )
  , U = require( path.join(lib, 'utils'))

  , M = express()
;

M.set('port', ( process.env.PORT || 3000) );

M.set('dirs', {
  'hosts' : path.join(process.cwd(), 'hosts')
});

M.set('defaultHost', {
    development: 'http://localhost:' + M.get('port')
  , production : 'https://jaeh.at/'
} );

autoload(M);

M.on('mount', function (parent) {
  U.log('M mounted');

  M.use(errorHandler);

  M.use(function(req, res, next) {
    res.redirect(M.get('defaultHost')[M.get('env')]);
  });

  M.listen(M.get('port'), function() {
    U.log( 'M listening to port:', M.get('port') );
  });
});

module.exports = M;
<|endoftext|>


<commit_before>import assign from 'object-assign'

const _toArray = (arrayLike) => [].slice.call(arrayLike)

class DOM {
  constructor (selector) {
    let elements = document.querySelectorAll(selector)
    this.length = elements.length
    return assign(this, elements)
  }

  map (fn) {
    _toArray(this).map(el => fn.call(el, el))
    return this
  }

  each (fn) {
    _toArray(this).forEach(el => fn.call(el, el))
    return this
  }

  reduce (fn) {
    _toArray(this).forEach(el => fn.call(el, el))
    return this
  }

  addClass (classNames) {
    let classes = classNames.split(' ')
    return this.map(el => el.classList.add(...classes))
  }

  removeClass (classNames) {
    let classes = classNames.split(' ')
    return this.map(el => el.classList.add(...classes))
  }

  toggleClass (classNames) {
    let classes = classNames.split(' ')
    return this.map(el => el.classList.toggle(...classes))
  }

  hasClass (className) {
    for (let el of _toArray(this)) {
      if (el.classList.contains(className)) {
        return true
      }
    }
    return false
  }
}

window.$ = selector => new DOM(selector);
<commit_msg>add `on` to add event listeners<commit_after>import assign from 'object-assign'

const _toArray = (arrayLike) => [].slice.call(arrayLike)

class DOM {
  constructor (selector) {
    let elements = document.querySelectorAll(selector)
    this.length = elements.length
    return assign(this, elements)
  }

  map (fn) {
    _toArray(this).map(el => fn.call(el, el))
    return this
  }

  each (fn) {
    _toArray(this).forEach(el => fn.call(el, el))
    return this
  }

  reduce (fn) {
    _toArray(this).forEach(el => fn.call(el, el))
    return this
  }

  addClass (classNames) {
    let classes = classNames.split(' ')
    return this.map(el => el.classList.add(...classes))
  }

  removeClass (classNames) {
    let classes = classNames.split(' ')
    return this.map(el => el.classList.add(...classes))
  }

  toggleClass (classNames) {
    let classes = classNames.split(' ')
    return this.map(el => el.classList.toggle(...classes))
  }

  hasClass (className) {
    for (let el of _toArray(this)) {
      if (el.classList.contains(className)) {
        return true
      }
    }
    return false
  }

  on (eventNames, callback) {
    let events = eventNames.split(' ')
    events.forEach(event =>
      this.map(el => el.addEventListener(event, callback, false))
    )
    return this
  }
}

window.$ = selector => new DOM(selector);
<|endoftext|>


<commit_before>/**
 * Helpers for working with map/filter/reduce
 *
 * Should play nice with Node/RequireJS/VanillaJS
 */

/*globals module:true, define:true*/
(function(root, factory) {
    "use strict";

    root.f = factory.call({});

    if (typeof define === "function" && define.amd) {
        define(root.f.always(root.f));
    } else if (typeof module === "object" && "exports" in module) {
        module.exports = root.f;
    }
}(this, function() {
    "use strict";

    function makeArray(a) {
        return Array.prototype.slice.call(a, 0);
    }

    /**
     * Multiplies the input
     */
    function mul(a, b) {
        return Number(a) * Number(b);
    }
    this.mul = mul;

    /**
     * Adds the input
     */
    function add(a, b) {
        return Number(a) + Number(b);
    }
    this.add = add;

    /**
     * Subtracts the input
     */
    function sub(a, b) {
        return Number(a) - Number(b);
    }
    this.sub = sub;

    /**
     * Divides the input
     */
    function div(a, b) {
        return Number(a) / Number(b);
    }
    this.div = div;

    /**
     * Always returns the original input
     */
    function always(x) {
        return function () {
            return x;
        };
    }
    this.always = always;

    /**
     * Extracts the head from array/string
     */
    function head(a, until) {
        until = until || 1;
        return a.slice(0, until);
    }
    this.head = head;

    /**
     * Extracts the tail from an array/string
     */
    function tail(a, from) {
        from = from || 1;
        return a.slice(from);
    }
    this.tail = tail;

    /**
     * Returns the sign of input
     */
    function sign(n) {
        n = Number(n);
        return isNaN(n) || n === 0 ? 0 : Math.abs(n) / n;
    }
    this.sign = sign;

    /**
     * Inverts a boolean input
     */
    function inverse(b) {
        return !b;
    }
    this.inverse = inverse;

    /**
     * Returns true for an empty string/array
     */
    function empty(s) {
        return s.length === 0;
    }
    this.empty = empty;

    /**
     * Trim a string
     */
    function trim(s) {
        return s.replace(/^\s+|\s+$/g, "");
    }
    this.trim = trim;

    /**
     * Constrains a number within defined boundaries
     */
    function constrain(lower, upper) {
        return function (v) {
            return Math.min(upper, Math.max(lower, v));
        };
    }
    this.constrain = constrain;

    /**
     * Returns a property key from input
     */
    function prop(key) {
        return function (o) {
            return o[key];
        };
    }
    this.prop = prop;
    this.pluck = prop;

    /**
     * Invokes a function fn on input
     */
    function func(fn) {
        return function (o) {
            return o[fn]();
        };
    }
    this.func = func;

    /**
     * Match a value against a regex
     */
    function match(re) {
        if (! (re instanceof RegExp)) {
            re = new RegExp("^" + re + "$");
        }
        return function (v) {
            return re.test(v);
        };
    }
    this.match = match;

    /**
     * Shorthand for an inverted matcher
     */
    function omit(re) {
        return compose(inverse, match(re));
    }
    this.omit = omit;

    /**
     * Splits a string on a separator to limit parts
     * The sum of the returned parts is always the
     * original input.
     */
    function split(sep, limit) {
        limit = limit && Math.max(limit, 1) || false;
        return function (s) {
            var p = s.split(sep);
            var r = p.splice(limit);
            if (limit && r.length) {
                r.unshift(p.pop());
                p.push(r.join(sep));
            }
            return p;
        };
    }
    this.split = split;

    /**
     * Maps an array to an object
     */
    function object(keys) {
        return function (a) {
            var ret = {};
            var k = keys.slice(0);
            while (k.length > 0) {
                ret[k.shift()] = a.shift();
            }
            return ret;
        };
    }
    this.object = object;

    /**
     * Returns a partial application
     */
    function partial(ctx, fn) {
        var rest = tail(makeArray(arguments), 2);
        return function partialinner() {
            var args = rest.concat(makeArray(arguments));
            return fn.apply(ctx, args);
        };
    }
    this.partial = partial;

    /**
     * Composes a function-stack to pass a value through.
     * Evaluates right-to-left, i.e. the final returned value
     * is returned by the first argument
     */
    function compose() {
        var fstack = Array.prototype.slice.call(arguments, 0).reverse();
        return function composeinner(v) {
            var r = [v];
            fstack.forEach(function (f) {
                r = [f.apply(this, r)];
            });
            return r[0];
        };
    }
    this.compose = compose;

    return this;
}));
<commit_msg>Added first and last<commit_after>/**
 * Helpers for working with map/filter/reduce
 *
 * Should play nice with Node/RequireJS/VanillaJS
 */

/*globals module:true, define:true*/
(function(root, factory) {
    "use strict";

    root.f = factory.call({});

    if (typeof define === "function" && define.amd) {
        define(root.f.always(root.f));
    } else if (typeof module === "object" && "exports" in module) {
        module.exports = root.f;
    }
}(this, function() {
    "use strict";

    function makeArray(a) {
        return Array.prototype.slice.call(a, 0);
    }

    /**
     * Multiplies the input
     */
    function mul(a, b) {
        return Number(a) * Number(b);
    }
    this.mul = mul;

    /**
     * Adds the input
     */
    function add(a, b) {
        return Number(a) + Number(b);
    }
    this.add = add;

    /**
     * Subtracts the input
     */
    function sub(a, b) {
        return Number(a) - Number(b);
    }
    this.sub = sub;

    /**
     * Divides the input
     */
    function div(a, b) {
        return Number(a) / Number(b);
    }
    this.div = div;

    /**
     * Always returns the original input
     */
    function always(x) {
        return function () {
            return x;
        };
    }
    this.always = always;

    /**
     * Extracts the head from array/string
     */
    function head(a, until) {
        until = until || 1;
        return a.slice(0, until);
    }
    this.head = head;

    /**
     * Extracts the tail from an array/string
     */
    function tail(a, from) {
        from = from || 1;
        return a.slice(from);
    }
    this.tail = tail;

    /**
     * Returns the first element of an array
     */
    function first(a) {
        return a[0];
    }
    this.first = first;

    /**
     * Returns the last element of an array
     */
    function last(a) {
        return a[a.length -1];
    }
    this.last = last;

    /**
     * Returns the sign of input
     */
    function sign(n) {
        n = Number(n);
        return isNaN(n) || n === 0 ? 0 : Math.abs(n) / n;
    }
    this.sign = sign;

    /**
     * Inverts a boolean input
     */
    function inverse(b) {
        return !b;
    }
    this.inverse = inverse;

    /**
     * Returns true for an empty string/array
     */
    function empty(s) {
        return s.length === 0;
    }
    this.empty = empty;

    /**
     * Trim a string
     */
    function trim(s) {
        return s.replace(/^\s+|\s+$/g, "");
    }
    this.trim = trim;

    /**
     * Constrains a number within defined boundaries
     */
    function constrain(lower, upper) {
        return function (v) {
            return Math.min(upper, Math.max(lower, v));
        };
    }
    this.constrain = constrain;

    /**
     * Returns a property key from input
     */
    function prop(key) {
        return function (o) {
            return o[key];
        };
    }
    this.prop = prop;
    this.pluck = prop;

    /**
     * Invokes a function fn on input
     */
    function func(fn) {
        return function (o) {
            return o[fn]();
        };
    }
    this.func = func;

    /**
     * Match a value against a regex
     */
    function match(re) {
        if (! (re instanceof RegExp)) {
            re = new RegExp("^" + re + "$");
        }
        return function (v) {
            return re.test(v);
        };
    }
    this.match = match;

    /**
     * Shorthand for an inverted matcher
     */
    function omit(re) {
        return compose(inverse, match(re));
    }
    this.omit = omit;

    /**
     * Splits a string on a separator to limit parts
     * The sum of the returned parts is always the
     * original input.
     */
    function split(sep, limit) {
        limit = limit && Math.max(limit, 1) || false;
        return function (s) {
            var p = s.split(sep);
            var r = p.splice(limit);
            if (limit && r.length) {
                r.unshift(p.pop());
                p.push(r.join(sep));
            }
            return p;
        };
    }
    this.split = split;

    /**
     * Maps an array to an object
     */
    function object(keys) {
        return function (a) {
            var ret = {};
            var k = keys.slice(0);
            while (k.length > 0) {
                ret[k.shift()] = a.shift();
            }
            return ret;
        };
    }
    this.object = object;

    /**
     * Returns a partial application
     */
    function partial(ctx, fn) {
        var rest = tail(makeArray(arguments), 2);
        return function partialinner() {
            var args = rest.concat(makeArray(arguments));
            return fn.apply(ctx, args);
        };
    }
    this.partial = partial;

    /**
     * Composes a function-stack to pass a value through.
     * Evaluates right-to-left, i.e. the final returned value
     * is returned by the first argument
     */
    function compose() {
        var fstack = Array.prototype.slice.call(arguments, 0).reverse();
        return function composeinner(v) {
            var r = [v];
            fstack.forEach(function (f) {
                r = [f.apply(this, r)];
            });
            return r[0];
        };
    }
    this.compose = compose;

    return this;
}));
<|endoftext|>


<commit_before>/* Le namespace "iJS"(pour "inside JS") initié ici est une mini bibliothèque pour le développement en JavaScript des projets associés.
 * En effet s'il est une chose que JQuery ne fais pas c'est le respect de la syntaxe JavaScript; ce qui constitue un problème lorsque après avoir appris le JavaScript,
 *il ne suffit plus seulement de connaître les fonctionnalités qu'apporte JQuery (ce qui se doit normalement d'être suffisant) mais aussi sa syntaxe à elle.
 * "iJS" tout comme "Dojo" s'oriente avant tout dans le respect de la syntaxe; sauf que seules sont récrites les fonctionnalités JS trop verbeux ou difficile d'utilisation.
 *
 * Ce namespace constitue un ensemble de petites fonctionnalités permettant de faciliter le développement en JavaScript.
 *
 * @license: GPL v3.0
 * @author : Tindo Ngoufo Arsel
 * @version: 0.0_(15.04)
*/

var iJS = {

    isNumber : function( arg ){

        if( (typeof arg).toLowerCase() === "number" || arg instanceof Number )
            return true ;
        else
            return false ;
    } ,

    isBoolean : function( arg ){

        if( (typeof arg).toLowerCase() === "boolean" || arg instanceof Boolean )
            return true ;
        else
            return false ;
    } ,

    isString : function( arg ){

        if( (typeof arg).toLowerCase() === "string" || arg instanceof String )
            return true ;
        else
            return false ;
    } ,

    isArray : function( arg ){

        if( arg instanceof Array )
            return true ;
        else
            return false ;
    } ,

    isHTMLElement : function( arg ){

        if( arg instanceof HTMLElement )
            return true ;
        else
            return false ;
    } ,

    isHTMLImageElement : function( arg ){

        if( arg instanceof HTMLImageElement )
            return true ;
        else
            return false ;
    } ,

    isObject : function( arg ){

        if( (typeof arg).toLowerCase() === "object" )
            return true ;
        else
            return false ;
    } ,

    /* permet de changer les images pour l'animations des chargements (simuler un "loader")
	 *
	 *"imgContainer" représente soit l'id d'un élément "img", soit un élément "img" proprement dit.
	 *"imgDir" représente le chemin du répertoire contenant les images à animer
	 *"imgLength" représente le nombre d'image à animer
	 *"imgGlobalName" représente le nom global des images à animer. En effet les images à animer
	 doivent être de la forme 'imglaod0.png', 'imglaod1.png', ... où 'imgload' est ici le nom globlal
	*"imgFormat" est le format des images à animer. Par défaut (ou s'il n'est pas renseigner) c'est 'png'.
	*/
    mi_loader : function(imgContainer, imgDir, imgLength, imgGlobalName, imgFormat ){

        if( iJS.isString( imgDir ) )
            this.imgDir = imgDir ;
        if( iJS.isNumber( imgLength ) )
            this.imgLength = imgLength ;
        if( iJS.isString( imgGlobalName ) )
            this.imgGlobalName = imgGlobalName ;

        this.imgFormat = ( iJS.isString(imgFormat) ) ? imgFormat : "png" ;

        if( iJS.isString( imgContainer ) )
            if( iJS.isHTMLImageElement( document.getElementById( imgContainer ) ) )
                this.imgContainer = document.getElementById( imgContainer ) ;
            else if( iJS.isHTMLImageElement( imgContainer ) )
                this.imgContainer = imgContainer ;

        this.imgIndex = 0 ; //représente le numéro de l'image à afficher
        this.imgPath = "" ; //représente le chemin vers l'image à afficher
        this.loaderID =0 ; //puisque clearInterval pourra être utilisées

        /*la fonction ci-dessous permet de changer ou remplacer l'image affichée par la suivante.
			 *le paramètre "loader" n'est nécessaire lorsque la fonction est passer en paramètre à une autre.
			 *en effet il fera le plus souvent référence à l'objet lui même (au "this").
			 *sauf que cela ne marche plus pour une utilisation dans une fonction externe à l'objet
			 *puis que, en prenant l'exemple de "setInterval" rattachée à l'objet "window"
			 *le "this" fera référence à l'objet "window" et non à l'objet voulu.
			 *en ce moment là faudra faire setIinterval( obj.changeIMGLoader, time, obj).
			*/
        this.changeIMGLoader = function( loader ){

            //ld = loader ou this ( l'objet lui même)
            var ld = ( loader instanceof iJS.mi_loader ) ? loader : this ;

            if( ld.imgDir && ld.imgLength && ld.imgGlobalName)
                if( ld.imgIndex < ld.imgLength )
                {
                    ld.imgPath = ld.imgDir + "/" + ld.imgGlobalName + ld.imgIndex + "." + ld.imgFormat ;
                    ld.imgIndex++ ;
                }
                else
                {
                    ld.imgIndex = 0 ;
                }

            if(  ld.imgContainer )
                ld.imgContainer.src = ld.imgPath ;
        }

        /*permet de lancer l'animation ( par remplacement successif d'image
			 *suivant une intervalle de temps défini par "timeInterval"
			 *par défaut l'intervalle de temps est de 150ms
			*/
        this.startLoading = function( timeInterval ){

            if( this.loaderID )//alors faut d'abord stopper l'animation encours
                this.stopLoading() ;

            if( iJS.isNumber( timeInterval ) )
                this.loaderID = setInterval( this.changeIMGLoader, timeInterval, this )
                else{
                    this.loaderID = setInterval( this.changeIMGLoader, 150, this ) ;
                }

        }

        /*permet de stopper l'animation; soit immédiatement, soit après un un certain temps défini ici par "time"*/
        this.stopLoading = function( time ){

            if( iJS.isNumber( time ) )
            {
                setTimeout( function( loader ){
                    if(loader instanceof iJS.mi_loader)
                    {
                        clearInterval( loader.loaderID );
                        loader.imgIndex=0;
                        loader.loaderID = 0 ;
                        loader.changeIMGLoader();
                    }
                }, time, this
                          ) ;
            }
            else
            {
                clearInterval( this.loaderID );
                this.imgIndex=0;
                this.loaderID = 0 ;
                this.changeIMGLoader() ;
            }

        }
    }

} <commit_msg>use of Brackets-beautify<commit_after>/* Le namespace "iJS"(pour "inside JS") initié ici est une mini bibliothèque pour le développement en JavaScript des projets associés.
 * En effet s'il est une chose que JQuery ne fais pas c'est le respect de la syntaxe JavaScript; ce qui constitue un problème lorsque après avoir appris le JavaScript,
 *il ne suffit plus seulement de connaître les fonctionnalités qu'apporte JQuery (ce qui se doit normalement d'être suffisant) mais aussi sa syntaxe à elle.
 * "iJS" tout comme "Dojo" s'oriente avant tout dans le respect de la syntaxe; sauf que seules sont récrites les fonctionnalités JS trop verbeux ou difficile d'utilisation.
 *
 * Ce namespace constitue un ensemble de petites fonctionnalités permettant de faciliter le développement en JavaScript.
 *
 * @license: GPL v3.0
 * @author : Tindo Ngoufo Arsel
 * @version: 0.0_(15.04)
 */

var iJS = {

    isNumber: function (arg) {

        if ((typeof arg).toLowerCase() === "number" || arg instanceof Number)
            return true;
        else
            return false;
    },

    isBoolean: function (arg) {

        if ((typeof arg).toLowerCase() === "boolean" || arg instanceof Boolean)
            return true;
        else
            return false;
    },

    isString: function (arg) {

        if ((typeof arg).toLowerCase() === "string" || arg instanceof String)
            return true;
        else
            return false;
    },

    isArray: function (arg) {

        if (arg instanceof Array)
            return true;
        else
            return false;
    },

    isHTMLElement: function (arg) {

        if (arg instanceof HTMLElement)
            return true;
        else
            return false;
    },

    isHTMLImageElement: function (arg) {

        if (arg instanceof HTMLImageElement)
            return true;
        else
            return false;
    },

    isObject: function (arg) {

        if ((typeof arg).toLowerCase() === "object")
            return true;
        else
            return false;
    },

    /* permet de changer les images pour l'animations des chargements (simuler un "loader")
	 *
	 *"imgContainer" représente soit l'id d'un élément "img", soit un élément "img" proprement dit.
	 *"imgDir" représente le chemin du répertoire contenant les images à animer
	 *"imgLength" représente le nombre d'image à animer
	 *"imgGlobalName" représente le nom global des images à animer. En effet les images à animer
	 doivent être de la forme 'imglaod0.png', 'imglaod1.png', ... où 'imgload' est ici le nom globlal
	*"imgFormat" est le format des images à animer. Par défaut (ou s'il n'est pas renseigner) c'est 'png'.
	*/
    mi_loader: function (imgContainer, imgDir, imgLength, imgGlobalName, imgFormat) {

        if (iJS.isString(imgDir))
            this.imgDir = imgDir;
        if (iJS.isNumber(imgLength))
            this.imgLength = imgLength;
        if (iJS.isString(imgGlobalName))
            this.imgGlobalName = imgGlobalName;

        this.imgFormat = (iJS.isString(imgFormat)) ? imgFormat : "png";

        if (iJS.isString(imgContainer))
            if (iJS.isHTMLImageElement(document.getElementById(imgContainer)))
                this.imgContainer = document.getElementById(imgContainer);
            else if (iJS.isHTMLImageElement(imgContainer))
            this.imgContainer = imgContainer;

        this.imgIndex = 0; //représente le numéro de l'image à afficher
        this.imgPath = ""; //représente le chemin vers l'image à afficher
        this.loaderID = 0; //puisque clearInterval pourra être utilisées

        /*la fonction ci-dessous permet de changer ou remplacer l'image affichée par la suivante.
         *le paramètre "loader" n'est nécessaire lorsque la fonction est passer en paramètre à une autre.
         *en effet il fera le plus souvent référence à l'objet lui même (au "this").
         *sauf que cela ne marche plus pour une utilisation dans une fonction externe à l'objet
         *puis que, en prenant l'exemple de "setInterval" rattachée à l'objet "window"
         *le "this" fera référence à l'objet "window" et non à l'objet voulu.
         *en ce moment là faudra faire setIinterval( obj.changeIMGLoader, time, obj).
         */
        this.changeIMGLoader = function (loader) {

            //ld = loader ou this ( l'objet lui même)
            var ld = (loader instanceof iJS.mi_loader) ? loader : this;

            if (ld.imgDir && ld.imgLength && ld.imgGlobalName)
                if (ld.imgIndex < ld.imgLength) {
                    ld.imgPath = ld.imgDir + "/" + ld.imgGlobalName + ld.imgIndex + "." + ld.imgFormat;
                    ld.imgIndex++;
                } else {
                    ld.imgIndex = 0;
                }

            if (ld.imgContainer)
                ld.imgContainer.src = ld.imgPath;
        }

        /*permet de lancer l'animation ( par remplacement successif d'image
         *suivant une intervalle de temps défini par "timeInterval"
         *par défaut l'intervalle de temps est de 150ms
         */
        this.startLoading = function (timeInterval) {

            if (this.loaderID) //alors faut d'abord stopper l'animation encours
                this.stopLoading();

            if (iJS.isNumber(timeInterval))
                this.loaderID = setInterval(this.changeIMGLoader, timeInterval, this)
            else {
                this.loaderID = setInterval(this.changeIMGLoader, 150, this);
            }

        }

        /*permet de stopper l'animation; soit immédiatement, soit après un un certain temps défini ici par "time"*/
        this.stopLoading = function (time) {

            if (iJS.isNumber(time)) {
                setTimeout(function (loader) {
                    if (loader instanceof iJS.mi_loader) {
                        clearInterval(loader.loaderID);
                        loader.imgIndex = 0;
                        loader.loaderID = 0;
                        loader.changeIMGLoader();
                    }
                }, time, this);
            } else {
                clearInterval(this.loaderID);
                this.imgIndex = 0;
                this.loaderID = 0;
                this.changeIMGLoader();
            }

        }
    }

}<|endoftext|>


<commit_before>/*jshint strict: false */
/*global setTimeout */

/*jshint -W098 */
var p = (function () {
  /*jshint +W098 */

  var task = setTimeout;

  function isFunction(value) {
    return typeof value === 'function';
  }

  function resolutionProcedure(promise, x, resolve, reject) {
    if (promise === x) {
      throw TypeError();
    }
    if ((x && typeof x === 'object') || isFunction(x)) {
      var called = 0;
      try {
        var then = x.then;
        if (isFunction(then)) {
          then.call(x, function (y) {
            if (called) {
              return;
            }
            called = 1;
            resolutionProcedure(promise, y, resolve, reject);
          }, function (r) {
            if (called) {
              return;
            }
            called = 1;
            reject(r);
          });
        } else {
          resolve(x);
        }
      } catch (e) {
        if (!called) {
          reject(e);
        }
      }
    } else {
      resolve(x);
    }
  }

  var FULFILLED = 1;
  var REJECTED = 2;

  function defer() {
    var state;
    var valueOrReason;
    var queue = [];
    function emptyQueue(offset, iteratee) {
      /*jshint loopfunc: true */
      var item;
      while ((item = queue.shift())) {
        (function (callback, promise, resolve, reject) {
          task(function () {
            iteratee(callback, promise, resolve, reject);
          });
        }(item[offset], item[2], item[3], item[4]));
      }
    }
    function callOnFulfilleds() {
      emptyQueue(0, function (onFulfilled, promise, resolve, reject) {
        try {
          var x = isFunction(onFulfilled) ? onFulfilled(valueOrReason) : valueOrReason;
          resolutionProcedure(promise, x, resolve, reject);
        } catch (e) {
          reject(e);
        }
      });
    }
    function callOnRejecteds() {
      emptyQueue(1, function (onRejected, promise, resolve, reject) {
        try {
          if (isFunction(onRejected)) {
            var x = onRejected(valueOrReason);
            resolutionProcedure(promise, x, resolve, reject);
          } else {
            reject(valueOrReason);
          }
        } catch (e) {
          reject(e);
        }
      });
    }
    function promiseThen(onFulfilled, onRejected) {
      var deferred = defer();
      queue.push([
        onFulfilled,
        onRejected,
        deferred.promise,
        deferred.resolve,
        deferred.reject
      ]);
      if (state === FULFILLED) {
        callOnFulfilleds();
      }
      if (state === REJECTED) {
        callOnRejecteds();
      }
      return deferred.promise;
    }
    function promiseCatch(onRejected) {
      return promiseThen(0, onRejected);
    }
    return {
      promise: {
        then: promiseThen,
        'catch': promiseCatch // Quotes for old IE
      },
      resolve: function (value) {
        if (state) {
          return;
        }
        state = FULFILLED;
        valueOrReason = value;
        callOnFulfilleds();
      },
      reject: function (reason) {
        if (state) {
          return;
        }
        state = REJECTED;
        valueOrReason = reason;
        callOnRejecteds();
      }
    };
  }

  return {
    defer: defer,
    resolve: function (value) {
      var deferred = defer();
      deferred.resolve(value);
      return deferred.promise;
    },
    reject: function (reason) {
      var deferred = defer();
      deferred.reject(reason);
      return deferred.promise;
    }
  };

}());
<commit_msg>Add all and props.<commit_after>/*jshint strict: false */
/*global setTimeout */

/*jshint -W098 */
var p = (function () {
  /*jshint +W098 */

  var task = setTimeout;

  function isFunction(value) {
    return typeof value === 'function';
  }

  function resolutionProcedure(promise, x, resolve, reject) {
    if (promise === x) {
      throw TypeError();
    }
    if ((x && typeof x === 'object') || isFunction(x)) {
      var called = 0;
      try {
        var then = x.then;
        if (isFunction(then)) {
          then.call(x, function (y) {
            if (called) {
              return;
            }
            called = 1;
            resolutionProcedure(promise, y, resolve, reject);
          }, function (r) {
            if (called) {
              return;
            }
            called = 1;
            reject(r);
          });
        } else {
          resolve(x);
        }
      } catch (e) {
        if (!called) {
          reject(e);
        }
      }
    } else {
      resolve(x);
    }
  }

  var FULFILLED = 1;
  var REJECTED = 2;

  function defer() {
    var state;
    var valueOrReason;
    var queue = [];
    function emptyQueue(offset, iteratee) {
      /*jshint loopfunc: true */
      var item;
      while ((item = queue.shift())) {
        (function (callback, promise, resolve, reject) {
          task(function () {
            iteratee(callback, promise, resolve, reject);
          });
        }(item[offset], item[2], item[3], item[4]));
      }
    }
    function callOnFulfilleds() {
      emptyQueue(0, function (onFulfilled, promise, resolve, reject) {
        try {
          var x = isFunction(onFulfilled) ? onFulfilled(valueOrReason) : valueOrReason;
          resolutionProcedure(promise, x, resolve, reject);
        } catch (e) {
          reject(e);
        }
      });
    }
    function callOnRejecteds() {
      emptyQueue(1, function (onRejected, promise, resolve, reject) {
        try {
          if (isFunction(onRejected)) {
            var x = onRejected(valueOrReason);
            resolutionProcedure(promise, x, resolve, reject);
          } else {
            reject(valueOrReason);
          }
        } catch (e) {
          reject(e);
        }
      });
    }
    function promiseThen(onFulfilled, onRejected) {
      var deferred = defer();
      queue.push([
        onFulfilled,
        onRejected,
        deferred.promise,
        deferred.resolve,
        deferred.reject
      ]);
      if (state === FULFILLED) {
        callOnFulfilleds();
      }
      if (state === REJECTED) {
        callOnRejecteds();
      }
      return deferred.promise;
    }
    function promiseCatch(onRejected) {
      return promiseThen(0, onRejected);
    }
    return {
      promise: {
        then: promiseThen,
        'catch': promiseCatch // Quotes for old IE
      },
      resolve: function (value) {
        if (state) {
          return;
        }
        state = FULFILLED;
        valueOrReason = value;
        callOnFulfilleds();
      },
      reject: function (reason) {
        if (state) {
          return;
        }
        state = REJECTED;
        valueOrReason = reason;
        callOnRejecteds();
      }
    };
  }

  function resolve(value) {
    var deferred = defer();
    resolutionProcedure(deferred.promise, value, deferred.resolve, deferred.reject);
    return deferred.promise;
  }

  return {
    defer: defer,
    resolve: resolve,
    reject: function (reason) {
      var deferred = defer();
      deferred.reject(reason);
      return deferred.promise;
    },
    all: function (array) {
      /*jshint loopfunc: true */
      var deferred = defer();
      var resolvedValues = [];
      var resolvedCount = 0;
      var length = array.length;
      for (var i = 0; i < length; i += 1) {
        (function (i) {
          resolve(array[i]).then(function (value) {
            resolvedValues[i] = value;
            resolvedCount += 1;
            if (resolvedCount === length) {
              deferred.resolve(resolvedValues);
            }
          }, deferred.reject);
        }(i));
      }
      return deferred.promise;
    },
    props: function (object) {
      /*jshint loopfunc: true */
      var deferred = defer();
      var resolvedValues = {};
      var resolvedCount = 0;
      var length = 0;
      for (var key in object) {
        if ({}.hasOwnProperty.call(object, key)) {
          length += 1;
          (function (key) {
            resolve(object[key]).then(function (value) {
              resolvedValues[key] = value;
              resolvedCount += 1;
              if (resolvedCount === length) {
                deferred.resolve(resolvedValues);
              }
            }, deferred.reject);
          }(key));
        }
      }
      return deferred.promise;
    }
  };

}());
<|endoftext|>


<commit_before>var express    = require('express'),
    fs   = require('fs'),
    path = require('path'),
    app  = express(),
    file = 'public/file.txt',
    pipe = require('pipe-io');

app.get('/', function(req, res) {
  var readStream = fs.createReadStream('public/index.html');
  pipe([readStream, res], function (error) {
    console.log(error || 'sent');
    if (error)
      res.status(error.status).end();
    else
      res.status(200).end();
  });
});

app.get('/file', function (req, res) {
  var readStream = fs.createReadStream(file);
  pipe([readStream, res], function (error) {
    console.log(error || 'done');
    if (error)
      res.status(error.status).end();
    else
      res.status(200).end();
  });
});

app.put('/file', function (req, res) {
  pipe([req, fs.createWriteStream(file, {'flags': 'a'})], function (error) {
    console.log(error || 'done');
    if (error)
      res.status(error.status).end();
    else
      res.status(200).end();
  });
});

console.log('Server is listening 3000 port. Enjoy :).')
app.listen(3000);<commit_msg>rm unnecessary status before successful res.end()<commit_after>var express    = require('express'),
    fs   = require('fs'),
    path = require('path'),
    app  = express(),
    file = 'public/file.txt',
    pipe = require('pipe-io');

app.get('/', function(req, res) {
  var readStream = fs.createReadStream('public/index.html');
  pipe([readStream, res], function (error) {
    console.log(error || 'sent');
    if (error)
      res.status(error.status).end();
    else
      res.end();
  });
});

app.get('/file', function (req, res) {
  var readStream = fs.createReadStream(file);
  pipe([readStream, res], function (error) {
    console.log(error || 'done');
    if (error)
      res.status(error.status).end();
    else
      res.end();
  });
});

app.put('/file', function (req, res) {
  pipe([req, fs.createWriteStream(file, {'flags': 'a'})], function (error) {
    console.log(error || 'done');
    if (error)
      res.status(error.status).end();
    else
      res.end();
  });
});

console.log('Server is listening 3000 port. Enjoy :).')
app.listen(3000);<|endoftext|>