<commit_before>(function(){
  function SwaggerType(type, format){
    this.type   = type;
    this.format = format;
  }

  var SwaggerTypes = {
    'integer'   : new SwaggerType('integer' , 'int32'   ),
    'long'      : new SwaggerType('integer' , 'int64'   ),
    'float'     : new SwaggerType('number'  , 'float'   ),
    'double'    : new SwaggerType('number'  , 'double'  ),
    'string'    : new SwaggerType('string'  , undefined ),
    'byte'      : new SwaggerType('string'  , 'byte'    ),
    'boolean'   : new SwaggerType('boolean' , undefined ),
    'date'      : new SwaggerType('string'  , 'date'    ),
    'dateTime'  : new SwaggerType('string'  , 'date-time'),
    'password'  : new SwaggerType('string'  , 'password'),
    // The follwing types are not defined in Swagger schema
    'decimal'   : new SwaggerType('number'  , 'decimal' ),
    'short'     : new SwaggerType('number'  , 'int16'   ),
    'guid'      : new SwaggerType('string'  , 'guid'    ),
    'dateTimeOffset'      : new SwaggerType('string'  , 'dateTimeOffset'    ),
    'duration'  : new SwaggerType('string'  , 'duration'),
  };

  var typeMap = {
      'Binary'  : undefined,
      'Boolean' : SwaggerTypes.boolean,
      'Byte'    : SwaggerTypes.byte,
      'Date'    : SwaggerTypes.date,
      'DateTimeOffset': SwaggerTypes.dateTimeOffset,
      'Decimal' : SwaggerTypes.decimal,
      'Double'  : SwaggerTypes.double,
      'Duration': SwaggerTypes.duration,
      'Guid'    : SwaggerTypes.guid,
      'Int16'   : SwaggerTypes.short,
      'Int32'   : SwaggerTypes.integer,
      'Int64'   : SwaggerTypes.long,
      // 'SByte'   : 'Edm.SByte',
      'Single'  : SwaggerTypes.float,
      // 'Stream': 'Edm.Stream',
      'String'  : SwaggerTypes.string,
      // 'TimeOfDay': 'Edm.TimeOfDay',
    };

  function getSwaggerType(type, isCollection){
    var sType = type === undefined  ?
                SwaggerTypes.string :
                typeMap[type];

    if(!sType){
      if(type.length>4 && type.slice(0,4) === 'edm.'){
        sType = new SwaggerType('string', type);
      }else{
        sType = {'$ref': '#/definitions/' + type};
      }
    }

    return isCollection ? {'type' : 'array', 'items' : sType } : sType;
  }

  function addPaths(model, resolveKey)
  {
    function getSchema(type, isCollection){
      var sref= { '$ref': '#/definitions/' + type };
      return isCollection ? {'type'  : 'array', 'items' : sref} : sref;
    }

    function routeGet(name, type, isCollection, swKey){
      var route = {
        'tags'        : [ type ],
        'description' : isCollection ?
            'Returns all items from ' + name + '.' :
            swKey ?
              'Returns a single item from ' + name + '.' :
              'Returns ' + name + '.',
        'responses':{
          '200' : {
            'description' : isCollection ?
              'An array of ' + type + ' items.' :
              'A single ' + type + ' item.',
            'schema' : getSchema(type, isCollection)
          }
        }
      };

      if (swKey){
        route.parameters = [
          {
            'name'        : swKey.name,
            'in'          : 'path',
            'description' : 'The key.',
            'required'    : true,
            'type'        : swKey.type,
            'format'      : swKey.format
          }
        ];
      }

      return route;
    }

    function routePost(name, type){
      var singleSchema = getSchema(type, false);
      return {
        'tags'        : [ type ],
        'description' : 'Adds a new ' + type + ' to ' + name + '.',
        'parameters'  : [
          {
            'name'        : type,
            'in'          : 'body',
            'description' : 'The new ' + type + ' item.',
            'required'    : true,
            'schema'      : singleSchema
          }
        ],
        'responses': {
          '201': {
            'description' : 'The newly added ' + type + ' item.',
            'schema'      : singleSchema
          },
        }
      };
    }

    function routePut(name, type, swKey){
      var route = {
        'tags'        : [ type ],
        'description' : swKey ?
          'Update an existing ' + type + ' item.' :
          'Update ' + name + '.',
        'parameters'  : [
          {
            'name'        : type,
            'in'          : 'body',
            'description' : 'The new ' + type + ' item.',
            'required'    : true,
            'schema'      : getSchema(type, false)
          },
          {
            'name': 'If-Match',
            'in': 'header',
            'description': 'If-Match header.',
            'type': 'string'
          }
        ],
        'responses': {
          '204': {
            'description' : 'Successful.'
          },
        }
      };

      if(swKey){
        route.parameters.unshift({
            'name'        : swKey.name,
            'in'          : 'path',
            'description' : 'The key.',
            'required'    : true,
            'type'        : swKey.type,
            'format'      : swKey.format
          });
      }

      return route;
    }

    function routeDelete(name, type, swKey){
      return {
        'tags'        : [ type ],
        'description' : 'Delete an item from ' + name + '.',
        'parameters'  : [
          {
            'name'        : swKey.name,
            'in'          : 'path',
            'description' : 'The key.',
            'required'    : true,
            'type'        : swKey.type,
            'format'      : swKey.format
          },
          {
            'name': 'If-Match',
            'in': 'header',
            'description': 'If-Match header.',
            'type': 'string'
          }
        ],
        'responses': {
          '204': {
            'description' : 'Successful.'
          },
        }
      };
    }

    function genAllows(allows){
      if(!allows) return {'read' : true};

      var ac = {};
      for(var i = 0; i < allows.length; i++){
        ac[allows[i]] = true;
      }

      return ac;
    }

    if(!model.container) return;

    var paths= {};
    var visitor   = new Visitor();

    visitor.visitObj(model.container,{
      'entitysets'  : function(arr){
        visitor.visitArr(arr, function(item){
          var allows = genAllows(item.allows);
          var routes = {};
          if(allows.read) routes.get = routeGet(item.name, item.type, true);
          if(allows.create) routes.post = routePost(item.name, item.type);
          paths['/' + item.name] = routes;

          var swKey = resolveKey(item.type);
          if(swKey){
            var sRoutes = {};
            if(allows.read) sRoutes.get = routeGet(item.name, item.type, false, swKey) ;
            if(allows.update) sRoutes.put = routePut(item.name, item.type, swKey);
            if(allows.delete) sRoutes.delete = routeDelete(item.name, item.type, swKey);
            paths['/' + item.name + '/{' + swKey.name + '}' ] = sRoutes;
          }
        });
      },
      'singletons'  : function(arr){
        visitor.visitArr(arr, function(item){
          var allows = genAllows(item.allows);
          var routes = {};
          if(allows.read) routes.get = routeGet(item.name, item.type, false);
          if(allows.update) routes.put = routePut(item.name, item.type);
          paths['/' + item.name] = routes;
        });
      },
    });

    return paths;
  }

  Morpho.registerTo('swagger', function (model, errors, option){
    var visitor   = this.getVisitor();
    var state     = {
      'swagger'   : '2.0',
      'info'      : {
        'title'   : 'Demo',
        'version' : '0.1'
      },
      'paths'     : {}
    };

    var keys = {};

    visitor.visitObj(model, {
        'types'   : function(arr){
          state.definitions = {};
          this.visitArr(arr, function(item){
            var type = {properties:{}};
            var keyProperty = null;
            visitor.visitArr(item.properties, function(item){
              var swType = getSwaggerType(item.type, item.isCollection);
              var propertyType;
              if(swType.type){
                propertyType = { type: swType.type };
                if(swType.format) propertyType.format = swType.format;
                if(swType.items) propertyType.items = swType.items;
              }else{
                propertyType = swType;
              }

              type.properties[item.name] = propertyType;

              if(!keyProperty && item.isKey){
                keyProperty = {
                  'name'  : item.name,
                  'type'  : swType.type,
                  'format': swType.format
                };
              }
            });

            if(keyProperty){
              keys[item.name] = keyProperty;
            }

            state.definitions[item.name] = type;
          });
        }
      });

    state.paths = addPaths(model, function(type){
      return keys[type];
    });

    if(option.returnJSON){
      return state;
    }else if(option.format){
      return JSON.stringify(state, null, 2);
    }

    return JSON.stringify(state);
  });
})();
<commit_msg>Fix undefined format.<commit_after>(function(){
  function SwaggerType(type, format){
    this.type   = type;
    if(format) this.format = format;
  }

  var SwaggerTypes = {
    'integer'   : new SwaggerType('integer' , 'int32'   ),
    'long'      : new SwaggerType('integer' , 'int64'   ),
    'float'     : new SwaggerType('number'  , 'float'   ),
    'double'    : new SwaggerType('number'  , 'double'  ),
    'string'    : new SwaggerType('string'  , undefined ),
    'byte'      : new SwaggerType('string'  , 'byte'    ),
    'boolean'   : new SwaggerType('boolean' , undefined ),
    'date'      : new SwaggerType('string'  , 'date'    ),
    'dateTime'  : new SwaggerType('string'  , 'date-time'),
    'password'  : new SwaggerType('string'  , 'password'),
    // The follwing types are not defined in Swagger schema
    'decimal'   : new SwaggerType('number'  , 'decimal' ),
    'short'     : new SwaggerType('number'  , 'int16'   ),
    'guid'      : new SwaggerType('string'  , 'guid'    ),
    'dateTimeOffset'      : new SwaggerType('string'  , 'dateTimeOffset'    ),
    'duration'  : new SwaggerType('string'  , 'duration'),
  };

  var typeMap = {
      'Binary'  : undefined,
      'Boolean' : SwaggerTypes.boolean,
      'Byte'    : SwaggerTypes.byte,
      'Date'    : SwaggerTypes.date,
      'DateTimeOffset': SwaggerTypes.dateTimeOffset,
      'Decimal' : SwaggerTypes.decimal,
      'Double'  : SwaggerTypes.double,
      'Duration': SwaggerTypes.duration,
      'Guid'    : SwaggerTypes.guid,
      'Int16'   : SwaggerTypes.short,
      'Int32'   : SwaggerTypes.integer,
      'Int64'   : SwaggerTypes.long,
      // 'SByte'   : 'Edm.SByte',
      'Single'  : SwaggerTypes.float,
      // 'Stream': 'Edm.Stream',
      'String'  : SwaggerTypes.string,
      // 'TimeOfDay': 'Edm.TimeOfDay',
    };

  function getSwaggerType(type, isCollection){
    var sType = type === undefined  ?
                SwaggerTypes.string :
                typeMap[type];

    if(!sType){
      if(type.length>4 && type.slice(0,4) === 'edm.'){
        sType = new SwaggerType('string', type);
      }else{
        sType = {'$ref': '#/definitions/' + type};
      }
    }

    return isCollection ? {'type' : 'array', 'items' : sType } : sType;
  }

  function addPaths(model, resolveKey)
  {
    function getSchema(type, isCollection){
      var sref= { '$ref': '#/definitions/' + type };
      return isCollection ? {'type'  : 'array', 'items' : sref} : sref;
    }

    function routeGet(name, type, isCollection, swKey){
      var route = {
        'tags'        : [ type ],
        'description' : isCollection ?
            'Returns all items from ' + name + '.' :
            swKey ?
              'Returns a single item from ' + name + '.' :
              'Returns ' + name + '.',
        'responses':{
          '200' : {
            'description' : isCollection ?
              'An array of ' + type + ' items.' :
              'A single ' + type + ' item.',
            'schema' : getSchema(type, isCollection)
          }
        }
      };

      if (swKey){
        var parameter =
        {
            'name'        : swKey.name,
            'in'          : 'path',
            'description' : 'The key.',
            'required'    : true,
            'type'        : swKey.type,
        };
        if(swKey.format) parameter.format = swKey.format;

        route.parameters = [ parameter ];
      }

      return route;
    }

    function routePost(name, type){
      var singleSchema = getSchema(type, false);
      return {
        'tags'        : [ type ],
        'description' : 'Adds a new ' + type + ' to ' + name + '.',
        'parameters'  : [
          {
            'name'        : type,
            'in'          : 'body',
            'description' : 'The new ' + type + ' item.',
            'required'    : true,
            'schema'      : singleSchema
          }
        ],
        'responses': {
          '201': {
            'description' : 'The newly added ' + type + ' item.',
            'schema'      : singleSchema
          },
        }
      };
    }

    function routePut(name, type, swKey){
      var route = {
        'tags'        : [ type ],
        'description' : swKey ?
          'Update an existing ' + type + ' item.' :
          'Update ' + name + '.',
        'parameters'  : [
          {
            'name'        : type,
            'in'          : 'body',
            'description' : 'The new ' + type + ' item.',
            'required'    : true,
            'schema'      : getSchema(type, false)
          },
          {
            'name': 'If-Match',
            'in': 'header',
            'description': 'If-Match header.',
            'type': 'string'
          }
        ],
        'responses': {
          '204': {
            'description' : 'Successful.'
          },
        }
      };

      if(swKey){
        var parameter = {
          'name'        : swKey.name,
          'in'          : 'path',
          'description' : 'The key.',
          'required'    : true,
          'type'        : swKey.type,
        };

        if(swKey.format) parameter.format = swKey.format;
        route.parameters.unshift(parameter);
      }

      return route;
    }

    function routeDelete(name, type, swKey){
      var parameter = {
        'name'        : swKey.name,
        'in'          : 'path',
        'description' : 'The key.',
        'required'    : true,
        'type'        : swKey.type,
      };
      if(swKey.format) parameter.format = swKey.format;

      return {
        'tags'        : [ type ],
        'description' : 'Delete an item from ' + name + '.',
        'parameters'  : [
          parameter,
          {
            'name': 'If-Match',
            'in': 'header',
            'description': 'If-Match header.',
            'type': 'string'
          }
        ],
        'responses': {
          '204': {
            'description' : 'Successful.'
          },
        }
      };
    }

    function genAllows(allows){
      if(!allows) return {'read' : true};

      var ac = {};
      for(var i = 0; i < allows.length; i++){
        ac[allows[i]] = true;
      }

      return ac;
    }

    if(!model.container) return;

    var paths= {};
    var visitor   = new Visitor();

    visitor.visitObj(model.container,{
      'entitysets'  : function(arr){
        visitor.visitArr(arr, function(item){
          var allows = genAllows(item.allows);
          var routes = {};
          if(allows.read) routes.get = routeGet(item.name, item.type, true);
          if(allows.create) routes.post = routePost(item.name, item.type);
          paths['/' + item.name] = routes;

          var swKey = resolveKey(item.type);
          if(swKey){
            var sRoutes = {};
            if(allows.read) sRoutes.get = routeGet(item.name, item.type, false, swKey) ;
            if(allows.update) sRoutes.put = routePut(item.name, item.type, swKey);
            if(allows.delete) sRoutes.delete = routeDelete(item.name, item.type, swKey);
            paths['/' + item.name + '/{' + swKey.name + '}' ] = sRoutes;
          }
        });
      },
      'singletons'  : function(arr){
        visitor.visitArr(arr, function(item){
          var allows = genAllows(item.allows);
          var routes = {};
          if(allows.read) routes.get = routeGet(item.name, item.type, false);
          if(allows.update) routes.put = routePut(item.name, item.type);
          paths['/' + item.name] = routes;
        });
      },
    });

    return paths;
  }

  Morpho.registerTo('swagger', function (model, errors, option){
    var visitor   = this.getVisitor();
    var state     = {
      'swagger'   : '2.0',
      'info'      : {
        'title'   : 'Demo',
        'version' : '0.1'
      },
      'paths'     : {}
    };

    var keys = {};

    visitor.visitObj(model, {
        'types'   : function(arr){
          state.definitions = {};
          this.visitArr(arr, function(item){
            var type = {properties:{}};
            var keyProperty = null;
            visitor.visitArr(item.properties, function(item){
              var swType = getSwaggerType(item.type, item.isCollection);
              var propertyType;
              if(swType.type){
                propertyType = { type: swType.type };
                if(swType.format) propertyType.format = swType.format;
                if(swType.items) propertyType.items = swType.items;
              }else{
                propertyType = swType;
              }

              type.properties[item.name] = propertyType;

              if(!keyProperty && item.isKey){
                keyProperty = {
                  'name'  : item.name,
                  'type'  : swType.type,
                  // add paths would check whether format undefined.
                  'format': swType.format
                };
              }
            });

            if(keyProperty){
              keys[item.name] = keyProperty;
            }

            state.definitions[item.name] = type;
          });
        }
      });

    state.paths = addPaths(model, function(type){
      return keys[type];
    });

    if(option.returnJSON){
      return state;
    }else if(option.format){
      return JSON.stringify(state, null, 2);
    }

    return JSON.stringify(state);
  });
})();
<|endoftext|>


