<commit_before>/* stores the keywords */
var ENTRIES = {};

function filter(what) {
  var filters = ['freetext', 'author', 'keyword', 'year'];
  /* get filters which are set */
  var active_filters = {};
  for (var i=0,filter; filter = filters[i]; i++) {
    var val = document.getElementById(filter).value;
    if (val.length > 1) {
      active_filters[filter] = val;
    }
  }
  if (Object.keys(active_filters).length == 0) {
    BIB['ACTIVE'] = [];
    showentries();
    return;
  }
  console.log(active_filters)
  var keys = BIB['keys'];
  var actives = [];
  for (var i=0,key; key=keys[i]; i++) {
    var check = true;
    for (filter in active_filters) {
      if (filter in BIB[key] && typeof BIB[key][filter] == 'string'){
        if (BIB[key][filter].toLowerCase().indexOf(active_filters[filter].toLowerCase()) == -1) {
          check = false;
          break;
        }
      }
      else if (filter == 'keyword') {
        ENTRIES[key] = [];
        var tmp_check = false;
        var keywords = active_filters['keyword'].split(',');
        keywords = keywords.slice(0, keywords.length-1);
        var bibkeywords = [];
        for (var k=0,keyword; keyword=BIB[key]['keyword'][k]; k++) {
          bibkeywords.push(keyword.toLowerCase());
        }
        for (var k=0,keyword; keyword=keywords[k]; k++) {
          var tmp_check = false;
          if (bibkeywords.indexOf(keyword.toLowerCase().trim()) != -1) {
            tmp_check = true;
            ENTRIES[key].push(keyword);
          }
          else {
            tmp_check = false;
            break;
          }
        }
        if (!tmp_check) {
          check = false;
          break;
        }
      }
    }
    if (check) {
      actives.push(key);
    }
  }
  actives.sort(function (x, y) {
    if (BIB[x]['author'] < BIB[y]['author']) {return -1};
    if (BIB[x]['author'] > BIB[y]['author']) {return 1};
    return 0;});
  BIB['ACTIVE'] = actives;
  showentries();
}

function showCat(category) {
  BIB['ACTIVE'] = KAT[category];
  showentries();

}

function fakeAlert(text){
  var falert = document.createElement('div');
  falert.id = 'fake';
  var text = '

' + text + '
';
  text += ' OK
';
  falert.className = 'fake_alert';

  document.body.appendChild(falert);
  falert.innerHTML = text;
  document.onkeydown = function(event){$('#fake').remove();};
}

function showBibTex(key){
  fakeAlert('

BibTex Entry

'+BIB[key]['bibtex']+'

');
}

function showCategories(key){
  var kats = KAT[key].split('; ');
  var text = '

'+kats[0]+'
';
  var stack = '
';
  var level = 1;
  for (var i=1,kat; kat=kats[i]; i++) {
    var splits = kat.split('\u00a0');
    if (splits[0].split('.').length == 1) {
      text += stack;
      stack = '
';
    }
    if (level != splits[0].split('.').length) {
      text += '
';
      stack += '
';
    }
    text += '
'+splits[0] + ': ' + splits[1]+'
';
    stack += '
';
    level = splits[0].split('.').length;
  }
  fakeAlert('

Kategorien
'+text+stack+'
');
}

function showAbstract(key){
  var text = BIB[key]['abstract'];
  fakeAlert('

Abstract
'+text+'
');
}
function showKeywords(key){
  if (key in COOC) {
    var neighbors = Object.keys(COOC[key]);
  }
  else {
    var neighbors = [];
  }
  var text = '
';
  var freq = KW[key];
  var english = TRAN[key];
  neighbors.sort(function(x,y) {
    if(COOC[key][x].length < COOC[key][y].length){return 1;}
    else if(COOC[key][x].length > COOC[key][y].length){return -1;}
    else {return 0;}
  });
  for (var i=0,neighbor; neighbor=neighbors[i]; i++) {
    if (neighbor in TRAN) {
      var english = ' ('+TRAN[neighbor]+', ';
    }
    else {
      var english = ' (';
    }
    if (COOC[key][neighbor].length == 1) {
      var kook = ' Kookkurrenz';
    }
    else {
      var kook = ' Kookkurrenzen';
    }
    text += '
'+neighbor+english+COOC[key][neighbor].length+kook+')
';
    if (i > 9) {
      break;
    }
  }
  text += '
';
  fakeAlert('

Häufig mit «'+key+'» zusammen verwendete Schlagwörter:
'+text+'
');
}

function showentries() {
  var out = '';
  if (BIB['ACTIVE'].length > 0) {
    var num = BIB['ACTIVE'].length;
    out += '
'+ num +' Einträge gefunden
';
  }
  else {
    out += '
Keine Einträge gefunden.
';
  }
  for (var i=0,entry; entry=BIB['ACTIVE'][i]; i++) {
    if (entry != 'ACTIVE') {
      out += '
'+BIB[entry]['html'];
      out += '
';
      out += '';
      var kw = 0;
      var visited = [];
      if (entry in ENTRIES) {
        for (var k=0,keyword; keyword=ENTRIES[entry][k]; k++){
          out += ' '+keyword+'';
          kw += 1;
          visited.push(keyword);
        }
      }
      for (var k=0,keyword; keyword=BIB[entry]['keyword'][k]; k++) {
        if (k+kw < 6 && visited.indexOf(keyword) == -1) {
          out += ' '+keyword+'';
        }
      }
      out +='';
      out += '';
      var abs = '';
      if (typeof BIB[entry]['abstract'] != 'undefined') {
        abs = 'ABSTRACT ';
      }

      out += 'ID: '+entry+' ' + abs +
        'BIBTEX ' +
        'KATEGORIEN ';
      if ('isbn' in BIB[entry]['data']) {
        out += 'ISBN';

      }
      if ('doi' in BIB[entry]['data']) {
        out += 'DOI';
      }
      out += '
';
    }
  }
  document.getElementById('bibliography').innerHTML = out;
}

$( function() {
  var availableTags = Object.keys(KW);
  function split( val ) {
    return val.split( /,\s*/ );
  }
  function extractLast( term ) {
    return split( term ).pop();
  }

  $( "#keyword" )
    // don't navigate away from the field on tab when selecting an item
    .on( "keydown", function( event ) {
      if ( event.keyCode === $.ui.keyCode.TAB &&
          $( this ).autocomplete( "instance" ).menu.active ) {
        event.preventDefault();
      }
    })
    .autocomplete({
      minLength: 0,
      source: function( request, response ) {
        // delegate back to autocomplete, but extract the last term
        response( $.ui.autocomplete.filter(
          availableTags, extractLast( request.term ) ) );
      },
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function( event, ui ) {
        var terms = split( this.value );
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push( ui.item.value );
        // add placeholder to get the comma-and-space at the end
        terms.push( "" );
        this.value = terms.join( ", " );
        filter('keyword');
        return false;
      }
    });
} );
<commit_msg>update script<commit_after>/* stores the keywords */
var ENTRIES = {};

function filter(what) {
  var filters = ['freetext', 'author', 'keyword', 'year'];
  /* get filters which are set */
  var active_filters = {};
  for (var i=0,filter; filter = filters[i]; i++) {
    var val = document.getElementById(filter).value;
    if (val.length > 1) {
      active_filters[filter] = val;
    }
  }
  if (Object.keys(active_filters).length == 0) {
    BIB['ACTIVE'] = [];
    showentries();
    return;
  }
  console.log(active_filters)
  var keys = BIB['keys'];
  var actives = [];
  for (var i=0,key; key=keys[i]; i++) {
    var check = true;
    for (filter in active_filters) {
      if (filter in BIB[key] && typeof BIB[key][filter] == 'string'){
        if (BIB[key][filter].toLowerCase().indexOf(active_filters[filter].toLowerCase()) == -1) {
          check = false;
          break;
        }
      }
      else if (filter == 'keyword') {
        ENTRIES[key] = [];
        var tmp_check = false;
        var keywords = active_filters['keyword'].split(',');
        keywords = keywords.slice(0, keywords.length-1);
        var bibkeywords = [];
        for (var k=0,keyword; keyword=BIB[key]['keyword'][k]; k++) {
          bibkeywords.push(keyword.toLowerCase());
        }
        for (var k=0,keyword; keyword=keywords[k]; k++) {
          var tmp_check = false;
          if (bibkeywords.indexOf(keyword.toLowerCase().trim()) != -1) {
            tmp_check = true;
            ENTRIES[key].push(keyword);
          }
          else {
            tmp_check = false;
            break;
          }
        }
        if (!tmp_check) {
          check = false;
          break;
        }
      }
    }
    if (check) {
      actives.push(key);
    }
  }
  actives.sort(function (x, y) {
    if (BIB[x]['author'] < BIB[y]['author']) {return -1};
    if (BIB[x]['author'] > BIB[y]['author']) {return 1};
    return 0;});
  BIB['ACTIVE'] = actives;
  showentries();
}

function showCat(category) {
  BIB['ACTIVE'] = KAT[category];
  showentries();

}

function fakeAlert(text){
  var falert = document.createElement('div');
  falert.id = 'fake';
  var text = '

' + text + '
';
  text += ' OK
';
  falert.className = 'fake_alert';

  document.body.appendChild(falert);
  falert.innerHTML = text;
  document.onkeydown = function(event){$('#fake').remove();};
}

function showBibTex(key){
  fakeAlert('

BibTex Entry

'+BIB[key]['bibtex']+'

');
}

function showCategories(key){
  var kats = KAT[key].split('; ');
  var text = '

'+kats[0]+'
';
  var stack = '
';
  var level = 1;
  for (var i=1,kat; kat=kats[i]; i++) {
    var splits = kat.split('\u00a0');
    if (splits[0].split('.').length == 1) {
      text += stack;
      stack = '
';
    }
    if (level != splits[0].split('.').length) {
      text += '
';
      stack += '
';
    }
    text += '
'+splits[0] + ': ' + splits[1]+'
';
    stack += '
';
    level = splits[0].split('.').length;
  }
  fakeAlert('

Kategorien
'+text+stack+'
');
}

function showAbstract(key){
  var text = BIB[key]['abstract'];
  fakeAlert('

Abstract
'+text+'
');
}
function showKeywords(key){
  if (key in COOC) {
    var neighbors = Object.keys(COOC[key]);
  }
  else {
    var neighbors = [];
  }
  var text = '
';
  var freq = KW[key];
  var english = TRAN[key];
  neighbors.sort(function(x,y) {
    if(COOC[key][x].length < COOC[key][y].length){return 1;}
    else if(COOC[key][x].length > COOC[key][y].length){return -1;}
    else {return 0;}
  });
  for (var i=0,neighbor; neighbor=neighbors[i]; i++) {
    if (neighbor in TRAN) {
      var english = ' ('+TRAN[neighbor]+', ';
    }
    else {
      var english = ' (';
    }
    if (COOC[key][neighbor].length == 1) {
      var kook = ' Kookkurrenz';
    }
    else {
      var kook = ' Kookkurrenzen';
    }
    text += '
'+neighbor+english+COOC[key][neighbor].length+kook+')
';
    if (i > 9) {
      break;
    }
  }
  text += '
';
  fakeAlert('

Häufig mit «'+key+'» zusammen verwendete Schlagwörter:
'+text+'
');
}

function showentries() {
  var out = '';
  if (BIB['ACTIVE'].length > 0) {
    var num = BIB['ACTIVE'].length;
    out += '
'+ num +' Einträge gefunden
';
  }
  else {
    out += '
Keine Einträge gefunden.
';
  }
  for (var i=0,entry; entry=BIB['ACTIVE'][i]; i++) {
    if (entry != 'ACTIVE') {
      out += '
'+BIB[entry]['html'];
      out += '
';
      out += '';
      var kw = 0;
      var visited = [];
      if (entry in ENTRIES) {
        for (var k=0,keyword; keyword=ENTRIES[entry][k]; k++){
          out += ' '+keyword+'';
          kw += 1;
          visited.push(keyword);
        }
      }
      for (var k=0,keyword; keyword=BIB[entry]['keyword'][k]; k++) {
        if (k+kw < 6 && visited.indexOf(keyword) == -1) {
          out += ' '+keyword+'';
        }
      }
      out +='';
      out += '';
      var abs = '';
      if (typeof BIB[entry]['abstract'] != 'undefined') {
        abs = 'ABSTRACT ';
      }

      out += 'ID: '+entry+' ' + abs +
        'BIBTEX ' +
        'KATEGORIEN ';
      if ('isbn' in BIB[entry]['data']) {
        out += 'ISBN';

      }
      if ('doi' in BIB[entry]['data']) {
        out += 'DOI';
      }
      out += '
';
    }
  }
  document.getElementById('bibliography').innerHTML = out;
}

$( function() {
  var availableTags = Object.keys(KW);
  function split( val ) {
    return val.split( /,\s*/ );
  }
  function extractLast( term ) {
    return split( term ).pop();
  }

  $( "#keyword" )
    // don't navigate away from the field on tab when selecting an item
    .on( "keydown", function( event ) {
      if ( event.keyCode === $.ui.keyCode.TAB &&
          $( this ).autocomplete( "instance" ).menu.active ) {
        event.preventDefault();
      }
    })
    .autocomplete({
      minLength: 0,
      source: function( request, response ) {
        // delegate back to autocomplete, but extract the last term
        response( $.ui.autocomplete.filter(
          availableTags, extractLast( request.term ) ) );
      },
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function( event, ui ) {
        var terms = split( this.value );
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push( ui.item.value );
        // add placeholder to get the comma-and-space at the end
        terms.push( "" );
        this.value = terms.join( ", " );
        filter('keyword');
        return false;
      }
    });
} );

var url = window.location.href;
if (url.indexOf('?') != -1) {
  var params = url.split('?')[1];
  if (params == 'headless'){
    $('h1.main').toggle();
    document.getElementById('content').style.backgroundColor="white";
    $('body')[0].style.backgroundColor="white";
    $('.footer').toggle();

  }
}
<|endoftext|>


<commit_before>import { Projects } from '../lib/collections/projects.js';
import { Settings } from '../lib/collections/settings.js';
import { Activities } from '../lib/collections/activities.js';
import { ActivityElements } from '../lib/collections/activity_elements.js';
import { Flows } from '../lib/collections/flows.js';
import { Contradictions } from '../lib/collections/contradictions.js';
import { Discussions } from '../lib/collections/discussions.js';

// Publish users
Meteor.publish('projects', function(userId) {
    return Projects.find();
});

// Publish users
Meteor.publish('usersList', function() {
    return Meteor.users.find({}, {
        fields: {
            'emails': 1,
            'username': 1,
            'profile.firstName': 1,
            'profile.lastName': 1,
            'profile.bio': 1
        }
    });
});

// Publish users, for the tabular
Meteor.publishComposite("tabular_users", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Meteor.users.find({}, {
            fields: {
                'emails': 1,
                'username': 1,
                'roles': 1,
                'profile.firstName': 1,
                'profile.lastName': 1,
                'profile.bio': 1
            }
        });
    },
  };
});

// Publish activities, for the tabular
Meteor.publishComposite("tabular_activities", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Activities.find({}, {
            fields: {
                'id': 1,
                'contradictionData.title': 1
            }
        });
    },
  };
});