<commit_before>(() => {
  return {
    data(){
      let tasks = this.closest('bbn-router').$parent;
      return {
        typeSelection: [{
          text: bbn._('Mine'),
          value: 'user'
        }, {
          text: bbn._('My groups'),
          value: 'group'
        }, {
          text: bbn._('All'),
          value: 'all'
        }],
        typeSelected: 'user',
        tableData: [],
        taskTitle: '',
        tasks: tasks,
        users: bbn.fn.order(appui.app.users, 'text', 'ASC'),
        priority: Array.apply(null, { length: 9 }).map(Function.call, a => { return a + 1 }),
        filters: {
          conditions: [{
            field: 'state',
            operator: 'neq',
            value: tasks.source.states.closed
          }]
        }
      };
    },
    methods: {
      createTask(){
        if ( this.taskTitle.length ){
          this.getPopup().open({
            title: bbn._('New task'),
            width: 500,
            component: this.$options.components['appui-tasks-create-form'],
            source: {
              title: this.taskTitle,
              type: ''
            },
            opener: this
          });
        }
      },
      openTask(row){
        bbn.fn.link(this.source.root + 'task/' + (typeof row === 'object' ? row.id : row) + '/main');
      },
      refreshTable(){
        this.$refs.tasksTable.updateData();
      },
      renderPriority(row){
        return '
' + row.priority + '
';
      },
      priorityClass(row){
        return 'bbn-c bbn-task-pr' + row.priority;
      },
      renderState(row){
        let icon,
            color;
        if ( row.state === this.tasks.source.states.opened ){
          icon = 'clock';
          color = 'orange';
        }
        else if ( row.state === this.tasks.source.states.pending ){
          icon = 'clock';
          color = 'red';
        }
        else if ( row.state === this.tasks.source.states.ongoing ){
          icon = 'play';
          color = 'blue';
        }
        else if ( row.state === this.tasks.source.states.closed ){
          icon = 'check';
          color = 'green';
        }
        else if ( row.state === this.tasks.source.states.holding ){
          icon = 'pause';
          color = 'grey';
        }
        return ' ';
      },
      renderLast(row){
        return dayjs(row.last_action).calendar();
      },
      renderRole(row){
        return bbn.fn.getField(this.tasks.source.options.roles, "text", "value", row.role) || '-';
      },
      renderType(row){
        return bbn.fn.getField(this.tasks.source.options.cats, "text", "value", row.type);
      },
      renderDuration(row){
        let start = dayjs(row.creation_date);
        return row.state === this.tasks.source.states.closed ?
          dayjs(row.last_action).from(start, true) :
          dayjs().from(start, true);
      },
      renderCreationDate(row){
        return dayjs(row.creation_date).calendar();
      },
      renderDeadline(row){
        let t = dayjs(row.deadline),
            now = dayjs(),
            diff = t.unix() - now.unix(),
            col = 'green',
            d = row.state === this.tasks.source.states.closed ? t.calendar() : t.fromNow();

        if ( !t.isValid() ){
          return '-';
        }
        if ( diff < 0 ){
          col = 'brown'
        }
        else if ( diff < (3*24*3600) ){
          col = 'red'
        }
        else if ( diff < (7*24*3600) ){
          col = 'orange'
        }
        else if ( diff < (7*24*3600) ){
          col = 'orange'
        }
        return '' + d + '';
      }
    },
    watch: {
      typeSelected(val){
        this.$nextTick(() => {
          this.refreshTable();
        });
      },
      taskTitle(val){
        if ( this.titleTimeout ){
          clearTimeout(this.titleTimeout);
        }
        this.titleTimeout = setTimeout(() => {
          this.refreshTable();
        }, 500);
      }
    },
    components: {
      'appui-tasks-user-avatar': {
        template: `
<bbn-initial v-if="source.id_user"
             :user-id="source.id_user"
             :title="userName"
             :height="25"
             :width="25"
             :font-size="15"
></bbn-initial>
        `,
        props: ['source'],
        computed: {
          userName(){
            return appui.app.getUserName(this.source.id_user);
          }
        }
      },
      'appui-tasks-create-form': {
        template: `
<bbn-form :action="cp.tasks.source.root + 'actions/task/insert'"
          :source="source"
          @success="refreshTable"
>

` + bbn._('Title') + `

    <bbn-input maxlength="255"
               required="required"
               v-model="source.title"
               class="bbn-w-100"
    ></bbn-input>

` + bbn._('Type') + `

    <bbn-dropdown :source="cp.tasks.fullCategories"
                  v-model="source.type"
                  group="group"
                  source-value="id"
                  required="required"
                  placeholder="`+ bbn._('Select a type...') +`"
                  class="bbn-w-100"
    ></bbn-dropdown>

</bbn-form>
        `,
        props: ['source'],
        data(){
          return {
            cp: this.closest('bbn-container').getComponent()
          }
        },
        methods: {
          refreshTable(d){
            this.cp.taskTitle = '';
            if ( d.success ){
              this.cp.openTask(d.success);
            }
          }
        }
      }
    }
  }
})();<commit_msg>Bugfixes on search page<commit_after>(() => {
  return {
    data(){
      let tasks = this.closest('bbn-router').$parent;
      return {
        typeSelection: [{
          text: bbn._('Mine'),
          value: 'user'
        }, {
          text: bbn._('My groups'),
          value: 'group'
        }, {
          text: bbn._('All'),
          value: 'all'
        }],
        typeSelected: 'user',
        tableData: [],
        taskTitle: '',
        tasks: tasks,
        users: bbn.fn.order(appui.app.users, 'text', 'ASC'),
        priority: Array.apply(null, { length: 9 }).map(Function.call, a => { return a + 1 }),
        filters: {
          conditions: [{
            field: 'state',
            operator: 'neq',
            value: tasks.source.states.closed
          }]
        }
      };
    },
    methods: {
      createTask(){
        if ( this.taskTitle.length ){
          this.getPopup().open({
            title: bbn._('New task'),
            width: 500,
            component: 'appui-task-form-new',
            source: {
              title: this.taskTitle,
              type: ''
            },
            opener: this
          });
        }
      },
      openTask(row){
        bbn.fn.link(this.source.root + 'task/' + (typeof row === 'object' ? row.id : row) + '/main');
      },
      refreshTable(){
        this.$refs.tasksTable.updateData();
      },
      renderPriority(row){
        return '
' + row.priority + '
';
      },
      priorityClass(row){
        return 'bbn-c bbn-task-pr' + row.priority;
      },
      renderState(row){
        let icon,
            color;
        if ( row.state === this.tasks.source.states.opened ){
          icon = 'clock';
          color = 'orange';
        }
        else if ( row.state === this.tasks.source.states.pending ){
          icon = 'clock';
          color = 'red';
        }
        else if ( row.state === this.tasks.source.states.ongoing ){
          icon = 'play';
          color = 'blue';
        }
        else if ( row.state === this.tasks.source.states.closed ){
          icon = 'check';
          color = 'green';
        }
        else if ( row.state === this.tasks.source.states.holding ){
          icon = 'pause';
          color = 'grey';
        }
        return ' ';
      },
      renderLast(row){
        return dayjs(row.last_action).calendar();
      },
      renderRole(row){
        return bbn.fn.getField(this.tasks.source.options.roles, "text", "value", row.role) || '-';
      },
      renderType(row){
        return bbn.fn.getField(this.tasks.source.options.cats, "text", "value", row.type);
      },
      renderDuration(row){
        let start = dayjs(row.creation_date);
        return row.state === this.tasks.source.states.closed ?
          dayjs(row.last_action).from(start, true) :
          dayjs().from(start, true);
      },
      renderCreationDate(row){
        return dayjs(row.creation_date).calendar();
      },
      renderDeadline(row){
        let t = dayjs(row.deadline),
            diff = t.unix() - dayjs().unix(),
            col = 'green',
            isClosed = row.state === appui.options.tasks.states.closed,
            d = isClosed ? t.calendar() : t.fromNow();

        if ( !t.isValid() ){
          return '-';
        }
        if ( diff < 0 ){
          col = 'brown'
        }
        else if ( diff < (3*24*3600) ){
          col = 'red'
        }
        else if ( diff < (7*24*3600) ){
          col = 'orange'
        }
        return `<span class="${isClosed ? '' : 'bbn-b '}bbn-${col}">${d}</span>`;
      }
    },
    watch: {
      typeSelected(val){
        this.$nextTick(() => {
          this.refreshTable();
        });
      },
      taskTitle(val){
        if ( this.titleTimeout ){
          clearTimeout(this.titleTimeout);
        }
        this.titleTimeout = setTimeout(() => {
          this.refreshTable();
        }, 500);
      }
    },
    components: {
      'appui-tasks-user-avatar': {
        template: `
<bbn-initial v-if="source.id_user"
             :user-id="source.id_user"
             :title="userName"
             :height="25"
             :width="25"
             :font-size="15"
></bbn-initial>
        `,
        props: ['source'],
        computed: {
          userName(){
            return appui.app.getUserName(this.source.id_user);
          }
        }
      }
    }
  }
})();<|endoftext|>