// Publish flows, for the tabular
Meteor.publishComposite("tabular_flows", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Flows.find({}, {
            fields: {
                'id': 1,
                'flowData.title': 1
            }
        });
    },
  };
});

// Publish contradictions, for the tabular
Meteor.publishComposite("tabular_contradictions", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Contradictions.find({}, {
            fields: {
                'id': 1,
                'contradictionData.title': 1
            }
        });
    },
  };
});

// Publish discussions, for the tabular
Meteor.publishComposite("tabular_discussions", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Discussions.find({}, {
            fields: {
                'id': 1,
                'attachedToDescription': 1,
                'numberOfComments': 1,
                'icon': 1
            }
        });
    },
  };
});

// Publish settings for the whole app
Meteor.publish('settings', function () {
  return Settings.find();
});

// Publish activities for the whole app
Meteor.publish('activities', function() {
    return Activities.find();
});

// Publish activity elements for the whole app
Meteor.publish('activityElements', function() {
    return ActivityElements.find();
});

// Publish flows for the whole app
Meteor.publish('flows', function() {
    return Flows.find();
});

// Publish contradictions for the whole app
Meteor.publish('contradictions', function() {
    return Contradictions.find();
});

// Publish discussions for the whole app
Meteor.publish('discussions', function() {
    return Discussions.find();
});

// Publish projects for autocomplete forms
Meteor.publish("autocompleteProjects", function(selector, options) {
  Autocomplete.publishCursor(Projects.find(selector, options), this);
  this.ready();
});

// Publish users for autocomplete forms
Meteor.publish("autocompleteUsers", function(selector, options) {
  Autocomplete.publishCursor(Meteor.users.find(selector, options), this);
  this.ready();
});

// Publish activities for autocomplete forms
Meteor.publish("autocompleteActivities", function(selector, options) {
  Autocomplete.publishCursor(Activities.find(selector, options), this);
  this.ready();
});

// Publish activity elements for autocomplete forms
Meteor.publish("autocompleteActivityElements", function(selector, options) {
  Autocomplete.publishCursor(ActivityElements.find(selector, options), this);
  this.ready();
});
<commit_msg>Fix bug in activity elements publish<commit_after>import { Projects } from '../lib/collections/projects.js';
import { Settings } from '../lib/collections/settings.js';
import { Activities } from '../lib/collections/activities.js';
import { ActivityElements } from '../lib/collections/activity_elements.js';
import { Flows } from '../lib/collections/flows.js';
import { Contradictions } from '../lib/collections/contradictions.js';
import { Discussions } from '../lib/collections/discussions.js';

// Publish users
Meteor.publish('projects', function(userId) {
    return Projects.find();
});

// Publish users
Meteor.publish('usersList', function() {
    return Meteor.users.find({}, {
        fields: {
            'emails': 1,
            'username': 1,
            'profile.firstName': 1,
            'profile.lastName': 1,
            'profile.bio': 1
        }
    });
});

// Publish users, for the tabular
Meteor.publishComposite("tabular_users", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Meteor.users.find({}, {
            fields: {
                'emails': 1,
                'username': 1,
                'roles': 1,
                'profile.firstName': 1,
                'profile.lastName': 1,
                'profile.bio': 1
            }
        });
    },
  };
});

// Publish activities, for the tabular
Meteor.publishComposite("tabular_activities", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Activities.find({}, {
            fields: {
                'id': 1,
                'contradictionData.title': 1
            }
        });
    },
  };
});

// Publish flows, for the tabular
Meteor.publishComposite("tabular_flows", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Flows.find({}, {
            fields: {
                'id': 1,
                'flowData.title': 1
            }
        });
    },
  };
});

// Publish contradictions, for the tabular
Meteor.publishComposite("tabular_contradictions", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Contradictions.find({}, {
            fields: {
                'id': 1,
                'contradictionData.title': 1
            }
        });
    },
  };
});

// Publish discussions, for the tabular
Meteor.publishComposite("tabular_discussions", function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  this.unblock(); // requires meteorhacks:unblock package

  return {
    find: function () {
      this.unblock(); // requires meteorhacks:unblock package

      return Discussions.find({}, {
            fields: {
                'id': 1,
                'attachedToDescription': 1,
                'numberOfComments': 1,
                'icon': 1
            }
        });
    },
  };
});

// Publish settings for the whole app
Meteor.publish('settings', function () {
  return Settings.find();
});

// Publish activities for the whole app
Meteor.publish('activities', function() {
    return Activities.find();
});

// Publish activity elements for the whole app
Meteor.publish('activityelements', function() {
    return ActivityElements.find();
});

// Publish flows for the whole app
Meteor.publish('flows', function() {
    return Flows.find();
});

// Publish contradictions for the whole app
Meteor.publish('contradictions', function() {
    return Contradictions.find();
});

// Publish discussions for the whole app
Meteor.publish('discussions', function() {
    return Discussions.find();
});

// Publish projects for autocomplete forms
Meteor.publish("autocompleteProjects", function(selector, options) {
  Autocomplete.publishCursor(Projects.find(selector, options), this);
  this.ready();
});