<commit_before>$(".ProfileNav .UserActions .user-actions").append('<button class="user-actions-follow-button btn" type="button">Block All</button>');
var usersBlocked = 0,
    usersFound = 0,
    usersSkipped = 0,
    totalCount = 0,
    errors = 0;
var scrollerInterval = false,
    finderInterval = false,
    blockerInterval = false;
var userQueue = new Queue();

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
    if (request.blockChainStart)
        startBlockChain();
    sendResponse({ack: true});
});
$("#blockAllUsers").click(startBlockChain);
function startBlockChain() {
    var result = confirm("Are you sure you want to block all users on this page that you aren't following?");
    if (!result)
        return;
    showDialog();
    var scrollerInterval = setInterval(function() {
        window.scroll(0, $(document).height());
        if ($(".GridTimeline-end.has-more-items").length==0) {
            clearInterval(scrollerInterval);
            scrollerInterval = false;
            doBlocking();
            totalCount = $(".ProfileCard").length;
            $("#blockchain-dialog .totalCount").text(totalCount);
        }
    },500);
    var finderInterval = setInterval(function() {
        doBlocking();
        if (usersFound==totalCount && totalCount > 0) {
            clearInterval(finderInterval);
            finderInterval = false;
        }
    },1000);
    var blockerInterval = setInterval(function() {
        var user = userQueue.dequeue();
        if (typeof user !== "undefined") {
            $.ajax({
                url: "https://twitter.com/i/user/block",
                method: "POST",
                dataType: 'json',
                data: {
                    authenticity_token: $("#signout-form input.authenticity_token").val(),
                    block_user: true,
                    impression_id: "",
                    report_type: "",
                    screen_name: user.name,
                    user_id: user.id
                }
            }).done(function(response) {
                //console.log(response);
            }).fail(function(xhr, text, err) {
                errors++;
                $("#blockchain-dialog .errorCount").text(errors);
                //console.log(xhr);
            }).always(function() {
                usersBlocked++;
                $("#blockchain-dialog .usersBlocked").text(usersBlocked);
                if ((usersBlocked == totalCount || usersBlocked == usersFound) && totalCount > 0) {
                    clearInterval(blockerInterval);
                    blockerInterval = false;
                }
            });
        }
    },40);
}

function doBlocking() {
    $(".ProfileCard:not(.blockchain-added)").each(function(i,e) {
        $(e).addClass("blockchain-added");
        if ($(e).find('.user-actions.following, .user-actions.blocked').length > 0) {
            usersSkipped++;
            $("#blockchain-dialog .usersSkipped").text(usersSkipped);
            return true;
        }
        usersFound++;
        $("#blockchain-dialog .usersFound").text(usersFound);
        userQueue.enqueue({
            name: $(e).data('screen-name'),
            id: $(e).data('user-id')
        });
    });
}

function showDialog() {
    $("body").append(
'
'+
	'

'+
	'

'+
	'
'+
		'
'+
			'
Block All Report
'+
		'
'+
		'
'+
            '
Found:
'+
            '
Skipped:
'+
            '
Blocked:
'+
            '
Total:
'+
            '
Errors:
'+
		'
'+
		'
'+
			'
'+
				'<button id="done" class="btn primary-btn report-tweet-next-button" type="button">Done</button>'+
			'
'+
		'
'+
	'
'+
	'<button type="button" class="modal-btn modal-close js-close" aria-controls="block-or-report-dialog-dialog">'+
		''+
			'Close'+
		''+
	'</button>'+
	'

'+
'
'
    );
    $("#blockchain-dialog").show().find("button").click(function() {
        if (blockerInterval)
            clearInterval(blockerInterval);
            clearInterval(scrollerInterval);
            clearInterval(finderInterval);
        $("#blockchain-dialog").hide();
    });
}<commit_msg>removed blockall button until i can sort out how to properly insert it<commit_after>/*
$(".ProfileNav .UserActions .user-actions").append('<button class="user-actions-follow-button btn" type="button">Block All</button>');
*/
var usersBlocked = 0,
    usersFound = 0,
    usersSkipped = 0,
    totalCount = 0,
    errors = 0;
var scrollerInterval = false,
    finderInterval = false,
    blockerInterval = false;
var userQueue = new Queue();

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
    if (request.blockChainStart)
        startBlockChain();
    sendResponse({ack: true});
});
$("#blockAllUsers").click(startBlockChain);
function startBlockChain() {
    var result = confirm("Are you sure you want to block all users on this page that you aren't following?");
    if (!result)
        return;
    showDialog();
    var scrollerInterval = setInterval(function() {
        window.scroll(0, $(document).height());
        if ($(".GridTimeline-end.has-more-items").length==0) {
            clearInterval(scrollerInterval);
            scrollerInterval = false;
            doBlocking();
            totalCount = $(".ProfileCard").length;
            $("#blockchain-dialog .totalCount").text(totalCount);
        }
    },500);
    var finderInterval = setInterval(function() {
        doBlocking();
        if (usersFound==totalCount && totalCount > 0) {
            clearInterval(finderInterval);
            finderInterval = false;
        }
    },1000);
    var blockerInterval = setInterval(function() {
        var user = userQueue.dequeue();
        if (typeof user !== "undefined") {
            $.ajax({
                url: "https://twitter.com/i/user/block",
                method: "POST",
                dataType: 'json',
                data: {
                    authenticity_token: $("#signout-form input.authenticity_token").val(),
                    block_user: true,
                    impression_id: "",
                    report_type: "",
                    screen_name: user.name,
                    user_id: user.id
                }
            }).done(function(response) {
                //console.log(response);
            }).fail(function(xhr, text, err) {
                errors++;
                $("#blockchain-dialog .errorCount").text(errors);
                //console.log(xhr);
            }).always(function() {
                usersBlocked++;
                $("#blockchain-dialog .usersBlocked").text(usersBlocked);
                if ((usersBlocked == totalCount || usersBlocked == usersFound) && totalCount > 0) {
                    clearInterval(blockerInterval);
                    blockerInterval = false;
                }
            });
        }
    },40);
}

function doBlocking() {
    $(".ProfileCard:not(.blockchain-added)").each(function(i,e) {
        $(e).addClass("blockchain-added");
        if ($(e).find('.user-actions.following, .user-actions.blocked').length > 0) {
            usersSkipped++;
            $("#blockchain-dialog .usersSkipped").text(usersSkipped);
            return true;
        }
        usersFound++;
        $("#blockchain-dialog .usersFound").text(usersFound);
        userQueue.enqueue({
            name: $(e).data('screen-name'),
            id: $(e).data('user-id')
        });
    });
}

function showDialog() {
    $("body").append(
'
'+
	'

'+
	'

'+
	'
'+
		'
'+
			'
Block All Report
'+
		'
'+
		'
'+
            '
Found:
'+
            '
Skipped:
'+
            '
Blocked:
'+
            '
Total:
'+
            '
Errors:
'+
		'
'+
		'
'+
			'
'+
				'<button id="done" class="btn primary-btn report-tweet-next-button" type="button">Done</button>'+
			'
'+
		'
'+
	'
'+
	'<button type="button" class="modal-btn modal-close js-close" aria-controls="block-or-report-dialog-dialog">'+
		''+
			'Close'+
		''+
	'</button>'+
	'

'+
'
'
    );
    $("#blockchain-dialog").show().find("button").click(function() {
        if (blockerInterval)
            clearInterval(blockerInterval);
            clearInterval(scrollerInterval);
            clearInterval(finderInterval);
        $("#blockchain-dialog").hide();
    });
}<|endoftext|>


<commit_before>'use strict';

const BaseEntity = require('./baseentity.js');

/**
 * Represents an in-game player.
 */
class Player extends BaseEntity {
  constructor(demo, index, classId, serialNum, baseline) {
    super(demo, index, classId, serialNum, baseline);

    /**
     * The 'client slot' is the index into various arrays such as the userinfo table.
     */
    this.clientSlot = index - 1;
  }

  /**
   * @returns {int} Current health
   */
  get health() {
    return this.getProp('DT_BasePlayer', 'm_iHealth');
  }

  get eyeAngles() {
    return {
      pitch: this.getProp('DT_CSPlayer', 'm_angEyeAngles[0]'),
      yaw: this.getProp('DT_CSPlayer', 'm_angEyeAngles[1]')
    };
  }

  get position() {
    let xy = this.getProp('DT_CSLocalPlayerExclusive', 'm_vecOrigin');
    return {
      x: xy.x,
      y: xy.y,
      z: this.getProp('DT_CSLocalPlayerExclusive', 'm_vecOrigin[2]')
    };
  }

  /**
   * @returns {int} Current cash
   */
  get account() {
    return this.getProp('DT_CSPlayer', 'm_iAccount');
  }

  /**
   * @returns {int} 0: Alive, 1: Dying, 2: Dead
   */
  get lifeState() {
    return this.getProp('DT_BasePlayer', 'm_lifeState');
  }

  /**
   * @returns {bool} lifeState == 0
   */
  get isAlive() {
    return this.lifeState === 0;
  }

  /**
   * @returns {PlayerInfo|null} User info associated with this player
   */
  get userInfo() {
    let userInfoTable = this._demo.stringTables.findTableByName('userinfo');
    return userInfoTable.entries[this.clientSlot].userData;
  }

  /**
   * @returns {int} User ID
   */
  get userId() {
    return this.userInfo.userId;
  }

  /**
   * @returns {string} Steam ID
   */
  get steamId() {
    return this.userInfo.guid;
  }

  /**
   * @returns {string} Steam 64 ID
   */
  get steam64Id() {
    return this.userInfo.xuid.toString();
  }

  /**
   * @returns {string} Player name
   */
  get name() {
    return this.userInfo.name;
  }

  /**
   * @returns {bool} Is this player fake (i.e. a bot)
   */
  get isFakePlayer() {
    return this.userInfo.fakePlayer;
  }

  /**
   * @returns {bool} Is this player a HLTV relay
   */
  get isHltv() {
    return this.userInfo.isHltv;
  }

  /**
   * @returns {int} Player armor (0-100)
   */
  get armor() {
    return this.getProp('DT_CSPlayer', 'm_ArmorValue');
  }

  /**
   * @returns {string} Current navmesh place name
   */
  get placeName() {
    return this.getProp('DT_BasePlayer', 'm_szLastPlaceName');
  }

  /**
   * @returns {Entity|null} Currently held weapon
   */
  get weapon() {
    return this._demo.entities.getByHandle(this.getProp('DT_BaseCombatCharacter', 'm_hActiveWeapon'));
  }

  /**
   * @returns {Entity[]} All weapons helds by this player
   */
  get weapons() {
    let weapons = [];

    for(let index in this.props['m_hMyWeapons']) {
      let weapon = this._demo.entities.getByHandle(this.props['m_hMyWeapons'][index]);

      if (weapon) {
        weapons.push(weapon);
      }
    }

    return weapons;
  }

  /**
   * @returns {bool} Is the player is the bomb zone?
   */
  get isInBombZone() {
    return this.getProp('DT_CSPlayer', 'm_bInBombZone');
  }

  /**
   * @returns {bool} Is the player in the buy zone?
   */
  get isInBuyZone() {
    return this.getProp('DT_CSPlayer', 'm_bInBuyZone');
  }

  /**
   * @returns {bool} Is the player defusing?
   */
  get isDefusing() {
    return this.getProp('DT_CSPlayer', 'm_bIsDefusing');
  }

  /**
   * @returns {bool} Does the player have a defuser?
   */
  get hasDefuser() {
    return this.getProp('DT_CSPlayer', 'm_bHasDefuser');
  }

  /**
   * @returns {bool} Does the player have a helmet?
   */
  get hasHelmet() {
    return this.getProp('DT_CSPlayer', 'm_bHasHelmet');
  }