// Publish users for autocomplete forms
Meteor.publish("autocompleteUsers", function(selector, options) {
  Autocomplete.publishCursor(Meteor.users.find(selector, options), this);
  this.ready();
});

// Publish activities for autocomplete forms
Meteor.publish("autocompleteActivities", function(selector, options) {
  Autocomplete.publishCursor(Activities.find(selector, options), this);
  this.ready();
});

// Publish activity elements for autocomplete forms
Meteor.publish("autocompleteActivityElements", function(selector, options) {
  Autocomplete.publishCursor(ActivityElements.find(selector, options), this);
  this.ready();
});
<|endoftext|>


<commit_before>define([
  'angular',
  'lodash',
  'kbn',
  './queryCtrl',
],
function (angular, _, kbn) {
  'use strict';

  var module = angular.module('grafana.services');
  var tagList = null;

  module.factory('KairosDBDatasource', function($q, $http) {

    function KairosDBDatasource(datasource) {
      this.type = datasource.type;
      this.editorSrc = 'plugins/datasources/kairosdb/kairosdb.editor.html';
      this.url = datasource.url;
      this.name = datasource.name;
      this.supportMetrics = true;
      this.grafanaDB = datasource.grafanaDB;
    }

    // Called once per panel (graph)
    KairosDBDatasource.prototype.query = function(options) {
      var start = options.range.from;
      var end = options.range.to;

      var queries = _.compact(_.map(options.targets, _.partial(convertTargetToQuery, options)));
      var plotParams = _.compact(_.map(options.targets, function(target) {
        var alias = target.alias;
        if (typeof target.alias === 'undefined' || target.alias === "") {
          alias = target.metric;
        }
        return !target.hide
            ?  {alias: alias,
                exouter: target.exOuter}
            : null;
      }));
      var handleKairosDBQueryResponseAlias = _.partial(handleKairosDBQueryResponse, plotParams);
      // No valid targets, return the empty result to save a round trip.
      if (_.isEmpty(queries)) {
        var d = $q.defer();
        d.resolve({ data: [] });
        return d.promise;
      }
      return this.performTimeSeriesQuery(queries, start, end).then(handleKairosDBQueryResponseAlias,handleQueryError);
    };

    ///////////////////////////////////////////////////////////////////////
    /// Query methods
    ///////////////////////////////////////////////////////////////////////

    KairosDBDatasource.prototype.performTimeSeriesQuery = function(queries, start, end) {
      var reqBody = {
        metrics: queries
      };
      reqBody.cache_time = 0;
      convertToKairosTime(start,reqBody,'start');
      convertToKairosTime(end,reqBody,'end');
      var options = {
        method: 'POST',
        url: '/api/v1/datapoints/query',
        data: reqBody
      };

      options.url = this.url + options.url;
      return $http(options);
    };

    /**
     * Gets the list of metrics
     * @returns {*|Promise}
     */
    KairosDBDatasource.prototype.performMetricSuggestQuery = function() {
      var options = {
        url : this.url + '/api/v1/metricnames',
        method : 'GET'
      };
      return $http(options).then(function(results) {
        if (!results.data) {
          return [];
        }
        return results.data.results;
      });

    };

    KairosDBDatasource.prototype.performTagSuggestQuery = function(metricname,range,type,keyValue) {
      if (tagList && (metricname === tagList.metricName) && (range.from === tagList.range.from) &&
        (range.to === tagList.range.to)) {
        return getTagListFromResponse(tagList.results,type,keyValue);
      }
      tagList = {
        metricName:metricname,
        range:range
      };
      var body = {
        metrics : [{name : metricname}]
      };
      convertToKairosTime(range.from,body,'start');
      convertToKairosTime(range.to,body,'end');
      var options = {
        url : this.url + '/api/v1/datapoints/query/tags',
        method : 'POST',
        data : body
      };
      return $http(options).then(function(results) {
        tagList.results = results;
        return getTagListFromResponse(results,type,keyValue);
      });

    };

    /////////////////////////////////////////////////////////////////////////
    /// Formatting methods
    ////////////////////////////////////////////////////////////////////////

    function getTagListFromResponse(results,type,keyValue) {
      if (!results.data) {
        return [];
      }
      if (type === "key") {
        return _.keys(results.data.queries[0].results[0].tags);
      }
      else if (type === "value" && _.has(results.data.queries[0].results[0].tags,keyValue)) {
        return results.data.queries[0].results[0].tags[keyValue];
      }
      return [];
    }

    /**
     * Requires a verion of KairosDB with every CORS defects fixed
     * @param results
     * @returns {*}
     */
    function handleQueryError(results) {
      if (results.data.errors && !_.isEmpty(results.data.errors)) {
        var errors = {
          message: results.data.errors[0]
        };
        return $q.reject(errors);
      }
      else {
        return $q.reject(results);
      }
    }

    function handleKairosDBQueryResponse(plotParams, results) {
      var output = [];
      var index = 0;
      _.each(results.data.queries, function (series) {
        var sample_size = series.sample_size;
        console.log("sample_size:" + sample_size + " samples");

        _.each(series.results, function (result) {

          //var target = result.name;
          var target = plotParams[index].alias;
          var details = " ( ";
          _.each(result.group_by,function(element) {
            if (element.name === "tag") {
              _.each(element.group,function(value, key) {
                details += key + "=" + value + " ";
              });
            }
            else if (element.name === "value") {
              details += 'value_group=' + element.group.group_number + " ";
            }
            else if (element.name === "time") {
              details += 'time_group=' + element.group.group_number + " ";
            }
          });
          details += ") ";
          if (details !== " ( ) ") {
            target += details;
          }
          var datapoints = [];

          for (var i = 0; i < result.values.length; i++) {
            var t = Math.floor(result.values[i][0]);
            var v = result.values[i][1];
            datapoints[i] = [v, t];
          }
          if (plotParams[index].exouter) {
            datapoints = new PeakFilter(datapoints, 10);
          }
          output.push({ target: target, datapoints: datapoints });
        });
        index ++;
      });
      var output2 = { data: _.flatten(output) };

      return output2;
    }

    function convertTargetToQuery(options,target) {
      if (!target.metric || target.hide) {
        return null;
      }

      var query = {
        name: target.metric
      };

      query.aggregators = [];
      if (target.downsampling !== '(NONE)') {
        query.aggregators.push({
          name: target.downsampling,
          align_sampling: true,
          align_start_time: true,
          sampling: KairosDBDatasource.prototype.convertToKairosInterval(target.sampling || options.interval)
        });
      }
      if (target.horizontalAggregators) {
        _.each(target.horizontalAggregators,function(chosenAggregator) {
          var returnedAggregator = {
            name:chosenAggregator.name
          };
          if (chosenAggregator.sampling_rate) {
            returnedAggregator.sampling = KairosDBDatasource.prototype.convertToKairosInterval(chosenAggregator.sampling_rate);
            returnedAggregator.align_sampling = true;
            returnedAggregator.align_start_time =true;
          }
          if (chosenAggregator.unit) {
            returnedAggregator.unit = chosenAggregator.unit + 's';
          }
          if (chosenAggregator.factor && chosenAggregator.name === 'div') {
            returnedAggregator.divisor = chosenAggregator.factor;
          }
          else if (chosenAggregator.factor && chosenAggregator.name === 'scale') {
            returnedAggregator.factor = chosenAggregator.factor;
          }
          if (chosenAggregator.percentile) {
            returnedAggregator.percentile = chosenAggregator.percentile;
          }
          query.aggregators.push(returnedAggregator);
        });
      }
      if (_.isEmpty(query.aggregators)) {
        delete query.aggregators;
      }

      if (target.tags) {
        query.tags = angular.copy(target.tags);
      }

      if (target.groupByTags || target.nonTagGroupBys) {
        query.group_by = [];
        if (target.groupByTags) {query.group_by.push({name: "tag", tags: angular.copy(target.groupByTags)});}
        if (target.nonTagGroupBys) {
          _.each(target.nonTagGroupBys, function(rawGroupBy) {
            var formattedGroupBy = angular.copy(rawGroupBy);
            if (formattedGroupBy.name === 'time') {
              formattedGroupBy.range_size = KairosDBDatasource.prototype.convertToKairosInterval(formattedGroupBy.range_size);
            }
            query.group_by.push(formattedGroupBy);
          });
        }
      }
      return query;
    }

    ///////////////////////////////////////////////////////////////////////
    /// Time conversion functions specifics to KairosDB
    //////////////////////////////////////////////////////////////////////

    KairosDBDatasource.prototype.convertToKairosInterval = function(intervalString) {
      var interval_regex = /(\d+(?:\.\d+)?)([Mwdhmsy])/;
      var interval_regex_ms = /(\d+(?:\.\d+)?)(ms)/;
      var matches = intervalString.match(interval_regex_ms);
      if (!matches) {
        matches = intervalString.match(interval_regex);
      }
      if (!matches) {
        throw new Error('Invalid interval string, expecting a number followed by one of "y M w d h m s ms"');
      }

      var value = matches[1];
      var unit = matches[2];
      if (value%1 !== 0) {
        if (unit === 'ms') {throw new Error('Invalid interval value, cannot be smaller than the millisecond');}
        value = Math.round(kbn.intervals_in_seconds[unit] * value * 1000);
        unit = 'ms';

      }
      switch (unit) {
        case 'ms':
          unit = 'milliseconds';
          break;
        case 's':
          unit = 'seconds';
          break;
        case 'm':
          unit = 'minutes';
          break;
        case 'h':
          unit = 'hours';
          break;
        case 'd':
          unit = 'days';
          break;
        case 'w':
          unit = 'weeks';
          break;
        case 'M':
          unit = 'months';
          break;
        case 'y':
          unit = 'years';
          break;
        default:
          console.log("Unknown interval ", intervalString);
          break;
      }

      return {
        "value": value,
        "unit": unit
      };

    };

    function convertToKairosTime(date, response_obj, start_stop_name) {
      var name;
      if (_.isString(date)) {
        if (date === 'now') {
          return;
        }
        else if (date.indexOf('now-') >= 0) {

          name = start_stop_name + "_relative";

          date = date.substring(4);
          var re_date = /(\d+)\s*(\D+)/;
          var result = re_date.exec(date);
          if (result) {
            var value = result[1];
            var unit = result[2];
            switch (unit) {
              case 'ms':
                unit = 'milliseconds';
                break;
              case 's':
                unit = 'seconds';
                break;
              case 'm':
                unit = 'minutes';
                break;
              case 'h':
                unit = 'hours';
                break;
              case 'd':
                unit = 'days';
                break;
              case 'w':
                unit = 'weeks';
                break;
              case 'M':
                unit = 'months';
                break;
              case 'y':
                unit = 'years';
                break;
              default:
                console.log("Unknown date ", date);
                break;
            }
            response_obj[name] = {
              "value": value,
              "unit": unit
            };
            return;
          }
          console.log("Unparseable date", date);
          return;
        }
        date = kbn.parseDate(date);
      }

      if (_.isDate(date)) {
        name = start_stop_name + "_absolute";
        response_obj[name] = date.getTime();
        return;
      }

      console.log("Date is neither string nor date");
    }

    function PeakFilter(dataIn, limit) {
      var datapoints = dataIn;
      var arrLength = datapoints.length;
      if (arrLength <= 3) {
        return datapoints;
      }
      var LastIndx = arrLength - 1;

      // Check first point
      var prvDelta = Math.abs((datapoints[1][0] - datapoints[0][0]) / datapoints[0][0]);
      var nxtDelta = Math.abs((datapoints[1][0] - datapoints[2][0]) / datapoints[2][0]);
      if (prvDelta >= limit && nxtDelta < limit) {
        datapoints[0][0] = datapoints[1][0];
      }

      // Check last point
      prvDelta = Math.abs((datapoints[LastIndx - 1][0] - datapoints[LastIndx - 2][0]) / datapoints[LastIndx - 2][0]);
      nxtDelta = Math.abs((datapoints[LastIndx - 1][0] - datapoints[LastIndx][0]) / datapoints[LastIndx][0]);
      if (prvDelta >= limit && nxtDelta < limit) {
        datapoints[LastIndx][0] = datapoints[LastIndx - 1][0];
      }

      for (var i = 1; i < arrLength - 1; i++) {
        prvDelta = Math.abs((datapoints[i][0] - datapoints[i - 1][0]) / datapoints[i - 1][0]);
        nxtDelta = Math.abs((datapoints[i][0] - datapoints[i + 1][0]) / datapoints[i + 1][0]);
        if (prvDelta >= limit && nxtDelta >= limit) {
          datapoints[i][0] = (datapoints[i - 1][0] + datapoints[i + 1][0]) / 2;
        }
      }

      return datapoints;
    }

    ////////////////////////////////////////////////////////////////////////
    return KairosDBDatasource;
  });

});
<commit_msg>Fix styles around 'function'<commit_after>define([
  'angular',
  'lodash',
  'kbn',
  './queryCtrl',
],
function (angular, _, kbn) {
  'use strict';

  var module = angular.module('grafana.services');
  var tagList = null;

  module.factory('KairosDBDatasource', function($q, $http) {

    function KairosDBDatasource(datasource) {
      this.type = datasource.type;
      this.editorSrc = 'plugins/datasources/kairosdb/kairosdb.editor.html';
      this.url = datasource.url;
      this.name = datasource.name;
      this.supportMetrics = true;
      this.grafanaDB = datasource.grafanaDB;
    }

    // Called once per panel (graph)
    KairosDBDatasource.prototype.query = function(options) {
      var start = options.range.from;
      var end = options.range.to;

      var queries = _.compact(_.map(options.targets, _.partial(convertTargetToQuery, options)));
      var plotParams = _.compact(_.map(options.targets, function(target) {
        var alias = target.alias;
        if (typeof target.alias === 'undefined' || target.alias === "") {
          alias = target.metric;
        }
        return !target.hide
            ?  {alias: alias,
                exouter: target.exOuter}
            : null;
      }));
      var handleKairosDBQueryResponseAlias = _.partial(handleKairosDBQueryResponse, plotParams);
      // No valid targets, return the empty result to save a round trip.
      if (_.isEmpty(queries)) {
        var d = $q.defer();
        d.resolve({ data: [] });
        return d.promise;
      }
      return this.performTimeSeriesQuery(queries, start, end).then(handleKairosDBQueryResponseAlias,handleQueryError);
    };

    ///////////////////////////////////////////////////////////////////////
    /// Query methods
    ///////////////////////////////////////////////////////////////////////

    KairosDBDatasource.prototype.performTimeSeriesQuery = function(queries, start, end) {
      var reqBody = {
        metrics: queries
      };
      reqBody.cache_time = 0;
      convertToKairosTime(start,reqBody,'start');
      convertToKairosTime(end,reqBody,'end');
      var options = {
        method: 'POST',
        url: '/api/v1/datapoints/query',
        data: reqBody
      };

      options.url = this.url + options.url;
      return $http(options);
    };

    /**
     * Gets the list of metrics
     * @returns {*|Promise}
     */
    KairosDBDatasource.prototype.performMetricSuggestQuery = function() {
      var options = {
        url : this.url + '/api/v1/metricnames',
        method : 'GET'
      };
      return $http(options).then(function(results) {
        if (!results.data) {
          return [];
        }
        return results.data.results;
      });

    };

    KairosDBDatasource.prototype.performTagSuggestQuery = function(metricname,range,type,keyValue) {
      if (tagList && (metricname === tagList.metricName) && (range.from === tagList.range.from) &&
        (range.to === tagList.range.to)) {
        return getTagListFromResponse(tagList.results,type,keyValue);
      }
      tagList = {
        metricName:metricname,
        range:range
      };
      var body = {
        metrics : [{name : metricname}]
      };
      convertToKairosTime(range.from,body,'start');
      convertToKairosTime(range.to,body,'end');
      var options = {
        url : this.url + '/api/v1/datapoints/query/tags',
        method : 'POST',
        data : body
      };
      return $http(options).then(function(results) {
        tagList.results = results;
        return getTagListFromResponse(results,type,keyValue);
      });

    };

    /////////////////////////////////////////////////////////////////////////
    /// Formatting methods
    ////////////////////////////////////////////////////////////////////////

    function getTagListFromResponse(results,type,keyValue) {
      if (!results.data) {
        return [];
      }
      if (type === "key") {
        return _.keys(results.data.queries[0].results[0].tags);
      }
      else if (type === "value" && _.has(results.data.queries[0].results[0].tags,keyValue)) {
        return results.data.queries[0].results[0].tags[keyValue];
      }
      return [];
    }

    /**
     * Requires a verion of KairosDB with every CORS defects fixed
     * @param results
     * @returns {*}
     */
    function handleQueryError(results) {
      if (results.data.errors && !_.isEmpty(results.data.errors)) {
        var errors = {
          message: results.data.errors[0]
        };
        return $q.reject(errors);
      }
      else {
        return $q.reject(results);
      }
    }

    function handleKairosDBQueryResponse(plotParams, results) {
      var output = [];
      var index = 0;
      _.each(results.data.queries, function(series) {
        var sample_size = series.sample_size;
        console.log("sample_size:" + sample_size + " samples");

        _.each(series.results, function(result) {

          //var target = result.name;
          var target = plotParams[index].alias;
          var details = " ( ";
          _.each(result.group_by, function(element) {
            if (element.name === "tag") {
              _.each(element.group, function(value, key) {
                details += key + "=" + value + " ";
              });
            }
            else if (element.name === "value") {
              details += 'value_group=' + element.group.group_number + " ";
            }
            else if (element.name === "time") {
              details += 'time_group=' + element.group.group_number + " ";
            }
          });
          details += ") ";
          if (details !== " ( ) ") {
            target += details;
          }
          var datapoints = [];

          for (var i = 0; i < result.values.length; i++) {
            var t = Math.floor(result.values[i][0]);
            var v = result.values[i][1];
            datapoints[i] = [v, t];
          }
          if (plotParams[index].exouter) {
            datapoints = new PeakFilter(datapoints, 10);
          }
          output.push({ target: target, datapoints: datapoints });
        });
        index ++;
      });
      var output2 = { data: _.flatten(output) };

      return output2;
    }

    function convertTargetToQuery(options,target) {
      if (!target.metric || target.hide) {
        return null;
      }

      var query = {
        name: target.metric
      };

      query.aggregators = [];
      if (target.downsampling !== '(NONE)') {
        query.aggregators.push({
          name: target.downsampling,
          align_sampling: true,
          align_start_time: true,
          sampling: KairosDBDatasource.prototype.convertToKairosInterval(target.sampling || options.interval)
        });
      }
      if (target.horizontalAggregators) {
        _.each(target.horizontalAggregators, function(chosenAggregator) {
          var returnedAggregator = {
            name:chosenAggregator.name
          };
          if (chosenAggregator.sampling_rate) {
            returnedAggregator.sampling = KairosDBDatasource.prototype.convertToKairosInterval(chosenAggregator.sampling_rate);
            returnedAggregator.align_sampling = true;
            returnedAggregator.align_start_time =true;
          }
          if (chosenAggregator.unit) {
            returnedAggregator.unit = chosenAggregator.unit + 's';
          }
          if (chosenAggregator.factor && chosenAggregator.name === 'div') {
            returnedAggregator.divisor = chosenAggregator.factor;
          }
          else if (chosenAggregator.factor && chosenAggregator.name === 'scale') {
            returnedAggregator.factor = chosenAggregator.factor;
          }
          if (chosenAggregator.percentile) {
            returnedAggregator.percentile = chosenAggregator.percentile;
          }
          query.aggregators.push(returnedAggregator);
        });
      }
      if (_.isEmpty(query.aggregators)) {
        delete query.aggregators;
      }

      if (target.tags) {
        query.tags = angular.copy(target.tags);
      }

      if (target.groupByTags || target.nonTagGroupBys) {
        query.group_by = [];
        if (target.groupByTags) {query.group_by.push({name: "tag", tags: angular.copy(target.groupByTags)});}
        if (target.nonTagGroupBys) {
          _.each(target.nonTagGroupBys, function(rawGroupBy) {
            var formattedGroupBy = angular.copy(rawGroupBy);
            if (formattedGroupBy.name === 'time') {
              formattedGroupBy.range_size = KairosDBDatasource.prototype.convertToKairosInterval(formattedGroupBy.range_size);
            }
            query.group_by.push(formattedGroupBy);
          });
        }
      }
      return query;
    }

    ///////////////////////////////////////////////////////////////////////
    /// Time conversion functions specifics to KairosDB
    //////////////////////////////////////////////////////////////////////

    KairosDBDatasource.prototype.convertToKairosInterval = function(intervalString) {
      var interval_regex = /(\d+(?:\.\d+)?)([Mwdhmsy])/;
      var interval_regex_ms = /(\d+(?:\.\d+)?)(ms)/;
      var matches = intervalString.match(interval_regex_ms);
      if (!matches) {
        matches = intervalString.match(interval_regex);
      }
      if (!matches) {
        throw new Error('Invalid interval string, expecting a number followed by one of "y M w d h m s ms"');
      }

      var value = matches[1];
      var unit = matches[2];
      if (value%1 !== 0) {
        if (unit === 'ms') {throw new Error('Invalid interval value, cannot be smaller than the millisecond');}
        value = Math.round(kbn.intervals_in_seconds[unit] * value * 1000);
        unit = 'ms';

      }
      switch (unit) {
        case 'ms':
          unit = 'milliseconds';
          break;
        case 's':
          unit = 'seconds';
          break;
        case 'm':
          unit = 'minutes';
          break;
        case 'h':
          unit = 'hours';
          break;
        case 'd':
          unit = 'days';
          break;
        case 'w':
          unit = 'weeks';
          break;
        case 'M':
          unit = 'months';
          break;
        case 'y':
          unit = 'years';
          break;
        default:
          console.log("Unknown interval ", intervalString);
          break;
      }

      return {
        "value": value,
        "unit": unit
      };

    };

    function convertToKairosTime(date, response_obj, start_stop_name) {
      var name;
      if (_.isString(date)) {
        if (date === 'now') {
          return;
        }
        else if (date.indexOf('now-') >= 0) {

          name = start_stop_name + "_relative";

          date = date.substring(4);
          var re_date = /(\d+)\s*(\D+)/;
          var result = re_date.exec(date);
          if (result) {
            var value = result[1];
            var unit = result[2];
            switch (unit) {
              case 'ms':
                unit = 'milliseconds';
                break;
              case 's':
                unit = 'seconds';
                break;
              case 'm':
                unit = 'minutes';
                break;
              case 'h':
                unit = 'hours';
                break;
              case 'd':
                unit = 'days';
                break;
              case 'w':
                unit = 'weeks';
                break;
              case 'M':
                unit = 'months';
                break;
              case 'y':
                unit = 'years';
                break;
              default:
                console.log("Unknown date ", date);
                break;
            }
            response_obj[name] = {
              "value": value,
              "unit": unit
            };
            return;
          }
          console.log("Unparseable date", date);
          return;
        }
        date = kbn.parseDate(date);
      }

      if (_.isDate(date)) {
        name = start_stop_name + "_absolute";
        response_obj[name] = date.getTime();
        return;
      }

      console.log("Date is neither string nor date");
    }

    function PeakFilter(dataIn, limit) {
      var datapoints = dataIn;
      var arrLength = datapoints.length;
      if (arrLength <= 3) {
        return datapoints;
      }
      var LastIndx = arrLength - 1;

      // Check first point
      var prvDelta = Math.abs((datapoints[1][0] - datapoints[0][0]) / datapoints[0][0]);
      var nxtDelta = Math.abs((datapoints[1][0] - datapoints[2][0]) / datapoints[2][0]);
      if (prvDelta >= limit && nxtDelta < limit) {
        datapoints[0][0] = datapoints[1][0];
      }

      // Check last point
      prvDelta = Math.abs((datapoints[LastIndx - 1][0] - datapoints[LastIndx - 2][0]) / datapoints[LastIndx - 2][0]);
      nxtDelta = Math.abs((datapoints[LastIndx - 1][0] - datapoints[LastIndx][0]) / datapoints[LastIndx][0]);
      if (prvDelta >= limit && nxtDelta < limit) {
        datapoints[LastIndx][0] = datapoints[LastIndx - 1][0];
      }

      for (var i = 1; i < arrLength - 1; i++) {
        prvDelta = Math.abs((datapoints[i][0] - datapoints[i - 1][0]) / datapoints[i - 1][0]);
        nxtDelta = Math.abs((datapoints[i][0] - datapoints[i + 1][0]) / datapoints[i + 1][0]);
        if (prvDelta >= limit && nxtDelta >= limit) {
          datapoints[i][0] = (datapoints[i - 1][0] + datapoints[i + 1][0]) / 2;
        }
      }

      return datapoints;
    }

    ////////////////////////////////////////////////////////////////////////
    return KairosDBDatasource;
  });

});
<|endoftext|>


<commit_before>const _ = require('lodash')
const React = require('react')
const PropTypes = require('./prop-types')

let options
let initialized = false

const wrapPropTypes = () => {
  initialized = true
  // Adds a .type key which allows the type to be derived during the
  // evaluation process. This is necessary for complex types which
  // return the result of a generator function, leaving no way to
  // determine which type instantiated it.

  const original = _.cloneDeep(PropTypes)

  _.each(PropTypes, (v, k) => {
    if (v.isRequired !== undefined) {
      // Simple type. Just extend the object
      _.defaultsDeep(PropTypes[k], { type: k, isRequired: { type: k } })
    } else {
      // Complex type. Must extend the creator's return value
      PropTypes[k] = (arg) =>
        _.defaultsDeep(original[k](arg), {
          type: k, arg: arg,
          isRequired: { type: k, arg: arg }
        })
    }
  })
}

const GENERATORS = {
  // Simple types
  array: (propName) => [propName],
  bool: () => true,
  func: () => () => {},
  number: () => 1,
  object: (propName) => ({ [propName]: propName }),
  string: (propName) => propName,
  any: (propName) => propName,
  element: (propName) => React.createElement('div', propName),
  node: (propName) => propName,

  // Complex types
  arrayOf: (propName, type) => [generateOneProp(type, propName, false)],
  instanceOf: (propName, klass) => new klass(),
  objectOf: (propName, type) => ({ key: generateOneProp(type, propName, false) }),
  oneOf: (propName, values) => _.first(values),
  oneOfType: (propName, types) => forceGenerateOneProp(_.first(types), propName),
  shape: (propName, shape) => generateProps(shape, options)
}