  /**
   * @returns {int} How many kills the player has made
   */
  get kills() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let kills = pr.props['m_iKills'];
    return kills[Object.keys(kills)[this.index]];
  }

  /**
   * @returns {int} How many assists the player has made
   */
  get assists() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let assists = pr.props['m_iAssists'];
    return assists[Object.keys(assists)[this.index]];
  }

  /**
   * @returns {int} How many times the player has died
   */
  get deaths() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let deaths = pr.props['m_iDeaths'];
    return deaths[Object.keys(deaths)[this.index]];
  }

  /**
   * @returns {bool} Whether the player holds the C4
   */
  get hasC4() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    return pr.getProp('DT_CSPlayerResource', 'm_iPlayerC4') === this.index;
  }

  /**
   * @returns {int} Score of the player
   */
  get score() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let score = pr.props['m_iScore'];
    return score[Object.keys(score)[this.index]];
  }

  /**
   * @returns {int} MVPs of the player
   */
  get mvps() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let mvps = pr.props['m_iMVPs'];
    return mvps[Object.keys(mvps)[this.index]];
  }

  /**
   * @returns {string} Clantag of the player
   */
  get clanTag() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let clantag = pr.props['m_szClan'];
    return clantag[Object.keys(clantag)[this.index]];
  }

  /**
   * @returns {bool} Has this player been spotted by any others?
   */
  get isSpotted() {
    return this.getProp('DT_BaseEntity', 'm_bSpotted');
  }

  /**
   * @param {Player} other - Other player entity
   * @returns {bool} Is this player spotted by the other?
   */
  isSpottedBy(other) {
    let bit = other.clientSlot;
    let mask = null;

    if (other.clientSlot < 32) {
      mask = this.getProp('m_bSpottedByMask', '000');
    } else {
      bit = other.clientSlot - 32;
      mask = this.getProp('m_bSpottedByMask', '001');
    }

    return (mask & (1 << bit)) !== 0;
  }

  /**
   * @returns {Player[]} Players that have spotted this player
   */
  get allSpotters() {
    let masks = [
      this.getProp('m_bSpottedByMask', '000'),
      this.getProp('m_bSpottedByMask', '001')
    ];

    return Array.from({length: 64}, (_, i) => i)
      .filter(i => {
        let bit = i % 32;
        let mask = masks[(i/32) >> 0];
        return (mask & (1 << bit)) !== 0;
      })
      .map(clientSlot => this._demo.entities.entities[clientSlot + 1]);
  }

  /**
   * @param {Player} other - Other player entity
   * @returns {bool} Has this player spotted the other?
   */
  hasSpotted(other) {
    return other.isSpottedBy(this);
  }

  /**
   * @returns {Player[]} All players that this player has spotted
   */
  get allSpotted() {
    return this._demo.players
      .filter(p => p.clientSlot !== this.clientSlot && this.hasSpotted(p));
  }

  /**
   * @param {Player} other - Other player entity
   * @returns {bool} Whether the two players are on the same team
   */
  isFriendly(other) {
    let sameTeam = this.teamNumber === other.teamNumber;
    let teammatesAreEnemies = this._demo.conVars.vars['mp_teammates_are_enemies'] || 0;

    return sameTeam && !teammatesAreEnemies;
  }
}

module.exports = Player;
<commit_msg>Adding more property getters to player entity<commit_after>'use strict';

const BaseEntity = require('./baseentity.js');

/**
 * Represents an in-game player.
 */
class Player extends BaseEntity {
  constructor(demo, index, classId, serialNum, baseline) {
    super(demo, index, classId, serialNum, baseline);

    /**
     * The 'client slot' is the index into various arrays such as the userinfo table.
     */
    this.clientSlot = index - 1;
  }

  /**
   * @returns {int} Current health
   */
  get health() {
    return this.getProp('DT_BasePlayer', 'm_iHealth');
  }

  get eyeAngles() {
    return {
      pitch: this.getProp('DT_CSPlayer', 'm_angEyeAngles[0]'),
      yaw: this.getProp('DT_CSPlayer', 'm_angEyeAngles[1]')
    };
  }

  get position() {
    let xy = this.getProp('DT_CSLocalPlayerExclusive', 'm_vecOrigin');
    return {
      x: xy.x,
      y: xy.y,
      z: this.getProp('DT_CSLocalPlayerExclusive', 'm_vecOrigin[2]')
    };
  }

  /**
   * @returns {int} Current cash
   */
  get account() {
    return this.getProp('DT_CSPlayer', 'm_iAccount');
  }

  /**
   * @returns {int} 0: Alive, 1: Dying, 2: Dead
   */
  get lifeState() {
    return this.getProp('DT_BasePlayer', 'm_lifeState');
  }

  /**
   * @returns {bool} lifeState == 0
   */
  get isAlive() {
    return this.lifeState === 0;
  }

  /**
   * @returns {PlayerInfo|null} User info associated with this player
   */
  get userInfo() {
    let userInfoTable = this._demo.stringTables.findTableByName('userinfo');
    return userInfoTable.entries[this.clientSlot].userData;
  }

  /**
   * @returns {int} User ID
   */
  get userId() {
    return this.userInfo.userId;
  }

  /**
   * @returns {string} Steam ID
   */
  get steamId() {
    return this.userInfo.guid;
  }

  /**
   * @returns {string} Steam 64 ID
   */
  get steam64Id() {
    return this.userInfo.xuid.toString();
  }

  /**
   * @returns {string} Player name
   */
  get name() {
    return this.userInfo.name;
  }

  /**
   * @returns {bool} Is this player fake (i.e. a bot)
   */
  get isFakePlayer() {
    return this.userInfo.fakePlayer;
  }

  /**
   * @returns {bool} Is this player a HLTV relay
   */
  get isHltv() {
    return this.userInfo.isHltv;
  }

  /**
   * @returns {int} Player armor (0-100)
   */
  get armor() {
    return this.getProp('DT_CSPlayer', 'm_ArmorValue');
  }

  /**
   * @returns {string} Current navmesh place name
   */
  get placeName() {
    return this.getProp('DT_BasePlayer', 'm_szLastPlaceName');
  }

  /**
   * @returns {Entity|null} Currently held weapon
   */
  get weapon() {
    return this._demo.entities.getByHandle(this.getProp('DT_BaseCombatCharacter', 'm_hActiveWeapon'));
  }

  /**
   * @returns {Entity[]} All weapons helds by this player
   */
  get weapons() {
    let weapons = [];

    for(let index in this.props['m_hMyWeapons']) {
      let weapon = this._demo.entities.getByHandle(this.props['m_hMyWeapons'][index]);

      if (weapon) {
        weapons.push(weapon);
      }
    }

    return weapons;
  }

  /**
   * @returns {bool} Is the player is the bomb zone?
   */
  get isInBombZone() {
    return this.getProp('DT_CSPlayer', 'm_bInBombZone');
  }

  /**
   * @returns {bool} Is the player in the buy zone?
   */
  get isInBuyZone() {
    return this.getProp('DT_CSPlayer', 'm_bInBuyZone');
  }

  /**
   * @returns {bool} Is the player defusing?
   */
  get isDefusing() {
    return this.getProp('DT_CSPlayer', 'm_bIsDefusing');
  }

  /**
   * @returns {bool} Does the player have a defuser?
   */
  get hasDefuser() {
    return this.getProp('DT_CSPlayer', 'm_bHasDefuser');
  }

  /**
   * @returns {bool} Does the player have a helmet?
   */
  get hasHelmet() {
    return this.getProp('DT_CSPlayer', 'm_bHasHelmet');
  }

  /**
   * @returns {int} How many kills the player has made
   */
  get kills() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let kills = pr.props['m_iKills'];
    return kills[Object.keys(kills)[this.index]];
  }

  /**
   * @returns {int} How many assists the player has made
   */
  get assists() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let assists = pr.props['m_iAssists'];
    return assists[Object.keys(assists)[this.index]];
  }

  /**
   * @returns {int} How many times the player has died
   */
  get deaths() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let deaths = pr.props['m_iDeaths'];
    return deaths[Object.keys(deaths)[this.index]];
  }

  /**
   * @returns {bool} Whether the player holds the C4
   */
  get hasC4() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    return pr.getProp('DT_CSPlayerResource', 'm_iPlayerC4') === this.index;
  }

  /**
   * @returns {int} Score of the player
   */
  get score() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let score = pr.props['m_iScore'];
    return score[Object.keys(score)[this.index]];
  }

  /**
   * @returns {int} MVPs of the player
   */
  get mvps() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let mvps = pr.props['m_iMVPs'];
    return mvps[Object.keys(mvps)[this.index]];
  }

  /**
   * @returns {string} Clantag of the player
   */
  get clanTag() {
    let pr = this._demo.entities.getSingleton('DT_CSPlayerResource');
    let clantag = pr.props['m_szClan'];
    return clantag[Object.keys(clantag)[this.index]];
  }

  /**
   * @returns {bool} Has this player been spotted by any others?
   */
  get isSpotted() {
    return this.getProp('DT_BaseEntity', 'm_bSpotted');
  }

  /**
   * @param {Player} other - Other player entity
   * @returns {bool} Is this player spotted by the other?
   */
  isSpottedBy(other) {
    let bit = other.clientSlot;
    let mask = null;

    if (other.clientSlot < 32) {
      mask = this.getProp('m_bSpottedByMask', '000');
    } else {
      bit = other.clientSlot - 32;
      mask = this.getProp('m_bSpottedByMask', '001');
    }

    return (mask & (1 << bit)) !== 0;
  }

  /**
   * @returns {Player[]} Players that have spotted this player
   */
  get allSpotters() {
    let masks = [
      this.getProp('m_bSpottedByMask', '000'),
      this.getProp('m_bSpottedByMask', '001')
    ];

    return Array.from({length: 64}, (_, i) => i)
      .filter(i => {
        let bit = i % 32;
        let mask = masks[(i/32) >> 0];
        return (mask & (1 << bit)) !== 0;
      })
      .map(clientSlot => this._demo.entities.entities[clientSlot + 1]);
  }

  /**
   * @param {Player} other - Other player entity
   * @returns {bool} Has this player spotted the other?
   */
  hasSpotted(other) {
    return other.isSpottedBy(this);
  }

  /**
   * @returns {Player[]} All players that this player has spotted
   */
  get allSpotted() {
    return this._demo.players
      .filter(p => p.clientSlot !== this.clientSlot && this.hasSpotted(p));
  }

  /**
   * @param {Player} other - Other player entity
   * @returns {bool} Whether the two players are on the same team
   */
  isFriendly(other) {
    let sameTeam = this.teamNumber === other.teamNumber;
    let teammatesAreEnemies = this._demo.conVars.vars['mp_teammates_are_enemies'] || 0;

    return sameTeam && !teammatesAreEnemies;
  }

  /**
   * @returns {bool} Is scoped
   */
  get isScoped() {
    return this.getProp('DT_CSPlayer', 'm_bIsScoped');
  }

  /**
   * @returns {bool} Is walking
   */
  get isWalking() {
    return this.getProp('DT_CSPlayer', 'm_bIsWalking');
  }

  /**
   * @returns {float} Duration of a flash that hit the player
   */
  get flashDuration() {
    return this.getProp('DT_CSPlayer', 'm_flFlashDuration');
  }

  /**
   * @returns {int} Current equipment value
   */
  get currentEquipmentValue() {
    return this.getProp('DT_CSPlayer', 'm_unCurrentEquipmentValue');
  }

  /**
   * @returns {int} Round start equipment value
   */
  get roundStartEquipmentValue() {
    return this.getProp('DT_CSPlayer', 'm_unRoundStartEquipmentValue');
  }

  /**
   * @returns {int} Freeze time end equipment value
   */
  get freezeTimeEndEquipmentValue() {
    return this.getProp('DT_CSPlayer', 'm_unFreezetimeEndEquipmentValue');
  }
}