const shouldGenerate = (propType) => {
  return (
    // Generate required props, and this is the required version
    (options.required && !propType.isRequired) ||
    // Generate optional props, and this is the optional version
    (options.optional && !!propType.isRequired)
  )
}

const initError = new Error(
  'generateProps.init() must be called at the beginning of your test suite'
)

const generateOneProp = (propType, propName, wrapInArray = true) => {
  if (propType.type === undefined && initialized === false) {
    throw initError
  }

  const generate = options.generators[propType.type].bind(this, propName)
  const arg = propType.arg
  if (generate) {
    if (shouldGenerate(propType)) {
      if (wrapInArray) {
        return [propName, generate(arg)]
      } else {
        return generate(arg)
      }
    }
  }
}

const forceGenerateOneProp = (propType, propName) => {
  const generate = GENERATORS[propType.type].bind(this, propName)
  const arg = propType.arg
  if (generate) {
    return generate(arg)
  }
}

const generateProps = (arg, opts) => {
  if (initialized === false) {
    throw initError
  }

  options = _.defaults({}, opts, { required: true, optional: false })
  if (opts && opts.generators) {
    options.generators = _.defaults({}, opts.generators, GENERATORS)
  } else {
    options.generators = GENERATORS
  }

  let propTypes

  if (!arg) {
    throw new TypeError('generateProps expected a propType object or a React Component')
  } else if (_.isPlainObject(arg.propTypes)) {
    propTypes = arg.propTypes
  } else if (_.isPlainObject(arg)) {
    propTypes = arg
  } else {
    throw new TypeError('generateProps expected a propType object or a React Component')
  }

  return _(propTypes)
    .map(generateOneProp)
    .compact()
    .fromPairs()
    .value()
}

Object.assign(generateProps, { init: wrapPropTypes })

module.exports = generateProps
<commit_msg>Improve "empty" generated results when no propName<commit_after>const _ = require('lodash')
const React = require('react')
const PropTypes = require('./prop-types')

let options
let initialized = false

const wrapPropTypes = () => {
  initialized = true
  // Adds a .type key which allows the type to be derived during the
  // evaluation process. This is necessary for complex types which
  // return the result of a generator function, leaving no way to
  // determine which type instantiated it.

  const original = _.cloneDeep(PropTypes)

  _.each(PropTypes, (v, k) => {
    if (v.isRequired !== undefined) {
      // Simple type. Just extend the object
      _.defaultsDeep(PropTypes[k], { type: k, isRequired: { type: k } })
    } else {
      // Complex type. Must extend the creator's return value
      PropTypes[k] = (arg) =>
        _.defaultsDeep(original[k](arg), {
          type: k, arg: arg,
          isRequired: { type: k, arg: arg }
        })
    }
  })
}

const GENERATORS = {
  // Simple types
  array: (propName) => propName ? [propName] : [],
  bool: () => true,
  func: () => () => {},
  number: () => 1,
  object: (propName) => propName ? ({ [propName]: propName }): {},
  string: (propName) => propName || 'string',
  any: (propName) => propName || 'any',
  element: (propName) => React.createElement('div', propName),
  node: (propName) => propName || 'node',

  // Complex types
  arrayOf: (propName, type) => {
    const res = generateOneProp(type, propName, false)
    return res ? [res] : []
  },
  instanceOf: (propName, klass) => new klass(),
  objectOf: (propName, type) => ({ key: generateOneProp(type, propName, false) }),
  oneOf: (propName, values) => _.first(values),
  oneOfType: (propName, types) => forceGenerateOneProp(_.first(types), propName),
  shape: (propName, shape) => generateProps(shape, options)
}

const shouldGenerate = (propType) => {
  return (
    // Generate required props, and this is the required version
    (options.required && !propType.isRequired) ||
    // Generate optional props, and this is the optional version
    (options.optional && !!propType.isRequired)
  )
}

const initError = new Error(
  'generateProps.init() must be called at the beginning of your test suite'
)

const generateOneProp = (propType, propName, wrapInArray = true) => {
  if (propType.type === undefined && initialized === false) {
    throw initError
  }

  const generate = options.generators[propType.type].bind(this, propName)
  const arg = propType.arg
  if (generate) {
    if (shouldGenerate(propType)) {
      if (wrapInArray) {
        return [propName, generate(arg)]
      } else {
        return generate(arg)
      }
    }
  }
}

const forceGenerateOneProp = (propType, propName) => {
  const generate = GENERATORS[propType.type].bind(this, propName)
  const arg = propType.arg
  if (generate) {
    return generate(arg)
  }
}

const generateProps = (arg, opts) => {
  if (initialized === false) {
    throw initError
  }

  options = _.defaults({}, opts, { required: true, optional: false })
  if (opts && opts.generators) {
    options.generators = _.defaults({}, opts.generators, GENERATORS)
  } else {
    options.generators = GENERATORS
  }

  let propTypes

  if (!arg) {
    throw new TypeError('generateProps expected a propType object or a React Component')
  } else if (_.isPlainObject(arg.propTypes)) {
    propTypes = arg.propTypes
  } else if (_.isPlainObject(arg)) {
    propTypes = arg
  } else {
    throw new TypeError('generateProps expected a propType object or a React Component')
  }

  return _(propTypes)
    .map(generateOneProp)
    .compact()
    .fromPairs()
    .value()
}

Object.assign(generateProps, { init: wrapPropTypes })

module.exports = generateProps
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = requir<commit_msg>Really commit all the required changes<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = <|endoftext|>


<commit_before>// A passthrough read/write stream that sets its properties
// based on a header, extendedHeader, and globalHeader
//
// Can be either a file system object of some sort, or
// a pax/ustar metadata entry.

module.exports = Entry

var TarHeader = require("./header.js")
  , tar = require("../tar")
  , assert = require("assert").ok
  , Stream = require("stream").Stream
  , inherits = require("inherits")
  , fstream = require("fstream").Abstract

function Entry (header, extended, global) {
  Stream.call(this)
  this.readable = true
  this.writable = true

  this._needDrain = false
  this._paused = false
  this._reading = false
  this._ending = false
  this._ended = false
  this._remaining = 0
  this._queue = []
  this._index = 0
  this._queueLen = 0

  this._read = this._read.bind(this)

  this.props = {}
  this._header = header
  this._extended = extended || {}

  // globals can change throughout the course of
  // a file parse operation.  Freeze it at its current state.
  this._global = {}
  var me = this
  Object.keys(global || {}).forEach(function (g) {
    me._global[g] = global[g]
  })

  this._setProps()
}

inherits(Entry, Stream,
{ write: function (c) {
    if (this._ending) this.error("write() after end()", null, true)
    if (this._remaining === 0) {
      this.error("invalid bytes past eof")
    }

    // often we'll get a bunch of \0 at the end of the last write,
    // since chunks will always be 512 bytes when reading a tarball.
    if (c.length > this._remaining) {
      c = c.slice(0, this._remaining)
    }
    this._remaining -= c.length

    // put it on the stack.
    var ql = this._queueLen
    this._queue.push(c)
    this._queueLen ++

    this._read()

    // either paused, or buffered
    if (this._paused || ql > 0) {
      this._needDrain = true
      return false
    }

    return true
  }

, end: function (c) {
    if (c) this.write(c)
    this._ending = true
    this._read()
  }

, pause: function () {
    this._paused = true
    this.emit("pause")
  }

, resume: function () {
    // console.error("    Tar Entry resume", this.path)
    this.emit("resume")
    this._paused = false
    this._read()
    return this._queueLen - this._index > 1
  }

  // This is bound to the instance
, _read: function () {
    // console.error("    Tar Entry _read", this.path)

    if (this._paused || this._reading || this._ended) return

    // set this flag so that event handlers don't inadvertently
    // get multiple _read() calls running.
    this._reading = true

    // have any data to emit?
    if (this._index < this._queueLen) {
      var chunk = this._queue[this._index ++]
      this.emit("data", chunk)
    }

    // check if we're drained
    if (this._index >= this._queueLen) {
      this._queue.length = this._queueLen = this._index = 0
      if (this._needDrain) {
        this._needDrain = false
        this.emit("drain")
      }
      if (this._ending) {
        this._ended = true
        this.emit("end")
      }
    }

    // if the queue gets too big, then pluck off whatever we can.
    // this should be fairly rare.
    var mql = this._maxQueueLen
    if (this._queueLen > mql && this._index > 0) {
      mql = Math.min(this._index, mql)
      this._index -= mql
      this._queueLen -= mql
      this._queue = this._queue.slice(mql)
    }

    this._reading = false
  }

, _setProps: function () {
    // props = extended->global->header->{}
    var header = this._header
      , extended = this._extended
      , global = this._global
      , props = this.props

    // first get the values from the normal header.
    var fields = tar.fields
    for (var f = 0; fields[f] !== null; f ++) {
      var field = fields[f]
        , val = header[field]
      if (typeof val !== "undefined") props[field] = val
    }

    // next, the global header for this file.
    // numeric values, etc, will have already been parsed.
    ;[global, extended].forEach(function (p) {
      Object.keys(p).forEach(function (f) {
        if (typeof p[f] !== "undefined") props[f] = p[f]
      })
    })

    // no nulls allowed in path or linkpath
    ;["path", "linkpath"].forEach(function (p) {
      if (props.hasOwnProperty(p)) {
        props[p] = props[p].split("\0")[0]
      }
    })

    // set date fields to be a proper date
    ;["mtime", "ctime", "atime"].forEach(function (p) {
      if (props.hasOwnProperty(p)) {
        props[p] = new Date(props[p] * 1000)
      }
    })

    // set the type so that we know what kind of file to create
    var type
    switch (tar.types[props.type]) {
      case "OldFile":
      case "ContiguousFile":
        type = "File"
        break

      case "GNUDumpDir":
        type = "Directory"
        break

      case undefined:
        type = "Unknown"
        break

      case "Link":
      case "SymbolicLink":
      case "CharacterDevice":
      case "BlockDevice":
      case "Directory":
      case "FIFO":
      default:
        type = tar.types[props.type]
    }

    this.type = type
    this.path = props.path
    this.size = props.size

    // size is special, since it signals when the file needs to end.
    this._remaining = props.size
  }
, warn: fstream.warn
, error: fstream.error
})
<commit_msg>Handle case where more than one thing can get in the queue<commit_after>// A passthrough read/write stream that sets its properties
// based on a header, extendedHeader, and globalHeader
//
// Can be either a file system object of some sort, or
// a pax/ustar metadata entry.

module.exports = Entry

var TarHeader = require("./header.js")
  , tar = require("../tar")
  , assert = require("assert").ok
  , Stream = require("stream").Stream
  , inherits = require("inherits")
  , fstream = require("fstream").Abstract

function Entry (header, extended, global) {
  Stream.call(this)
  this.readable = true
  this.writable = true

  this._needDrain = false
  this._paused = false
  this._reading = false
  this._ending = false
  this._ended = false
  this._remaining = 0
  this._queue = []
  this._index = 0
  this._queueLen = 0

  this._read = this._read.bind(this)

  this.props = {}
  this._header = header
  this._extended = extended || {}

  // globals can change throughout the course of
  // a file parse operation.  Freeze it at its current state.
  this._global = {}
  var me = this
  Object.keys(global || {}).forEach(function (g) {
    me._global[g] = global[g]
  })

  this._setProps()
}

inherits(Entry, Stream,
{ write: function (c) {
    if (this._ending) this.error("write() after end()", null, true)
    if (this._remaining === 0) {
      this.error("invalid bytes past eof")
    }

    // often we'll get a bunch of \0 at the end of the last write,
    // since chunks will always be 512 bytes when reading a tarball.
    if (c.length > this._remaining) {
      c = c.slice(0, this._remaining)
    }
    this._remaining -= c.length

    // put it on the stack.
    var ql = this._queueLen
    this._queue.push(c)
    this._queueLen ++

    this._read()

    // either paused, or buffered
    if (this._paused || ql > 0) {
      this._needDrain = true
      return false
    }

    return true
  }

, end: function (c) {
    if (c) this.write(c)
    this._ending = true
    this._read()
  }

, pause: function () {
    this._paused = true
    this.emit("pause")
  }

, resume: function () {
    // console.error("    Tar Entry resume", this.path)
    this.emit("resume")
    this._paused = false
    this._read()
    return this._queueLen - this._index > 1
  }

  // This is bound to the instance
, _read: function () {
    // console.error("    Tar Entry _read", this.path)

    if (this._paused || this._reading || this._ended) return

    // set this flag so that event handlers don't inadvertently
    // get multiple _read() calls running.
    this._reading = true

    // have any data to emit?
    while (this._index < this._queueLen && !this._paused) {
      var chunk = this._queue[this._index ++]
      this.emit("data", chunk)
    }

    // check if we're drained
    if (this._index >= this._queueLen) {
      this._queue.length = this._queueLen = this._index = 0
      if (this._needDrain) {
        this._needDrain = false
        this.emit("drain")
      }
      if (this._ending) {
        this._ended = true
        this.emit("end")
      }
    }

    // if the queue gets too big, then pluck off whatever we can.
    // this should be fairly rare.
    var mql = this._maxQueueLen
    if (this._queueLen > mql && this._index > 0) {
      mql = Math.min(this._index, mql)
      this._index -= mql
      this._queueLen -= mql
      this._queue = this._queue.slice(mql)
    }

    this._reading = false
  }

, _setProps: function () {
    // props = extended->global->header->{}
    var header = this._header
      , extended = this._extended
      , global = this._global
      , props = this.props

    // first get the values from the normal header.
    var fields = tar.fields
    for (var f = 0; fields[f] !== null; f ++) {
      var field = fields[f]
        , val = header[field]
      if (typeof val !== "undefined") props[field] = val
    }

    // next, the global header for this file.
    // numeric values, etc, will have already been parsed.
    ;[global, extended].forEach(function (p) {
      Object.keys(p).forEach(function (f) {
        if (typeof p[f] !== "undefined") props[f] = p[f]
      })
    })

    // no nulls allowed in path or linkpath
    ;["path", "linkpath"].forEach(function (p) {
      if (props.hasOwnProperty(p)) {
        props[p] = props[p].split("\0")[0]
      }
    })

    // set date fields to be a proper date
    ;["mtime", "ctime", "atime"].forEach(function (p) {
      if (props.hasOwnProperty(p)) {
        props[p] = new Date(props[p] * 1000)
      }
    })

    // set the type so that we know what kind of file to create
    var type
    switch (tar.types[props.type]) {
      case "OldFile":
      case "ContiguousFile":
        type = "File"
        break

      case "GNUDumpDir":
        type = "Directory"
        break

      case undefined:
        type = "Unknown"
        break

      case "Link":
      case "SymbolicLink":
      case "CharacterDevice":
      case "BlockDevice":
      case "Directory":
      case "FIFO":
      default:
        type = tar.types[props.type]
    }

    this.type = type
    this.path = props.path
    this.size = props.size

    // size is special, since it signals when the file needs to end.
    this._remaining = props.size
  }
, warn: fstream.warn
, error: fstream.error
})
<|endoftext|>