module.exports = Player;
<|endoftext|>


<commit_before>// Global variables to manipulate Videos/canvases.
var video = [];
var videoImage = [];
var videoImageContext = [];
var imageData = [];

var homography = [[],[],[]];

// This function is called by common.js when the NaCl module is loaded.
function moduleDidLoad() {
  // Once we load, hide the plugin. In this example, we don't display anything
  // in the plugin, so it is fine to hide it.
  common.hideModule();

  document.getElementById('btn_calibrate').disabled = false;
}

var byteArray = [];
// This function is called by common.js when a message is received from the
// NaCl module.
function handleMessage(message) {
  // Via this single communication channel comes messages to dump to console and
  // hopefully the H matrix as well, coefficient by coefficient.
  if (message.data['message'] == "H") {
    // Uncomment next line for Debug:
    //console.log(message.data['row'] +" " +message.data['column'] +" "+message.data['value']);

    // |row|, |column| range from 0 to 2 and value is float.
    homography[message.data['row']][message.data['column']] =
        message.data['value'];

    if (homography[0].length==3 && homography[1].length==3 && homography[2].length==3) {
      console.log(" H=[" + homography[0][0].toFixed(3) +" "+ homography[0][1].toFixed(3) +" "+ homography[0][2].toFixed(3) + "]");
      console.log("   [" + homography[1][0].toFixed(3) +" "+ homography[1][1].toFixed(3) +" "+ homography[1][2].toFixed(3) + "]");
      console.log("   [" + homography[2][0].toFixed(3) +" "+ homography[2][1].toFixed(3) +" "+ homography[2][2].toFixed(3) + "]");

      updateWebGLWithHomography(homography);
      homography[0].length = homography[1].length = homography[2].length = 0;
    }
  } else if (message.data['message'] == "I") {
    var int8View = new Int8Array(message.data['value']);
    console.log(" Got image " + message.data['value'] + " - " +
        int8View.byteLength + "B");

    if (0) {
      var cnv1 = document.getElementById('canvas3');
      var ctx1 = cnv1.getContext('2d');
      var imageData1 = ctx1.getImageData(0, 0, 320, 240);
      var data1 = imageData1.data;
      var p = 0;
      for (var i = 0; i < data1.length; i += 4) {
        data1[i]     = int8View[p++];
        data1[i + 1] = int8View[p++];//int8View[i + 1];
        data1[i + 2] = int8View[p++];//int8View[i + 2];
        data1[i + 3] = 255;//int8View[p++];//int8View[i + 3];
        p++;
      }
      ctx1.putImageData(imageData1, 0, 0);
    }

  } else {
    // Dump stuff to special PNaCl output area.
    var logEl = document.getElementById('log');
    logEl.textContent += message.data;

    // And/Or to JS Console.
    console.log(message.data);
  }
}

// Calibrate does a whole lot of things: Plugs the <video> tags into their
// respective hidden <canvas> eleemnts, and then passes the data from those
// canvas snapshots to the stiching module, via a protocol of 3 steps:
// first the index of the next data buffer, then the buffer itself, repeat for
// each buffer; when done, send a string asking politely to do the stitching.
function calibrate() {

  // Plug the <video> vidX into canvasX.
  for(var i=0; i<2; i++) {
    video[i] = document.getElementById('vid' + (i+1));

    videoImage[i] = document.getElementById('canvas' + (i+1));
    videoImageContext[i] = videoImage[i].getContext('2d');
    // background color if no video present
    videoImageContext[i].fillStyle = '#000000';
    videoImageContext[i].fillRect( 0, 0, videoImage[0].width, videoImage[0].height);
  }

  for(var i=0; i<2; i++) {
    if (video[i].readyState === video[i].HAVE_ENOUGH_DATA) {
      videoImageContext[i].drawImage(
          video[i], 0, 0, videoImage[0].width, videoImage[0].height);
      imageData[i] = videoImageContext[i].getImageData(
          0, 0, videoImage[0].width, videoImage[0].height);

      // After the NaCl module has loaded, common.naclModule is a reference to
      // the NaCl module's <embed> element. Method postMessage sends a message
      // to it. F.i.:
      common.naclModule.postMessage({'message' : 'data',
                                     'index' : i,
                                     'width' : videoImage[0].width,
                                     'height' : videoImage[0].height,
                                     'data' : imageData[i].data.buffer});
    }
  }
  common.naclModule.postMessage('Please calculate the homography.');
}
<commit_msg>Removed cruft.<commit_after>// Global variables to manipulate Videos/canvases.
var video = [];
var videoImage = [];
var videoImageContext = [];
var imageData = [];

var homography = [[],[],[]];

// This function is called by common.js when the NaCl module is loaded.
function moduleDidLoad() {
  // Once we load, hide the plugin. In this example, we don't display anything
  // in the plugin, so it is fine to hide it.
  common.hideModule();

  document.getElementById('btn_calibrate').disabled = false;
}

// This function is called by common.js when a message is received from the
// NaCl module.
function handleMessage(message) {
  // Via this single communication channel comes messages to dump to console and
  // hopefully the H matrix as well, coefficient by coefficient.
  if (message.data['message'] == "H") {
    // Uncomment next line for Debug:
    //console.log(message.data['row'] +" " +message.data['column'] +" "+message.data['value']);

    // |row|, |column| range from 0 to 2 and value is float.
    homography[message.data['row']][message.data['column']] =
        message.data['value'];

    if (homography[0].length==3 && homography[1].length==3 && homography[2].length==3) {
      console.log(" H=[" + homography[0][0].toFixed(3) +" "+ homography[0][1].toFixed(3) +" "+ homography[0][2].toFixed(3) + "]");
      console.log("   [" + homography[1][0].toFixed(3) +" "+ homography[1][1].toFixed(3) +" "+ homography[1][2].toFixed(3) + "]");
      console.log("   [" + homography[2][0].toFixed(3) +" "+ homography[2][1].toFixed(3) +" "+ homography[2][2].toFixed(3) + "]");

      updateWebGLWithHomography(homography);
      homography[0].length = homography[1].length = homography[2].length = 0;
    }
  } else if (message.data['message'] == "I") {
    var int8View = new Int8Array(message.data['value']);
    console.log(" Got image " + message.data['value'] + " - " +
        int8View.byteLength + "B");

    if (0) {
      var cnv1 = document.getElementById('canvas3');
      var ctx1 = cnv1.getContext('2d');
      var imageData1 = ctx1.getImageData(0, 0, 320, 240);
      var data1 = imageData1.data;
      var p = 0;
      for (var i = 0; i < data1.length; i += 4) {
        data1[i]     = int8View[p++];
        data1[i + 1] = int8View[p++];//int8View[i + 1];
        data1[i + 2] = int8View[p++];//int8View[i + 2];
        data1[i + 3] = 255;//int8View[p++];//int8View[i + 3];
        p++;
      }
      ctx1.putImageData(imageData1, 0, 0);
    }

  } else {
    // Dump stuff to special PNaCl output area.
    var logEl = document.getElementById('log');
    logEl.textContent += message.data;

    // And/Or to JS Console.
    console.log(message.data);
  }
}

// Calibrate does a whole lot of things: Plugs the <video> tags into their
// respective hidden <canvas> eleemnts, and then passes the data from those
// canvas snapshots to the stiching module, via a protocol of 3 steps:
// first the index of the next data buffer, then the buffer itself, repeat for
// each buffer; when done, send a string asking politely to do the stitching.
function calibrate() {

  // Plug the <video> vidX into canvasX.
  for(var i=0; i<2; i++) {
    video[i] = document.getElementById('vid' + (i+1));

    videoImage[i] = document.getElementById('canvas' + (i+1));
    videoImageContext[i] = videoImage[i].getContext('2d');
    // background color if no video present
    videoImageContext[i].fillStyle = '#000000';
    videoImageContext[i].fillRect( 0, 0, videoImage[0].width, videoImage[0].height);
  }

  for(var i=0; i<2; i++) {
    if (video[i].readyState === video[i].HAVE_ENOUGH_DATA) {
      videoImageContext[i].drawImage(
          video[i], 0, 0, videoImage[0].width, videoImage[0].height);
      imageData[i] = videoImageContext[i].getImageData(
          0, 0, videoImage[0].width, videoImage[0].height);

      // After the NaCl module has loaded, common.naclModule is a reference to
      // the NaCl module's <embed> element. Method postMessage sends a message
      // to it. F.i.:
      common.naclModule.postMessage({'message' : 'data',
                                     'index' : i,
                                     'width' : videoImage[0].width,
                                     'height' : videoImage[0].height,
                                     'data' : imageData[i].data.buffer});
    }
  }
  common.naclModule.postMessage('Please calculate the homography.');
}
<|endoftext|>