<commit_before>(function () {

    me.CanvasRenderer = (function () {
        var api = {},
        canvas = null,
        context = null,
        doubleBuffering = null,
        backBufferCanvas = null,
        backBufferContext2D = null,
        gameHeightZoom = 0,
        gameWidthZoom = 0;

        api.init = function (c, db) {
            canvas = c;
            context = this.getContext2d(canvas);
            doubleBuffering = db;

            // create the back buffer if we use double buffering
            if (doubleBuffering) {
                backBufferCanvas = me.video.createCanvas(canvas.width, canvas.height, false);
                backBufferContext2D = this.getContext2d(backBufferCanvas);
            }
            else {
                backBufferCanvas = canvas;
                backBufferContext2D = context;
            }

            return this;
        };

        api.applyRGBFilter = function (object, effect, option) {
            //create a output canvas using the given canvas or image size
            var _context = api.getContext2d(me.video.createCanvas(object.width, object.height, false));
            // get the pixels array of the give parameter
            var imgpix = me.utils.getPixels(object);
            // pointer to the pixels data
            var pix = imgpix.data;

            // apply selected effect
            var i, n;
            switch (effect) {
                case "b&w":
                    for (i = 0, n = pix.length; i < n; i += 4) {
                        var grayscale = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) >>> 3;
                        pix[i] = grayscale; // red
                        pix[i + 1] = grayscale; // green
                        pix[i + 2] = grayscale; // blue
                    }
                    break;

                case "brightness":
                    // make sure it's between 0.0 and 1.0
                    var brightness = Math.abs(option).clamp(0.0, 1.0);
                    for (i = 0, n = pix.length; i < n; i += 4) {

                        pix[i] *= brightness; // red
                        pix[i + 1] *= brightness; // green
                        pix[i + 2] *= brightness; // blue
                    }
                    break;

                case "transparent":
                    var refColor = me.pool.pull("me.Color").parseHex(option);
                    var pixel = me.pool.pull("me.Color");
                    for (i = 0, n = pix.length; i < n; i += 4) {
                        pixel.setColor(pix[i], pix[i + 1], pix[i + 2]);
                        if (pixel.equals(refColor)) {
                            pix[i + 3] = 0;
                        }
                    }
                    me.pool.push(refColor);
                    me.pool.push(pixel);

                    break;

                default:
                    return null;
            }

            // put our modified image back in the new filtered canvas
            _context.putImageData(imgpix, 0, 0);

            // return it
            return _context;
        };

        /**
         * render the main framebuffer on screen
         * @name blitSurface
         * @memberOf me.video
         * @function
         */
        api.blitSurface = function () {
            if (doubleBuffering) {
                /** @ignore */
                api.blitSurface = function () {
                    //FPS.update();
                    context.drawImage(
                        backBufferCanvas, 0, 0,
                        backBufferCanvas.width, backBufferCanvas.height, 0,
                        0, gameWidthZoom, gameHeightZoom
                    );

                };
            }
            else {
                // "empty" function, as we directly render stuff on "context2D"
                /** @ignore */
                api.blitSurface = function () {
                };
            }
            api.blitSurface();
        };

        /**
         * Clear the specified context with the given color
         * @name clearSurface
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Context2d} canvas contest. Optional, will default to system context.
         * @param {String} color a CSS color string
         */
        api.clearSurface = function (ctx, col) {
            if (ctx === null) {
                ctx = context;
            }
            var _canvas = ctx.canvas;
            ctx.save();
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.fillStyle = col;
            ctx.fillRect(0, 0, _canvas.width, _canvas.height);
            ctx.restore();
        };

        /**
         * Draw an image using the canvas api
         * @name drawImage
         * @memberOf me.CanvasRenderer
         * @function
         * @param {image} an html image element
         * @param {Number} offsetX value, from the source image.
         * @param {Number} offsetY value, from the source image.
         * @param {Number} imageWidth the width of the image to be drawn
         * @param {Number} imageHeight the height of the image to be drawn
         * @param {Number} destX the x position to draw the image at on the screen
         * @param {Number} destY the y position to draw the image at on the screen
         * @param {Number} destW the width value to draw the image at on the screen
         * @param {Number} destH the height value to draw the image at on the screen
         */
        api.drawImage = function (image, offsetX, offsetY, imageWidth, imageHeight, destX, destY, destW, destH) {
            context.drawImage(image, offsetX, offsetY, imageWidth, imageHeight, destX, destY, destW, destH);
        };

        /**
         * Draw a filled rectangle at the specified coordinates with a given color
         * @name drawRectWithColor
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x position
         * @param {Number} y position
         * @param {Number} width to draw
         * @param {Number} height to draw
         * @param {String} css color for the rectangle
         */
        api.drawRectWithColor = function (x, y, width, height, color) {
            context.fillStyle = color;
            context.fillRect(x, y, width, height);
        };

        /**
         * return a reference to the screen canvas corresponding 2d Context

         * (will return buffered context if double buffering is enabled, or a reference to the Screen Context)
         * @name getScreenContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getScreenContext = function () {
            return context;
        };

        /**
         * Returns the 2D Context instance for the renderer
         * @name getContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getContext = function () {
            return context;
        };

        /**
         * Returns the 2D Context object of the given Canvas
         * `getContext2d` will also enable/disable antialiasing features based on global settings.
         * @name getContext2D
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Canvas}
         * @return {Context2d}
         */
        api.getContext2d = function (canvas) {
            var _context;
            if (navigator.isCocoonJS) {
                // cocoonJS specific extension
                _context = canvas.getContext("2d", {
                    "antialias" : me.sys.scalingInterpolation
                });
            }
            else {
                _context = canvas.getContext("2d");
            }
            if (!_context.canvas) {
                _context.canvas = canvas;
            }
            this.setImageSmoothing(_context, me.sys.scalingInterpolation);
            return _context;
        };

        /**
         * return a reference to the system canvas
         * @name getSystemCanvas
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Canvas}
         */
        api.getSystemCanvas = function () {
            return backBufferCanvas;
        };

        /**
         * return a reference to the system 2d Context
         * @name getSystemContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getSystemContext = function () {
            return backBufferContext2D;
        };

        /**
         * return the current global alpha
         * @name globalAlpha
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Number}
         */
        api.globalAlpha = function () {
            return context.globalAlpha;
        };

        /**
         * resets the canvas transform to identity
         * @name resetTransform
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.resetTransform = function () {
            context.setTransform(1, 0, 0, 1, 0, 0);
        };

        api.resize = function (scaleX, scaleY) {
            gameWidthZoom = backBufferCanvas.width * scaleX;
            gameHeightZoom = backBufferCanvas.height * scaleY;
            canvas.width = gameWidthZoom;
            canvas.height = gameHeightZoom;

            // adjust CSS style for High-DPI devices
            if (me.device.getPixelRatio() > 1) {
                canvas.style.width = (canvas.width / me.device.getPixelRatio()) + "px";
                canvas.style.height = (canvas.height / me.device.getPixelRatio()) + "px";
            }
            this.setImageSmoothing(context, me.sys.scalingInterpolation);
            this.blitSurface();
        };

        /**
         * restores the canvas context
         * @name restore
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.restore = function () {
            context.restore();
        };

        /**
         * rotates the canvas context
         * @name rotate
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} angle in radians
         */
        api.rotate = function (angle) {
            context.rotate(angle);
        };

        /**
         * save the canvas context
         * @name save
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.save = function () {
            context.save();
        };

        /**
         * scales the canvas context
         * @name scale
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x
         * @param {Number} y
         */
        api.scale = function (x, y) {
            context.scale(x, y);
        };

        api.setAlpha = function (enable) {
            context.globalCompositeOperation = enable ? "source-over" : "copy";
        };

        /**
         * Sets the global alpha on the canvas context
         * @name setGlobalAlpha
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} alpha value. 0.0 to 1.0 values accepted.
         */
        api.setGlobalAlpha = function (a) {
            context.globalAlpha = a;
        };

        /**
         * enable/disable image smoothing (scaling interpolation) for the specified 2d Context

         * (!) this might not be supported by all browsers

         * @name setImageSmoothing
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Context2d} context
         * @param {Boolean} [enable=false]
         */
        api.setImageSmoothing = function (context, enable) {
            me.agent.setPrefixed("imageSmoothingEnabled", enable === true, context);
        };

        /**
         * transforms the context. Accepts any number of integer arguments
         * @name transform
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.transform = function () {
            context.transform.apply(context, arguments);
        };

        /**
         * Translates the context to the given position
         * @name translate
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x
         * @param {Number} y
         */
        api.translate = function (x, y) {
            context.translate(x, y);
        };

        return api;
    })();

})();<commit_msg>initialize widthzoom variables correctly<commit_after>(function () {

    me.CanvasRenderer = (function () {
        var api = {},
        canvas = null,
        context = null,
        doubleBuffering = null,
        backBufferCanvas = null,
        backBufferContext2D = null,
        gameHeightZoom = 0,
        gameWidthZoom = 0;

        api.init = function (c, db) {
            canvas = c;
            context = this.getContext2d(canvas);
            doubleBuffering = db;

            // create the back buffer if we use double buffering
            if (doubleBuffering) {
                backBufferCanvas = me.video.createCanvas(canvas.width, canvas.height, false);
                backBufferContext2D = this.getContext2d(backBufferCanvas);
            }
            else {
                backBufferCanvas = canvas;
                backBufferContext2D = context;
            }

            gameWidthZoom = canvas.width;
            gameHeightZoom = canvas.height;

            return this;
        };

        api.applyRGBFilter = function (object, effect, option) {
            //create a output canvas using the given canvas or image size
            var _context = api.getContext2d(me.video.createCanvas(object.width, object.height, false));
            // get the pixels array of the give parameter
            var imgpix = me.utils.getPixels(object);
            // pointer to the pixels data
            var pix = imgpix.data;

            // apply selected effect
            var i, n;
            switch (effect) {
                case "b&w":
                    for (i = 0, n = pix.length; i < n; i += 4) {
                        var grayscale = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) >>> 3;
                        pix[i] = grayscale; // red
                        pix[i + 1] = grayscale; // green
                        pix[i + 2] = grayscale; // blue
                    }
                    break;

                case "brightness":
                    // make sure it's between 0.0 and 1.0
                    var brightness = Math.abs(option).clamp(0.0, 1.0);
                    for (i = 0, n = pix.length; i < n; i += 4) {

                        pix[i] *= brightness; // red
                        pix[i + 1] *= brightness; // green
                        pix[i + 2] *= brightness; // blue
                    }
                    break;

                case "transparent":
                    var refColor = me.pool.pull("me.Color").parseHex(option);
                    var pixel = me.pool.pull("me.Color");
                    for (i = 0, n = pix.length; i < n; i += 4) {
                        pixel.setColor(pix[i], pix[i + 1], pix[i + 2]);
                        if (pixel.equals(refColor)) {
                            pix[i + 3] = 0;
                        }
                    }
                    me.pool.push(refColor);
                    me.pool.push(pixel);

                    break;

                default:
                    return null;
            }

            // put our modified image back in the new filtered canvas
            _context.putImageData(imgpix, 0, 0);

            // return it
            return _context;
        };

        /**
         * render the main framebuffer on screen
         * @name blitSurface
         * @memberOf me.video
         * @function
         */
        api.blitSurface = function () {
            if (doubleBuffering) {
                /** @ignore */
                api.blitSurface = function () {
                    //FPS.update();
                    context.drawImage(
                        backBufferCanvas, 0, 0,
                        backBufferCanvas.width, backBufferCanvas.height, 0,
                        0, gameWidthZoom, gameHeightZoom
                    );

                };
            }
            else {
                // "empty" function, as we directly render stuff on "context2D"
                /** @ignore */
                api.blitSurface = function () {
                };
            }
            api.blitSurface();
        };

        /**
         * Clear the specified context with the given color
         * @name clearSurface
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Context2d} canvas contest. Optional, will default to system context.
         * @param {String} color a CSS color string
         */
        api.clearSurface = function (ctx, col) {
            if (ctx === null) {
                ctx = context;
            }
            var _canvas = ctx.canvas;
            ctx.save();
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.fillStyle = col;
            ctx.fillRect(0, 0, _canvas.width, _canvas.height);
            ctx.restore();
        };

        /**
         * Draw an image using the canvas api
         * @name drawImage
         * @memberOf me.CanvasRenderer
         * @function
         * @param {image} an html image element
         * @param {Number} offsetX value, from the source image.
         * @param {Number} offsetY value, from the source image.
         * @param {Number} imageWidth the width of the image to be drawn
         * @param {Number} imageHeight the height of the image to be drawn
         * @param {Number} destX the x position to draw the image at on the screen
         * @param {Number} destY the y position to draw the image at on the screen
         * @param {Number} destW the width value to draw the image at on the screen
         * @param {Number} destH the height value to draw the image at on the screen
         */
        api.drawImage = function (image, offsetX, offsetY, imageWidth, imageHeight, destX, destY, destW, destH) {
            context.drawImage(image, offsetX, offsetY, imageWidth, imageHeight, destX, destY, destW, destH);
        };

        /**
         * Draw a filled rectangle at the specified coordinates with a given color
         * @name drawRectWithColor
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x position
         * @param {Number} y position
         * @param {Number} width to draw
         * @param {Number} height to draw
         * @param {String} css color for the rectangle
         */
        api.drawRectWithColor = function (x, y, width, height, color) {
            context.fillStyle = color;
            context.fillRect(x, y, width, height);
        };

        /**
         * return a reference to the screen canvas corresponding 2d Context

         * (will return buffered context if double buffering is enabled, or a reference to the Screen Context)
         * @name getScreenContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getScreenContext = function () {
            return context;
        };

        /**
         * Returns the 2D Context instance for the renderer
         * @name getContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getContext = function () {
            return context;
        };

        /**
         * Returns the 2D Context object of the given Canvas
         * `getContext2d` will also enable/disable antialiasing features based on global settings.
         * @name getContext2D
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Canvas}
         * @return {Context2d}
         */
        api.getContext2d = function (canvas) {
            var _context;
            if (navigator.isCocoonJS) {
                // cocoonJS specific extension
                _context = canvas.getContext("2d", {
                    "antialias" : me.sys.scalingInterpolation
                });
            }
            else {
                _context = canvas.getContext("2d");
            }
            if (!_context.canvas) {
                _context.canvas = canvas;
            }
            this.setImageSmoothing(_context, me.sys.scalingInterpolation);
            return _context;
        };

        /**
         * return a reference to the system canvas
         * @name getSystemCanvas
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Canvas}
         */
        api.getSystemCanvas = function () {
            return backBufferCanvas;
        };

        /**
         * return a reference to the system 2d Context
         * @name getSystemContext
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Context2d}
         */
        api.getSystemContext = function () {
            return backBufferContext2D;
        };

        /**
         * return the current global alpha
         * @name globalAlpha
         * @memberOf me.CanvasRenderer
         * @function
         * @return {Number}
         */
        api.globalAlpha = function () {
            return context.globalAlpha;
        };

        /**
         * resets the canvas transform to identity
         * @name resetTransform
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.resetTransform = function () {
            context.setTransform(1, 0, 0, 1, 0, 0);
        };

        api.resize = function (scaleX, scaleY) {
            gameWidthZoom = backBufferCanvas.width * scaleX;
            gameHeightZoom = backBufferCanvas.height * scaleY;
            canvas.width = gameWidthZoom;
            canvas.height = gameHeightZoom;

            // adjust CSS style for High-DPI devices
            if (me.device.getPixelRatio() > 1) {
                canvas.style.width = (canvas.width / me.device.getPixelRatio()) + "px";
                canvas.style.height = (canvas.height / me.device.getPixelRatio()) + "px";
            }
            this.setImageSmoothing(context, me.sys.scalingInterpolation);
            this.blitSurface();
        };

        /**
         * restores the canvas context
         * @name restore
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.restore = function () {
            context.restore();
        };

        /**
         * rotates the canvas context
         * @name rotate
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} angle in radians
         */
        api.rotate = function (angle) {
            context.rotate(angle);
        };

        /**
         * save the canvas context
         * @name save
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.save = function () {
            context.save();
        };

        /**
         * scales the canvas context
         * @name scale
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x
         * @param {Number} y
         */
        api.scale = function (x, y) {
            context.scale(x, y);
        };

        api.setAlpha = function (enable) {
            context.globalCompositeOperation = enable ? "source-over" : "copy";
        };

        /**
         * Sets the global alpha on the canvas context
         * @name setGlobalAlpha
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} alpha value. 0.0 to 1.0 values accepted.
         */
        api.setGlobalAlpha = function (a) {
            context.globalAlpha = a;
        };

        /**
         * enable/disable image smoothing (scaling interpolation) for the specified 2d Context

         * (!) this might not be supported by all browsers

         * @name setImageSmoothing
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Context2d} context
         * @param {Boolean} [enable=false]
         */
        api.setImageSmoothing = function (context, enable) {
            me.agent.setPrefixed("imageSmoothingEnabled", enable === true, context);
        };

        /**
         * transforms the context. Accepts any number of integer arguments
         * @name transform
         * @memberOf me.CanvasRenderer
         * @function
         */
        api.transform = function () {
            context.transform.apply(context, arguments);
        };

        /**
         * Translates the context to the given position
         * @name translate
         * @memberOf me.CanvasRenderer
         * @function
         * @param {Number} x
         * @param {Number} y
         */
        api.translate = function (x, y) {
            context.translate(x, y);
        };

        return api;
    })();

})();<|endoftext|>