<commit_before>/**
 * Push
 * =======
 * A compact, cross-browser solution for the JavaScript Notifications API
 *
 * Credits
 * -------
 * Tsvetan Tsvetkov (ttsvetko)
 * Alex Gibson (alexgibson)
 *
 * License
 * -------
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Tyler Nickerson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @preserve
 */

(function (global, factory) {

    'use strict';

    /* Use AMD */
    if (typeof define === 'function' && define.amd) {
        define(function () {
            return new (factory(global, global.document))();
        });
    }
    /* Use CommonJS */
    else if (typeof module !== 'undefined' && module.exports) {
        module.exports = (factory(global, global.document))();
    }
    /* Use Browser */
    else {
        global.Push = new (factory(global, global.document))();
    }

})(window !== 'undefined' ? window : self, function (w, d) {

    var Push = function () {

        var
        self = this,
        isUndefined   = function (obj) { return obj === undefined; },
        isString   = function (obj) { return obj && obj.constructor === String; },
        isFunction = function (obj) { return obj && obj.constructor === Function; },

        /* Whether Push has permission to notify */
        hasPermission = false,

        /* List of active notifications */
        notifications = [],

        /**
         * Closes a notification
         * @param {Notification} notification
         * @return {void}
         */
        close_notification = function (notification) {

            /* Safari 6+, Chrome 23+ */
            if (notification.close) {

                notification.close();

            /* Legacy webkit browsers */
            } else if (notification.cancel) {

                notification.cancel();

            /* IE9+ */
            } else if (w.external && w.external.msIsSiteMode) {

                w.external.msSiteModeClearIconOverlay();

            }

        },

        /**
         * Updates the notification count
         * @return {void}
         */
        updateCount = function () {
            self.count = notifications.length;
        },

        /**
         * Callback function for the 'create' method
         * @return {void}
         */
        create_callback = function (title, options) {

            /* Set empty settings if none are specified */
            options = options || {};

            /* Safari 6+, Chrome 23+ */
            if (w.Notification) {

                notification =  new w.Notification(
                    title,
                    {
                        icon: (isString(options.icon) || isUndefined(options.icon)) ? options.icon : options.icon.x32,
                        body: options.body,
                        tag: options.tag,
                    }
                );

            /* Legacy webkit browsers */
            } else if (w.webkitNotifications) {

                notification = win.webkitNotifications.createNotification(
                    options.icon,
                    title,
                    options.body
                );

                notification.show();

            /* Firefox Mobile */
            } else if (navigator.mozNotification) {

                notification = navigator.mozNotification.createNotification(
                    title,
                    options.body,
                    options.icon
                );

                notification.show();

            /* IE9+ */
            } else if (win.external && win.external.msIsSiteMode()) {

                //Clear any previous notifications
                w.external.msSiteModeClearIconOverlay();
                w.external.msSiteModeSetIconOverlay(((isString(options.icon) || isUndefined(options.icon)) ? options.icon : options.icon.x16), title);
                w.external.msSiteModeActivate();

                notification = {};
            }

            /* Wrapper used to close notification later on */
            wrapper = {

                close: function () {
                    close_notification(notification);
                }

            };

            /* Autoclose timeout */
            if (options.timeout) {
                setTimeout(function () {
                    wrapper.close();
                }, options.timeout);
            }

            /* Notification callbacks */
            if (isFunction(options.onShow))
                notification.addEventListener('show', options.onShow);

            if (isFunction(options.onError))
                notification.addEventListener('error', options.onError);

            if (isFunction(options.onClick))
                notification.addEventListener('click', options.onClick);

            if (isFunction(options.onClose)) {
                notification.addEventListener('close', options.onClose);
                notification.addEventListener('cancel', options.onClose);
            }

            /* Add it to the global array */
            notifications.push(notification);

            /* Update the notification count */
            updateCount();

            /* Return the wrapper so the user can call close() */
            return wrapper;
        },

        /**
         * Permission types
         * @enum {String}
         */
        Permission = {
            DEFAULT: 'default',
            GRANTED: 'granted',
            DENIED: 'denied'
        },

        Permissions = [Permission.GRANTED, Permission.DEFAULT, Permission.DENIED];

        /* Allow enums to be accessible from Push object */
        self.Permission = Permission;

        /* Number of open notifications */
        self.count = 0;

        /*****************
            Permissions
        /*****************/

        /**
         * Requests permission for desktop notifications
         * @param {Function} callback - Function to execute once permission is granted
         * @return {void}
         */
        self.Permission.request = function (onGranted, onDenied) {

            /* Return if Push not supported */
            if (!self.isSupported) {
                console.error('PushError: push.js is incompatible with browser.');
                return;
            }

            /* Default callback */
            callback = function (result) {

                switch (result) {

                    case self.Permission.GRANTED:
                        hasPermission = true;
                        if (onGranted) onGranted();
                        break;

                    case self.Permission.DENIED:
                        hasPermission = false;
                        if (onDenied) onDenied();
                        break;

                }

            };

            /* Safari 6+, Chrome 23+ */
            if (w.Notification && w.Notification.requestPermission) {
                Notification.requestPermission(callback);
            }
            /* Legacy webkit browsers */
            else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
                w.webkitNotifications.requestPermission(callback);
            }

        };

        /**
         * Returns whether Push has been granted permission to run
         * @return {Boolean}
         */
        self.Permission.has = function () {
            return hasPermission;
        };

        /**
         * Gets the permission level
         * @return {Permission} The permission level
         */
        self.Permission.get = function () {

            var permission;

            /* Return if Push not supported */
            if (!self.isSupported) { return; }

            /* Safari 6+, Chrome 23+ */
            if (w.Notification && w.Notification.permissionLevel) {
                permission = w.Notification.permissionLevel;

            /* Legacy webkit browsers */
            } else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
                permission = Permissions[w.webkitNotifications.checkPermission()];

            /* Firefox 23+ */
            } else if (w.Notification && w.Notification.permission) {
                permission = w.Notification.permission;

            /* Firefox Mobile */
            } else if (navigator.mozNotification) {
                permission = Permissions.GRANTED;

            /* IE9+ */
            } else if (w.external && w.external.msIsSiteMode() !== undefined) {
                permission = w.external.msIsSiteMode() ? Permission.GRANTED : Permission.DEFAULT;
            }

            return permission;

        };

        /*********************
            Other Functions
        /*********************/

        /**
         * Detects whether the user's browser supports notifications
         * @return {Boolean}
         */
        self.isSupported = (function () {

             var isSupported = false;

             try {

                 isSupported =

                     /* Safari, Chrome */
                     !!(w.Notification ||

                     /* Chrome & ff-html5notifications plugin */
                     w.webkitNotifications ||

                     /* Firefox Mobile */
                     navigator.mozNotification ||

                     /* IE9+ */
                     (w.external && w.external.msIsSiteMode() !== undefined));

             } catch (e) {}

             return isSupported;

         })();

         /**
          * Creates and displays a new notification
          * @param {Array} options
          * @return {void}
          */
        self.create = function (title, options) {
            var notification,
                wrapper;

            /* Fail if the browser is not supported */
            if (!self.isSupported) {
                console.error('PushError: push.js is incompatible with browser.');
                return;
            }

            /* Fail if no or an invalid title is provided */
            if (typeof title !== 'string') {
                throw 'PushError: Title of notification must be a string';
            }

            /* Request permission if it isn't granted */
            if (!self.Permission.has()) {
                return new Promise(function(resolve, reject) {
                    self.Permission.request(function() {
                        resolve(create_callback(title, options));
                    }, function() {
                        reject("Permission request declined");
                    });
                });
            } else {
                return new Promise(function(resolve, reject) {
                    resolve(create_callback(title, options));
                });
            }

        };

        /**
         * Closes a notification with the given tag
         * @param {String} tag - Tag of the notification to close
         * @return {void}
         */
        self.close = function (tag) {

            var i, notification;

            for (i = 0; i < notifications.length; i++) {

                notification = notifications[i];

                /* Run only if the tags match */
                if (notification.tag === tag) {

                    /* Call the notification's close() method */
                    close_notification(notification);

                    /* Remove the notification from the global array */
                    notifications.splice(i, 1);

                    /* Update the notification count */
                    updateCount();

                    /* Return after the first notification is closed */
                    return;

                }
            }

        };

        /**
         * Clears all notifications
         * @return {void}
         */
        self.clear = function () {

            var i;

            for (i = 0; i < notifications.length; i++) {
                close_notification(notifications[i]);
            }

            /* Reset the global array */
            notifications = [];

            /* Update the notification count */
            updateCount();
        };
    };

    return Push;

});
<commit_msg>cmd exports should  be consistent with others<commit_after>/**
 * Push
 * =======
 * A compact, cross-browser solution for the JavaScript Notifications API
 *
 * Credits
 * -------
 * Tsvetan Tsvetkov (ttsvetko)
 * Alex Gibson (alexgibson)
 *
 * License
 * -------
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Tyler Nickerson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @preserve
 */