<commit_before>import React from 'react';

import styles from './Footer.scss';
import Link from '../Link';

export default function Footer({showCFP, filters, addConferenceUrl, showPast}) {
  return (

        <Link url={addConferenceUrl} external>
          Add a conference
        </Link>
        <Link routed url={addConferenceUrl} external>
          {showPast ? 'Hide past conferences' : 'See past conferences'}
        </Link>
        <Link selected={showCFP} url={showCFP ? `/${filters.type}` : `/cfp/${filters.type}`}>
          See Call For Papers
        </Link>

        Maintained by {Twitter('katyaprigara')}, {Twitter('nimz_co')} and {Twitter('trivikram')}

  );
}
function Twitter(handle) {
  return (
    <Link url={`https://twitter.com/@${handle}`} external>
      @{handle}
    </Link>
  );
}
<commit_msg>Fixed togglePast link<commit_after>import React from 'react';

import styles from './Footer.scss';
import Link from '../Link';

export default function Footer({showCFP, filters, addConferenceUrl, togglePast, showPast}) {
  return (

        <Link url={addConferenceUrl} external>
          Add a conference
        </Link>
        <Link selected={showPast} onClick={togglePast}>
          {showPast ? 'Hide past conferences' : 'See past conferences'}
        </Link>
        <Link selected={showCFP} url={showCFP ? `/${filters.type}` : `/cfp/${filters.type}`}>
          See Call For Papers
        </Link>

        Maintained by {Twitter('katyaprigara')}, {Twitter('nimz_co')} and {Twitter('trivikram')}

  );
}
function Twitter(handle) {
  return (
    <Link url={`https://twitter.com/@${handle}`} external>
      @{handle}
    </Link>
  );
}
<|endoftext|>