(function (global, factory) {

    'use strict';

    /* Use AMD */
    if (typeof define === 'function' && define.amd) {
        define(function () {
            return new (factory(global, global.document))();
        });
    }
    /* Use CommonJS */
    else if (typeof module !== 'undefined' && module.exports) {
        module.exports = new (factory(global, global.document))();
    }
    /* Use Browser */
    else {
        global.Push = new (factory(global, global.document))();
    }

})(window !== 'undefined' ? window : self, function (w, d) {

    var Push = function () {

        var
        self = this,
        isUndefined   = function (obj) { return obj === undefined; },
        isString   = function (obj) { return obj && obj.constructor === String; },
        isFunction = function (obj) { return obj && obj.constructor === Function; },

        /* Whether Push has permission to notify */
        hasPermission = false,

        /* List of active notifications */
        notifications = [],

        /**
         * Closes a notification
         * @param {Notification} notification
         * @return {void}
         */
        close_notification = function (notification) {

            /* Safari 6+, Chrome 23+ */
            if (notification.close) {

                notification.close();

            /* Legacy webkit browsers */
            } else if (notification.cancel) {

                notification.cancel();

            /* IE9+ */
            } else if (w.external && w.external.msIsSiteMode) {

                w.external.msSiteModeClearIconOverlay();

            }

        },

        /**
         * Updates the notification count
         * @return {void}
         */
        updateCount = function () {
            self.count = notifications.length;
        },

        /**
         * Callback function for the 'create' method
         * @return {void}
         */
        create_callback = function (title, options) {

            /* Set empty settings if none are specified */
            options = options || {};

            /* Safari 6+, Chrome 23+ */
            if (w.Notification) {

                notification =  new w.Notification(
                    title,
                    {
                        icon: (isString(options.icon) || isUndefined(options.icon)) ? options.icon : options.icon.x32,
                        body: options.body,
                        tag: options.tag,
                    }
                );

            /* Legacy webkit browsers */
            } else if (w.webkitNotifications) {

                notification = win.webkitNotifications.createNotification(
                    options.icon,
                    title,
                    options.body
                );

                notification.show();

            /* Firefox Mobile */
            } else if (navigator.mozNotification) {

                notification = navigator.mozNotification.createNotification(
                    title,
                    options.body,
                    options.icon
                );

                notification.show();

            /* IE9+ */
            } else if (win.external && win.external.msIsSiteMode()) {

                //Clear any previous notifications
                w.external.msSiteModeClearIconOverlay();
                w.external.msSiteModeSetIconOverlay(((isString(options.icon) || isUndefined(options.icon)) ? options.icon : options.icon.x16), title);
                w.external.msSiteModeActivate();

                notification = {};
            }

            /* Wrapper used to close notification later on */
            wrapper = {

                close: function () {
                    close_notification(notification);
                }

            };

            /* Autoclose timeout */
            if (options.timeout) {
                setTimeout(function () {
                    wrapper.close();
                }, options.timeout);
            }

            /* Notification callbacks */
            if (isFunction(options.onShow))
                notification.addEventListener('show', options.onShow);

            if (isFunction(options.onError))
                notification.addEventListener('error', options.onError);

            if (isFunction(options.onClick))
                notification.addEventListener('click', options.onClick);

            if (isFunction(options.onClose)) {
                notification.addEventListener('close', options.onClose);
                notification.addEventListener('cancel', options.onClose);
            }

            /* Add it to the global array */
            notifications.push(notification);

            /* Update the notification count */
            updateCount();

            /* Return the wrapper so the user can call close() */
            return wrapper;
        },

        /**
         * Permission types
         * @enum {String}
         */
        Permission = {
            DEFAULT: 'default',
            GRANTED: 'granted',
            DENIED: 'denied'
        },

        Permissions = [Permission.GRANTED, Permission.DEFAULT, Permission.DENIED];

        /* Allow enums to be accessible from Push object */
        self.Permission = Permission;

        /* Number of open notifications */
        self.count = 0;

        /*****************
            Permissions
        /*****************/

        /**
         * Requests permission for desktop notifications
         * @param {Function} callback - Function to execute once permission is granted
         * @return {void}
         */
        self.Permission.request = function (onGranted, onDenied) {

            /* Return if Push not supported */
            if (!self.isSupported) {
                console.error('PushError: push.js is incompatible with browser.');
                return;
            }

            /* Default callback */
            callback = function (result) {

                switch (result) {

                    case self.Permission.GRANTED:
                        hasPermission = true;
                        if (onGranted) onGranted();
                        break;

                    case self.Permission.DENIED:
                        hasPermission = false;
                        if (onDenied) onDenied();
                        break;

                }

            };

            /* Safari 6+, Chrome 23+ */
            if (w.Notification && w.Notification.requestPermission) {
                Notification.requestPermission(callback);
            }
            /* Legacy webkit browsers */
            else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
                w.webkitNotifications.requestPermission(callback);
            }

        };

        /**
         * Returns whether Push has been granted permission to run
         * @return {Boolean}
         */
        self.Permission.has = function () {
            return hasPermission;
        };

        /**
         * Gets the permission level
         * @return {Permission} The permission level
         */
        self.Permission.get = function () {

            var permission;

            /* Return if Push not supported */
            if (!self.isSupported) { return; }

            /* Safari 6+, Chrome 23+ */
            if (w.Notification && w.Notification.permissionLevel) {
                permission = w.Notification.permissionLevel;

            /* Legacy webkit browsers */
            } else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
                permission = Permissions[w.webkitNotifications.checkPermission()];

            /* Firefox 23+ */
            } else if (w.Notification && w.Notification.permission) {
                permission = w.Notification.permission;

            /* Firefox Mobile */
            } else if (navigator.mozNotification) {
                permission = Permissions.GRANTED;

            /* IE9+ */
            } else if (w.external && w.external.msIsSiteMode() !== undefined) {
                permission = w.external.msIsSiteMode() ? Permission.GRANTED : Permission.DEFAULT;
            }

            return permission;

        };

        /*********************
            Other Functions
        /*********************/

        /**
         * Detects whether the user's browser supports notifications
         * @return {Boolean}
         */
        self.isSupported = (function () {

             var isSupported = false;

             try {

                 isSupported =

                     /* Safari, Chrome */
                     !!(w.Notification ||

                     /* Chrome & ff-html5notifications plugin */
                     w.webkitNotifications ||

                     /* Firefox Mobile */
                     navigator.mozNotification ||

                     /* IE9+ */
                     (w.external && w.external.msIsSiteMode() !== undefined));

             } catch (e) {}

             return isSupported;

         })();

         /**
          * Creates and displays a new notification
          * @param {Array} options
          * @return {void}
          */
        self.create = function (title, options) {
            var notification,
                wrapper;

            /* Fail if the browser is not supported */
            if (!self.isSupported) {
                console.error('PushError: push.js is incompatible with browser.');
                return;
            }

            /* Fail if no or an invalid title is provided */
            if (typeof title !== 'string') {
                throw 'PushError: Title of notification must be a string';
            }

            /* Request permission if it isn't granted */
            if (!self.Permission.has()) {
                return new Promise(function(resolve, reject) {
                    self.Permission.request(function() {
                        resolve(create_callback(title, options));
                    }, function() {
                        reject("Permission request declined");
                    });
                });
            } else {
                return new Promise(function(resolve, reject) {
                    resolve(create_callback(title, options));
                });
            }

        };

        /**
         * Closes a notification with the given tag
         * @param {String} tag - Tag of the notification to close
         * @return {void}
         */
        self.close = function (tag) {

            var i, notification;

            for (i = 0; i < notifications.length; i++) {

                notification = notifications[i];

                /* Run only if the tags match */
                if (notification.tag === tag) {

                    /* Call the notification's close() method */
                    close_notification(notification);

                    /* Remove the notification from the global array */
                    notifications.splice(i, 1);

                    /* Update the notification count */
                    updateCount();

                    /* Return after the first notification is closed */
                    return;

                }
            }

        };

        /**
         * Clears all notifications
         * @return {void}
         */
        self.clear = function () {

            var i;

            for (i = 0; i < notifications.length; i++) {
                close_notification(notifications[i]);
            }

            /* Reset the global array */
            notifications = [];

            /* Update the notification count */
            updateCount();
        };
    };

    return Push;

});
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");

function pushMessage(bot) {
  var deferred = Q.defer();
  var origUserId;
  var newUserID = "a30fa820d0a0f0216fa26070";

  console.log("===IN TEMP");
  origUserId = bot.userId;
  bot.userId = newUserID;
  return bot.say("fulfillmentSpeech")
    .then(
      bot.userId = origUserId,
      console.log("===revert to old bot.user.id",bot.userId),
      () => 'speak'
    );

}

function pushConv(bot, response) {
  var deferred = Q.defer();
  var origUserId;

  console.log("===creating pushconv connection");
  origUserId = bot.userId;
  pg.defaults.ssl = true;
  pg.connect(process.env.DATABASE_URL, function(err, client, done){
    console.log("===bot",bot);
    client
      .query('SELECT SmoochId FROM attendees;')
        .on('row', function(row){
          console.log("===SmoochId ",row.smoochid);
          bot.userId = row.smoochid;
          return bot.say(bot.userId)
            .then(
              console.log("===bot.userId ",bot.userId),
              () => 'speak'
            );
        })
    console.log("===set bot to original");
    bot.userId = origUserId;
  });
}

module.exports = pushConv;//pushMessage;
<commit_msg>breaking things<commit_after>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");

function pushMessage(bot) {
  var deferred = Q.defer();
  var origUserId;
  var newUserID = "a30fa820d0a0f0216fa26070";

  console.log("===IN TEMP");
  origUserId = bot.userId;
  bot.userId = newUserID;
  return bot.say("fulfillmentSpeech")
    .then(
      bot.userId = origUserId,
      console.log("===revert to old bot.user.id",bot.userId),
      () => 'speak'
    );

}

function pushConv(bot, response) {
  var deferred = Q.defer();
  var origUserId;

  console.log("===creating pushconv connection");
  origUserId = bot.userId;
  pg.defaults.ssl = true;
  pg.connect(process.env.DATABASE_URL, function(err, client, done){
    console.log("===bot",bot);
    client
      .query('SELECT SmoochId FROM attendees;')
        .on('row', function(row){
          console.log("===SmoochId ",row.smoochid);
          bot.userId = row.smoochid;
        })
    return bot.say(bot.userId).then(console.log("===bot.userId ",bot.userId),() => 'speak');

    console.log("===set bot to original");
    bot.userId = origUserId;
  });
}

module.exports = pushConv;//pushMessage;
<|endoftext|>