<commit_before>export default [
    '(business|client|community|culture|customer|data|goal|intelligence|market' +
        '|process|quality|results|role|sales|subject|service|user)' +
        '.(centric(ity)?|facing|oriented|driven|focused|assessment|service|process)',
    '24/7',
    'ai',
    'agile',
    'artificial intelligence',
    'at (your|their) fingertips',
    'autonomous',
    'a[-/]b testing',
    'acquisition',
    'action items?',
    'advantages?',
    'aggregate',
    'accelerate',
    'all.in.one',
    'analytics?',
    'application service providers?',
    'assets?',
    'authoritative',
    'automated',
    'augmented',
    'extended reality',
    'award.winning',
    'b2(b|c)',
    'back to the drawing board',
    'ball.?park',
    'band.aid',
    'bandwidth',
    '(benefit|gap) analysis',
    'bespoke',
    'best.in.class',
    'best.of.breed',
    'best.practice',
    'big.data',
    'big picture',
    'big thinkers?',
    'block.?chain',
    'blazing(ly)? fast',
    'bottom.line',
    'bottom.up',
    'boost(s|ing)?',
    'brain.?storm(ing)?',
    'brain.?dump',
    'brand(s?|ing|ed)',
    'bright',
    'burn.rates?',
    'business( cases| plans)',
    'buzz',
    'call to action',
    'capacity',
    'capabilit(y|ies)',
    'capitali(s|z)e',
    'centers? of excellence',
    'challenges?',
    'change agents?',
    'circle the wagons',
    'cloud',
    'collaborat(e|ion|ive)s?',
    'communicat(e|ion)s?',
    'company-employee.fit',
    'compelling',
    'competitive( advantage)?',
    'connected systems?',
    'complex',
    'comprehensive',
    'connect the dots',
    'containerizat(e|ion|ing)',
    'content management',
    'contextual(ly)?',
    'contingency plans?',
    'control groups?',
    'convergence',
    'convergent',
    'conversions?',
    'core business',
    'core competenc(y|ies)',
    'core.to.edge',
    'cost-effective',
    'cost/benefit',
    'cost control',
    'craftsmanship',
    'critical path',
    'crypto.currency',
    'crypto(?!graphy).\\w+',
    'crm',
    'cross.sell',
    'crowd.?(fund(s?|ed|ing)|sourc(ed|e|ing))',
    'customer obsession',
    'cutting.edge',
    'cyber',
    'data mining',
    'de-?dupe',
    'deep dive',
    'deep learning',
    'delight',
    'deliverables?',
    'demographic',
    'devops',
    'digital transformation',
    'discovery',
    'distributed ledgers?',
    'disrupt(ive)?',
    'dollar.productive',
    'downsi(s|z)e',
    'drill down',
    'drink the kool-aid',
    'drop.?in',
    'drop the ball',
    'due dilligence',
    'dynamic(s|ally)?',
    'e-?(business|commerce|tailers)',
    'eas(y|ily)',
    'ecosystems?',
    'efficien(t|cy)',
    'elaboration',
    'elephant in the room',
    'elevator pitch',
    'enabl(e|ing)',
    'emerging markets?',
    'empower(ing|ment|s)?',
    'enablement',
    'end of the day',
    'end.to.end',
    'engulf',
    'engag(e|ing)',
    'enhanced?',
    'enterprise',
    'erp',
    'estimate',
    'eta',
    'etched in stone',
    'exceed expectations',
    'exhaustive',
    'expedite',
    'experiences',
    'experts?',
    'expertise',
    'exposure',
    'facilitat(e|or)',
    'fast track',
    'fault.tolerant',
    'first.to.market',
    'flexibility',
    'foot view',
    'four pillars',
    'front lines',
    'functional',
    'futurist',
    'full benefit',
    'future.proof',
    'game changer',
    'game plan',
    'behavioral',
    'global(ly)?',
    'go public',
    'go.to.market',
    'goals?',
    'going forward',
    'granular',
    'ground.?breaking',
    'growth',
    'grow',
    'guidance',
    'guru',
    'hackathon',
    'hacker( mindset)?',
    'happiness manage(ment|rs?)',
    'hardball',
    'heavy.lifting',
    'herding cats',
    'high.level',
    '(high|mass).impact',
    'hive ?mind',
    'hybrid environments?',
    'hyperconverged',
    'holistic',
    'impactful',
    'impeccable',
    'in a nutshell',
    'incent',
    'incentivi(s|z)e',
    'increase the odds',
    '(inflat|redeem)able value',
    'influencers?',
    'innovat(e|ed|ion|ive|ing|or)s?',
    'inspir(e|ing|ation)',
    'insights?',
    'integrat(e|ed|ion)s?',
    'internet of things',
    'intellectual property',
    'intuitive',
    'iot',
    'key results?',
    'knowledge.(base|transfer|sharing)',
    'kpis?',
    'landing pages?',
    'lead the field',
    'leading',
    'leaders?',
    'leadership',
    'learnings',
    'legacy',
    'lessons learned',
    'level (the )? playing field',
    'level set',
    'leverag(e|ing)',
    'low.hanging fruit',
    'look.(&|and).feel',
    'm2m',
    'machine learning',
    'made simple',
    'market (chang(er|ing)|leader|window)',
    'market.ready',
    'marketing collateral',
    'maximi(s|z)e',
    'meaningful( client | )interactions?',
    'measurements?',
    'methodolog(y|ies)',
    'metrics',
    'middleware',
    'milestone',
    'military.grade encryption',
    'mind ?share',
    'mind ?shower',
    'mind-boggling',
    'mindset',
    '(mission|time).critical',
    'ml',
    'moneti(s|z)e',
    'mov(e|ing) (fast|forward)',
    'multitask(ing?)',
    'multifaceted',
    'negotiated',
    'networking',
    'new.economy',
    'new.breed',
    '(new|next|second).(level|gen|generation)',
    'niches?',
    'ninja',
    'no-brainer',
    'non-traditional management',
    'objectives',
    'occupy the field',
    'off.site',
    'off.the.(radar|shelf)',
    'on board',
    'on.premises?',
    'on the (back end|radar screen|same page)',
    'one to one',
    'opportunit(y|ies)',
    'outperform',
    'optimal',
    'outstanding',
    'out(side)?.of.the.(box|loop)',
    'outsourc(e|ed|ing)',
    '(total cost of )?ownership',
    'paradigms?( shift)?',
    'partner(ships?)?',
    'patents?',
    'performance indicators',
    'personaliz(e|ed|ation)',
    'perspective',
    'phases?',
    'phased approach',
    'pipeline',
    'pioneers',
    'planning horizon',
    'platforms?',
    'plug.?in',
    'potentials?',
    'powerful',
    'prioriti(s|z)ed?',
    'proactive',
    'problem space',
    'processes',
    'profit(ability)?',
    'promotion',
    'promotional collateral',
    'prominent',
    'proprietary',
    'proof.of.concept',
    'push the envelope',
    'push.back',
    'productivity',
    'pushing on open doors',
    'quick wins?',
    'rais(e|ing) the bar',
    'ramp.up',
    'relationship management',
    'responsive',
    'engage(ments?)?',
    'reach out',
    'reactivation',
    'real.time',
    'real.world',
    'reconfigure',
    'redefin(e|ed|ing)',
    'red flags?',
    'reengineering',
    'reinvent(ing)? the(.square)? wheel',
    'reinvigorate',
    'relevance',
    'repurpose',
    'resilien(ce|cy|t)',
    'resource allocation',
    'restructuring',
    'retention',
    'return on investment',
    'reus(e|ability)',
    'revenue',
    'reverse.engineer',
    'revisit',
    'rich',
    'road ?map',
    'robust',
    'rock.?star',
    'roi',
    'run the numbers',
    '(s|p)aas',
    'scal(e|es|ing|ability)',
    'high availability',
    'scenarios?',
    'scope',
    'scrum( master)?',
    'seamless',
    'secret sauce',
    'search engine optimization',
    'segments?',
    'self-managed team',
    'seo',
    '(serial )?entrepreneurs?',
    'serverless',
    'shareholder value',
    'significant(ly)?',
    'single-source responsibility',
    'skill ?sets?',
    'smart(er)?',
    'smoke (&|and) mirrors',
    'social(.media|.gaming|.networks?)',
    'solutions?',
    'sophisticated',
    'soup to nuts',
    'sow',
    'stakeholders?',
    'start.up?',
    'statement of work',
    'state.of.the.art',
    'sticky-?ness',
    'strateg(y|ic|ize|ise)',
    'streamlin(ed|e|ing)',
    'story points?',
    'success(ful)?',
    'super(critical|star)',
    'sustainab(le|ility)',
    'synerg(y|ies|ized|i)',
    'tailwinds?',
    'talented',
    'take offline',
    'talking points',
    'target (audience|group)',
    'targeted',
    'tasked',
    'tco',
    'team.building',
    'team.player',
    'teamwork',
    'technolog(y|ies)',
    'that being said',
    'time.to.market',
    'timelines?',
    'top.down',
    'top.of.the.game',
    'total quality',
    'touch.base',
    'touchpoints?',
    'traction',
    'transform',
    'trends?',
    'turnkey',
    'ultimate',
    'up.to.speed',
    'up-?sell',
    'upside',
    'user.friendly',
    'user funnels?',
    'user.experience',
    'utili(s|z)(e|ation)',
    'unicorn',
    'unique approach',
    'unlimited.holidays',
    'values?',
    'valueable',
    'value.add(ed)?',
    'venture',
    'venturing',
    'vertical market',
    'viral',
    'virtual(ization|isation)?',
    'visibility',
    'vision',
    'walk the talk',
    'wearable',
    'web.enabled',
    'win-win',
    'wisdom of crowds',
    'with due respect',
    'with ease',
    'workflows?',
    'world.?class',
    'world a better place',
    'wow.factor'
];
<commit_msg>Adds 'decentrali(s|z)ed' (#99)<commit_after>export default [
    '(business|client|community|culture|customer|data|goal|intelligence|market' +
        '|process|quality|results|role|sales|subject|service|user)' +
        '.(centric(ity)?|facing|oriented|driven|focused|assessment|service|process)',
    '24/7',
    'ai',
    'agile',
    'artificial intelligence',
    'at (your|their) fingertips',
    'autonomous',
    'a[-/]b testing',
    'acquisition',
    'action items?',
    'advantages?',
    'aggregate',
    'accelerate',
    'all.in.one',
    'analytics?',
    'application service providers?',
    'assets?',
    'authoritative',
    'automated',
    'augmented',
    'extended reality',
    'award.winning',
    'b2(b|c)',
    'back to the drawing board',
    'ball.?park',
    'band.aid',
    'bandwidth',
    '(benefit|gap) analysis',
    'bespoke',
    'best.in.class',
    'best.of.breed',
    'best.practice',
    'big.data',
    'big picture',
    'big thinkers?',
    'block.?chain',
    'blazing(ly)? fast',
    'bottom.line',
    'bottom.up',
    'boost(s|ing)?',
    'brain.?storm(ing)?',
    'brain.?dump',
    'brand(s?|ing|ed)',
    'bright',
    'burn.rates?',
    'business( cases| plans)',
    'buzz',
    'call to action',
    'capacity',
    'capabilit(y|ies)',
    'capitali(s|z)e',
    'centers? of excellence',
    'challenges?',
    'change agents?',
    'circle the wagons',
    'cloud',
    'collaborat(e|ion|ive)s?',
    'communicat(e|ion)s?',
    'company-employee.fit',
    'compelling',
    'competitive( advantage)?',
    'connected systems?',
    'complex',
    'comprehensive',
    'connect the dots',
    'containerizat(e|ion|ing)',
    'content management',
    'contextual(ly)?',
    'contingency plans?',
    'control groups?',
    'convergence',
    'convergent',
    'conversions?',
    'core business',
    'core competenc(y|ies)',
    'core.to.edge',
    'cost-effective',
    'cost/benefit',
    'cost control',
    'craftsmanship',
    'critical path',
    'crypto.currency',
    'crypto(?!graphy).\\w+',
    'crm',
    'cross.sell',
    'crowd.?(fund(s?|ed|ing)|sourc(ed|e|ing))',
    'customer obsession',
    'cutting.edge',
    'cyber',
    'data mining',
    'decentrali(s|z)ed',
    'de-?dupe',
    'deep dive',
    'deep learning',
    'delight',
    'deliverables?',
    'demographic',
    'devops',
    'digital transformation',
    'discovery',
    'distributed ledgers?',
    'disrupt(ive)?',
    'dollar.productive',
    'downsi(s|z)e',
    'drill down',
    'drink the kool-aid',
    'drop.?in',
    'drop the ball',
    'due dilligence',
    'dynamic(s|ally)?',
    'e-?(business|commerce|tailers)',
    'eas(y|ily)',
    'ecosystems?',
    'efficien(t|cy)',
    'elaboration',
    'elephant in the room',
    'elevator pitch',
    'enabl(e|ing)',
    'emerging markets?',
    'empower(ing|ment|s)?',
    'enablement',
    'end of the day',
    'end.to.end',
    'engulf',
    'engag(e|ing)',
    'enhanced?',
    'enterprise',
    'erp',
    'estimate',
    'eta',
    'etched in stone',
    'exceed expectations',
    'exhaustive',
    'expedite',
    'experiences',
    'experts?',
    'expertise',
    'exposure',
    'facilitat(e|or)',
    'fast track',
    'fault.tolerant',
    'first.to.market',
    'flexibility',
    'foot view',
    'four pillars',
    'front lines',
    'functional',
    'futurist',
    'full benefit',
    'future.proof',
    'game changer',
    'game plan',
    'behavioral',
    'global(ly)?',
    'go public',
    'go.to.market',
    'goals?',
    'going forward',
    'granular',
    'ground.?breaking',
    'growth',
    'grow',
    'guidance',
    'guru',
    'hackathon',
    'hacker( mindset)?',
    'happiness manage(ment|rs?)',
    'hardball',
    'heavy.lifting',
    'herding cats',
    'high.level',
    '(high|mass).impact',
    'hive ?mind',
    'hybrid environments?',
    'hyperconverged',
    'holistic',
    'impactful',
    'impeccable',
    'in a nutshell',
    'incent',
    'incentivi(s|z)e',
    'increase the odds',
    '(inflat|redeem)able value',
    'influencers?',
    'innovat(e|ed|ion|ive|ing|or)s?',
    'inspir(e|ing|ation)',
    'insights?',
    'integrat(e|ed|ion)s?',
    'internet of things',
    'intellectual property',
    'intuitive',
    'iot',
    'key results?',
    'knowledge.(base|transfer|sharing)',
    'kpis?',
    'landing pages?',
    'lead the field',
    'leading',
    'leaders?',
    'leadership',
    'learnings',
    'legacy',
    'lessons learned',
    'level (the )? playing field',
    'level set',
    'leverag(e|ing)',
    'low.hanging fruit',
    'look.(&|and).feel',
    'm2m',
    'machine learning',
    'made simple',
    'market (chang(er|ing)|leader|window)',
    'market.ready',
    'marketing collateral',
    'maximi(s|z)e',
    'meaningful( client | )interactions?',
    'measurements?',
    'methodolog(y|ies)',
    'metrics',
    'middleware',
    'milestone',
    'military.grade encryption',
    'mind ?share',
    'mind ?shower',
    'mind-boggling',
    'mindset',
    '(mission|time).critical',
    'ml',
    'moneti(s|z)e',
    'mov(e|ing) (fast|forward)',
    'multitask(ing?)',
    'multifaceted',
    'negotiated',
    'networking',
    'new.economy',
    'new.breed',
    '(new|next|second).(level|gen|generation)',
    'niches?',
    'ninja',
    'no-brainer',
    'non-traditional management',
    'objectives',
    'occupy the field',
    'off.site',
    'off.the.(radar|shelf)',
    'on board',
    'on.premises?',
    'on the (back end|radar screen|same page)',
    'one to one',
    'opportunit(y|ies)',
    'outperform',
    'optimal',
    'outstanding',
    'out(side)?.of.the.(box|loop)',
    'outsourc(e|ed|ing)',
    '(total cost of )?ownership',
    'paradigms?( shift)?',
    'partner(ships?)?',
    'patents?',
    'performance indicators',
    'personaliz(e|ed|ation)',
    'perspective',
    'phases?',
    'phased approach',
    'pipeline',
    'pioneers',
    'planning horizon',
    'platforms?',
    'plug.?in',
    'potentials?',
    'powerful',
    'prioriti(s|z)ed?',
    'proactive',
    'problem space',
    'processes',
    'profit(ability)?',
    'promotion',
    'promotional collateral',
    'prominent',
    'proprietary',
    'proof.of.concept',
    'push the envelope',
    'push.back',
    'productivity',
    'pushing on open doors',
    'quick wins?',
    'rais(e|ing) the bar',
    'ramp.up',
    'relationship management',
    'responsive',
    'engage(ments?)?',
    'reach out',
    'reactivation',
    'real.time',
    'real.world',
    'reconfigure',
    'redefin(e|ed|ing)',
    'red flags?',
    'reengineering',
    'reinvent(ing)? the(.square)? wheel',
    'reinvigorate',
    'relevance',
    'repurpose',
    'resilien(ce|cy|t)',
    'resource allocation',
    'restructuring',
    'retention',
    'return on investment',
    'reus(e|ability)',
    'revenue',
    'reverse.engineer',
    'revisit',
    'rich',
    'road ?map',
    'robust',
    'rock.?star',
    'roi',
    'run the numbers',
    '(s|p)aas',
    'scal(e|es|ing|ability)',
    'high availability',
    'scenarios?',
    'scope',
    'scrum( master)?',
    'seamless',
    'secret sauce',
    'search engine optimization',
    'segments?',
    'self-managed team',
    'seo',
    '(serial )?entrepreneurs?',
    'serverless',
    'shareholder value',
    'significant(ly)?',
    'single-source responsibility',
    'skill ?sets?',
    'smart(er)?',
    'smoke (&|and) mirrors',
    'social(.media|.gaming|.networks?)',
    'solutions?',
    'sophisticated',
    'soup to nuts',
    'sow',
    'stakeholders?',
    'start.up?',
    'statement of work',
    'state.of.the.art',
    'sticky-?ness',
    'strateg(y|ic|ize|ise)',
    'streamlin(ed|e|ing)',
    'story points?',
    'success(ful)?',
    'super(critical|star)',
    'sustainab(le|ility)',
    'synerg(y|ies|ized|i)',
    'tailwinds?',
    'talented',
    'take offline',
    'talking points',
    'target (audience|group)',
    'targeted',
    'tasked',
    'tco',
    'team.building',
    'team.player',
    'teamwork',
    'technolog(y|ies)',
    'that being said',
    'time.to.market',
    'timelines?',
    'top.down',
    'top.of.the.game',
    'total quality',
    'touch.base',
    'touchpoints?',
    'traction',
    'transform',
    'trends?',
    'turnkey',
    'ultimate',
    'up.to.speed',
    'up-?sell',
    'upside',
    'user.friendly',
    'user funnels?',
    'user.experience',
    'utili(s|z)(e|ation)',
    'unicorn',
    'unique approach',
    'unlimited.holidays',
    'values?',
    'valueable',
    'value.add(ed)?',
    'venture',
    'venturing',
    'vertical market',
    'viral',
    'virtual(ization|isation)?',
    'visibility',
    'vision',
    'walk the talk',
    'wearable',
    'web.enabled',
    'win-win',
    'wisdom of crowds',
    'with due respect',
    'with ease',
    'workflows?',
    'world.?class',
    'world a better place',
    'wow.factor'
];
<|endoftext|>


<commit_before>var Gesture = (function(){
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
      var videoElementId = "video_cameraDisplay",
          eventName = "gest",
          functionToBeFiredOnGest,
          createDomElement = (function(){
            var video = document.createElement("video");
            video.setAttribute("src","");
            video.setAttribute("style","display:none;width:400px; height:400px;");
            video.setAttribute("id", videoElementId);
            document.body.appendChild(video);

          }),
          capture = (function(video){
            var w = video.videoWidth,
                h = video.videoHeight,
                canvas = document.createElement('canvas'),
                ctx,imageData={};
            canvas.width  = w;
            canvas.height = h;
            ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, w, h);
            if(canvas.width) {
              imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            }
            return (typeof imageData.data!="undefined")?imageData.data:{};
          }),
          shoot = (function() {// this function will return image data in {"0":41,"1":35,"2":27} format
            var video  = document.getElementById(videoElementId);
            var imageData = capture(video);
            return imageData;
          }),
          compareWithBasicAndFireEvent = (function(screenShot1, screenShot2) {
             var changeCounter = 0,
                 arrayLength = screenShot1.length,
                 flag = 0;
             for(var index = 0; index<arrayLength; index++) {
              if(screenShot1[index]!=screenShot2[index]) {
                changeCounter += 1;
                if(changeCounter>((arrayLength*0.6))) {
                  flag = 1;
                  break;
                }
              }
             }
             if(flag) {
               functionToBeFiredOnGest("gest");
             }
          }),
          startGestureReading = (function() {
            window.setInterval(function(){
              var screenShot1 = shoot(),
                  screenShot2;
              window.setTimeout(function(){
                screenShot2 = shoot();
                compareWithBasicAndFireEvent(screenShot1, screenShot2);
              },300)    ;

            },1000);
          });
          this.gest = (function(functionToBeFired) {
            var gestObject = {};
            functionToBeFiredOnGest = functionToBeFired;
          });

          this.start = (function(){
            createDomElement();
            var camera = document.getElementById(videoElementId),
            constraints = {video:true},
            success = (function(stream) {
              camera.src = window.URL.createObjectURL(stream);
              camera.play();
            }),
            failure = (function(error){
              alert("Error Occcured "+JSON.stringify(error));
            });
            navigator.getUserMedia(constraints, success, failure);
            startGestureReading();
          });

    });<commit_msg>changes<commit_after>var Gesture = (function(){
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
      var videoElementId = "video_cameraDisplay",
          eventName = "gest",
          functionToBeFiredOnGest,
          createDomElement = (function(){
            var video = document.createElement("video");
            video.setAttribute("src","");
            video.setAttribute("style","display:none;width:400px; height:400px;");
            video.setAttribute("id", videoElementId);
            document.body.appendChild(video);

          }),
          capture = (function(video){
            var w = video.videoWidth*0.2,
                h = video.videoHeight*0.2,
                canvas = document.createElement('canvas'),
                ctx,imageData={};
            canvas.width  = w;
            canvas.height = h;
            ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, w, h);
            if(canvas.width) {
              imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            }
            return (typeof imageData.data!="undefined")?imageData.data:{};
          }),
          shoot = (function() {
            var video  = document.getElementById(videoElementId);
            var imageData = capture(video);
            return imageData;
          }),
          compareWithBasicAndFireEvent = (function(screenShot1, screenShot2) {
             var changeCounter = 0,
                 arrayLength = screenShot1.length,
                 flag = 0;
             for(var index = 0; index<arrayLength; index++) {
              if(screenShot1[index]!=screenShot2[index]) {
                changeCounter += 1;
                if(changeCounter>((arrayLength*0.6))) {
                  flag = 1;
                  break;
                }
              }
             }
             if(flag) {
               functionToBeFiredOnGest("gest");
             }
          }),
          startGestureReading = (function() {
            window.setInterval(function(){
              var screenShot1 = shoot(),
                  screenShot2;
              window.setTimeout(function(){
                screenShot2 = shoot();
                compareWithBasicAndFireEvent(screenShot1, screenShot2);
              },300)    ;

            },1000);
          });
          this.gest = (function(functionToBeFired) {
            var gestObject = {};
            functionToBeFiredOnGest = functionToBeFired;
          });

          this.start = (function(){
            createDomElement();
            var camera = document.getElementById(videoElementId),
            constraints = {video:true},
            success = (function(stream) {
              camera.src = window.URL.createObjectURL(stream);
              camera.play();
            }),
            failure = (function(error){
              alert("Error Occcured "+JSON.stringify(error));
            });
            navigator.getUserMedia(constraints, success, failure);
            startGestureReading();
          });

    });<|endoftext|>


<commit_before>'use strict';

var links = require('./links'),
  localization = require('./localization');

var Control = L.Control.extend({
  include: L.Mixin.Events,
  options: {
    popupWindowClass: "",
    popupCloseButtonClass: "",
    toolContainerClass: "",
    editorButtonClass: "",
    josmButtonClass: "",
    localizationButtonClass: "",
    gpxLinkClass: ""
  },

  initialize: function(lrm, options) {
    L.setOptions(this, options);
    this._lrm = lrm;
    lrm.on('routesfound', this._updateDownloadLink, this);
    lrm.on('routeselected', function(e) {
      this._selectedAlternative = e.route;
    }, this);
  },

  onAdd: function(map) {
    var editorContainer,
      editorButton,
      josmContainer,
      josmButton,
      popupCloseButton,
      gpxContainer;
    this._container = L.DomUtil.create('div', 'leaflet-osrm-tools-container leaflet-bar ' + this.options.toolsContainerClass);
    L.DomEvent.disableClickPropagation(this._container);
    editorContainer = L.DomUtil.create('div', 'leaflet-osrm-tools-editor', this._container);
    editorButton = L.DomUtil.create('span', this.options.editorButtonClass, editorContainer);
    editorButton.title = localization[this.options.language]['Open in editor'];
    L.DomEvent.on(editorButton, 'click', this._openEditor, this);
    josmContainer = L.DomUtil.create('div', 'leaflet-osrm-tools-josm', this._container);
    josmButton = L.DomUtil.create('span', this.options.josmButtonClass, josmContainer);
    josmButton.title = localization[this.options.language]['Open in JOSM'];
    L.DomEvent.on(josmButton, 'click', this._openJOSM, this);
    gpxContainer = L.DomUtil.create('div', 'leaflet-osrm-tools-gpx', this._container);
    this._gpxLink = L.DomUtil.create('a', this.options.gpxLinkClass, gpxContainer);
    this._gpxLink.innerHTML = "GPX";
    this._gpxLink.alt = localization[this.options.language]['Download as GPX'];
    this._popupWindow = L.DomUtil.create('div',
      'leaflet-osrm-tools-popup leaflet-osrm-tools-popup-hide ' + this.options.popupWindowClass,
      this._container);
    this._popupContainer = L.DomUtil.create('div', '', this._popupWindow);
    popupCloseButton = L.DomUtil.create('span', 'leaflet-osrm-tools-popup-close ' + this.options.popupCloseButtonClass, this._popupWindow);
    L.DomEvent.on(popupCloseButton, 'click', this._closePopup, this);
    return this._container;
  },

  onRemove: function() {},

  _openEditor: function() {
    var position = this._map.getCenter(),
      zoom = this._map.getZoom(),
      prec = 6;
    window.open("http://www.openstreetmap.org/edit?lat=" + position.lat.toFixed(prec) + "&lon=" + position.lng.toFixed(prec) + "&zoom=" + zoom);
  },

  _openJOSM: function() {
    var bounds = this._map.getBounds(),
      url = 'http://127.0.0.1:8111/load_and_zoom' +
      '?left=' + bounds.getWest() +
      '&right=' + bounds.getEast() +
      '&bottom=' + bounds.getSouth() +
      '&top=' + bounds.getNorth();
    window.open(url);
  },

  _getLinkOptions: function() {
    return {
      zoom: this._map.getZoom(),
      center: this._map.getCenter(),
      waypoints: this._lrm.getWaypoints(),
      language: this.options.language,
      units: this.options.units,
      alternative: this._selectedAlternative
    };
  },

  _updateDownloadLink: function() {
    var plan = this._lrm.getPlan(),
      router = this._lrm.getRouter(),
      url;
    if (!plan.isReady()) {
      return;
    }
    url = router.buildRouteUrl(plan.getWaypoints(), {
      fileformat: 'gpx'
    });
    this._gpxLink.href = url;
  },

  _updatePopupPosition: function() {
    var rect = this._container.getBoundingClientRect();
    this._popupWindow.style.position = 'absolute';
    this._popupWindow.style.left = '0px';
    this._popupWindow.style.bottom = rect.height + 'px';
  },

  _openPopup: function(content) {
    var children = this._popupContainer.children,
      i;
    this._updatePopupPosition();
    for (i = 0; i < children.length; i++) {
      this._popupContainer.removeChild(children[i]);
    }
    this._popupContainer.appendChild(content);
    L.DomUtil.removeClass(this._popupWindow, 'leaflet-osrm-tools-popup-hide');
  },

  _closePopup: function() {
    L.DomUtil.addClass(this._popupWindow, 'leaflet-osrm-tools-popup-hide');
  }
});

module.exports = {
  control: function(lrm, options) {
    return new Control(lrm, options);
  }
};<commit_msg>remove GPX for tools.js<commit_after>'use strict';

var links = require('./links'),
  localization = require('./localization');

var Control = L.Control.extend({
  include: L.Mixin.Events,
  options: {
    popupWindowClass: "",
    popupCloseButtonClass: "",
    toolContainerClass: "",
    editorButtonClass: "",
    josmButtonClass: "",
    localizationButtonClass: "",
    gpxLinkClass: ""
  },

  initialize: function(lrm, options) {
    L.setOptions(this, options);
    this._lrm = lrm;
    lrm.on('routesfound', this._updateDownloadLink, this);
    lrm.on('routeselected', function(e) {
      this._selectedAlternative = e.route;
    }, this);
  },

  onAdd: function(map) {
    var editorContainer,
      editorButton,
      josmContainer,
      josmButton,
      popupCloseButton,
      gpxContainer;
    this._container = L.DomUtil.create('div', 'leaflet-osrm-tools-container leaflet-bar ' + this.options.toolsContainerClass);
    L.DomEvent.disableClickPropagation(this._container);
    editorContainer = L.DomUtil.create('div', 'leaflet-osrm-tools-editor', this._container);
    editorButton = L.DomUtil.create('span', this.options.editorButtonClass, editorContainer);
    editorButton.title = localization[this.options.language]['Open in editor'];
    L.DomEvent.on(editorButton, 'click', this._openEditor, this);
    josmContainer = L.DomUtil.create('div', 'leaflet-osrm-tools-josm', this._container);
    josmButton = L.DomUtil.create('span', this.options.josmButtonClass, josmContainer);
    josmButton.title = localization[this.options.language]['Open in JOSM'];
    L.DomEvent.on(josmButton, 'click', this._openJOSM, this);
    this._popupWindow = L.DomUtil.create('div',
      'leaflet-osrm-tools-popup leaflet-osrm-tools-popup-hide ' + this.options.popupWindowClass,
      this._container);
    this._popupContainer = L.DomUtil.create('div', '', this._popupWindow);
    popupCloseButton = L.DomUtil.create('span', 'leaflet-osrm-tools-popup-close ' + this.options.popupCloseButtonClass, this._popupWindow);
    L.DomEvent.on(popupCloseButton, 'click', this._closePopup, this);
    return this._container;
  },

  onRemove: function() {},

  _openEditor: function() {
    var position = this._map.getCenter(),
      zoom = this._map.getZoom(),
      prec = 6;
    window.open("http://www.openstreetmap.org/edit?lat=" + position.lat.toFixed(prec) + "&lon=" + position.lng.toFixed(prec) + "&zoom=" + zoom);
  },

  _openJOSM: function() {
    var bounds = this._map.getBounds(),
      url = 'http://127.0.0.1:8111/load_and_zoom' +
      '?left=' + bounds.getWest() +
      '&right=' + bounds.getEast() +
      '&bottom=' + bounds.getSouth() +
      '&top=' + bounds.getNorth();
    window.open(url);
  },

  _getLinkOptions: function() {
    return {
      zoom: this._map.getZoom(),
      center: this._map.getCenter(),
      waypoints: this._lrm.getWaypoints(),
      language: this.options.language,
      units: this.options.units,
      alternative: this._selectedAlternative
    };
  },

  _updateDownloadLink: function() {
    var plan = this._lrm.getPlan(),
      router = this._lrm.getRouter(),
      url;
    if (!plan.isReady()) {
      return;
    }
    url = router.buildRouteUrl(plan.getWaypoints(), {
      fileformat: 'gpx'
    });
    this._gpxLink.href = url;
  },

  _updatePopupPosition: function() {
    var rect = this._container.getBoundingClientRect();
    this._popupWindow.style.position = 'absolute';
    this._popupWindow.style.left = '0px';
    this._popupWindow.style.bottom = rect.height + 'px';
  },

  _openPopup: function(content) {
    var children = this._popupContainer.children,
      i;
    this._updatePopupPosition();
    for (i = 0; i < children.length; i++) {
      this._popupContainer.removeChild(children[i]);
    }
    this._popupContainer.appendChild(content);
    L.DomUtil.removeClass(this._popupWindow, 'leaflet-osrm-tools-popup-hide');
  },

  _closePopup: function() {
    L.DomUtil.addClass(this._popupWindow, 'leaflet-osrm-tools-popup-hide');
  }
});

module.exports = {
  control: function(lrm, options) {
    return new Control(lrm, options);
  }
};<|endoftext|>


<commit_before>/* eslint max-len: 0 */
const chalk = require('chalk')
const fs = require('fs')
const noon = require('noon')
const xml2js = require('xml2js')

/**
  * The tools module provides useful repetitive tasks
  * @module Utils
  */

/**
  * Checks if a file exists
  * @private
  * @param {string} path The filename to check.
  * @return {boolean} fileExists
  */
function checkOutfile(path) {
  let fileExists = null
  try {
    fs.statSync(path)
    fileExists = true
  } catch (e) {
    if (e.code === 'ENOENT') {
      fileExists = false
    }
  }
  return fileExists
}

/**
  * Converts string to boolean
  * @public
  * @param {string} value
  * @return {boolean} v
  */
exports.checkBoolean = (value) => {
  let v = value
  if (v === 'true') v = true
  if (v === 'false') v = false
  return v
}

/**
  * Checks if config exists. If not, prints init message and exits with error code.
  * @public
  * @param {string} file Configuration filepath
  */
exports.checkConfig = (file) => {
  try {
    fs.statSync(file)
  } catch (e) {
    if (e.code === 'ENOENT') {
      throw new Error(`No config found at ${file}, run: ${chalk.white.bold('leximaven config init')}`)
    } else { throw e }
  }
}

/**
  * Handles data export to file. Supports cson, json, noon, plist, xml, yaml.
  * @public
  * @param {string} path The desired filepath and extension
  * @param {boolean} force Whether to force overwrite
  * @param {Object} tofile A numbered object of data points
  */
exports.outFile = (path, force, tofile) => {
  const match = path.match(/\.([a-z]*)$/i)
  const ext = match[1]
  const builder = new xml2js.Builder()
  if (ext === 'xml') {
    if (checkOutfile(path)) {
      if (force) {
        const xml = builder.buildObject(tofile)
        const fd = fs.openSync(path, 'w+')
        fs.writeSync(fd, xml)
        fs.closeSync(fd)
        console.log(chalk.white(`Overwrote ${path} with data.`))
      } else {
        console.log(chalk.white(`${path} exists, use -f to force overwrite.`))
      }
    } else {
      const xml = builder.buildObject(tofile)
      const fd = fs.openSync(path, 'w+')
      fs.writeSync(fd, xml)
      fs.closeSync(fd)
      console.log(chalk.white(`Wrote data to ${path}.`))
    }
  } else if (ext === 'cson' || 'json' || 'noon' || 'plist' || 'yml' || 'yaml') {
    if (checkOutfile(path)) {
      if (force) {
        noon.save(path, tofile)
        console.log(chalk.white(`Overwrote ${path} with data.`))
      } else {
        console.log(chalk.white(`${path} exists, use -f to force overwrite.`))
      }
    } else {
      noon.save(path, tofile)
      console.log(chalk.white(`Wrote data to ${path}.`))
    }
  } else console.log(chalk.white(`Format ${ext} not supported.`))
}
<commit_msg>refactor(tools): checkConfig throws/returns value, fix file ext<commit_after>/* eslint max-len: 0 */
const chalk = require('chalk')
const fs = require('fs')
const noon = require('noon')
const xml2js = require('xml2js')

/**
  * The tools module provides useful repetitive tasks
  * @module Utils
  */

/**
  * Checks if a file exists
  * @private
  * @param {string} path The filename to check.
  * @return {boolean} fileExists
  */
function checkOutfile(path) {
  let fileExists = null
  try {
    fs.statSync(path)
    fileExists = true
  } catch (e) {
    if (e.code === 'ENOENT') {
      fileExists = false
    }
  }
  return fileExists
}

/**
  * Converts string to boolean
  * @public
  * @param {string} value
  * @return {boolean} v
  */
exports.checkBoolean = (value) => {
  let v = value
  if (v === 'true') v = true
  if (v === 'false') v = false
  return v
}

/**
  * Checks if config exists. If not, prints init message and exits with error code.
  * @public
  * @param {string} file Configuration filepath
  */
exports.checkConfig = (file) => {
  try {
    fs.statSync(file)
  } catch (e) {
    if (e.code === 'ENOENT') {
      throw new Error(`No config found at ${file}, run: 'leximaven config init'`)
    }
  }
  return true
}

/**
  * Handles data export to file. Supports cson, json, noon, plist, xml, yaml.
  * @public
  * @param {string} path The desired filepath and extension
  * @param {boolean} force Whether to force overwrite
  * @param {Object} tofile A numbered object of data points
  */
exports.outFile = (path, force, tofile) => {
  const match = path.match(/\.([a-z]*)$/i)
  const ext = match[1]
  const builder = new xml2js.Builder()
  if (ext === 'xml') {
    if (checkOutfile(path)) {
      if (force) {
        const xml = builder.buildObject(tofile)
        const fd = fs.openSync(path, 'w+')
        fs.writeSync(fd, xml)
        fs.closeSync(fd)
        console.log(chalk.white(`Overwrote ${path} with data.`))
      } else {
        console.log(chalk.white(`${path} exists, use -f to force overwrite.`))
      }
    } else {
      const xml = builder.buildObject(tofile)
      const fd = fs.openSync(path, 'w+')
      fs.writeSync(fd, xml)
      fs.closeSync(fd)
      console.log(chalk.white(`Wrote data to ${path}.`))
    }
  } else if (ext === 'cson' || ext === 'json' || ext === 'noon' || ext === 'plist' || ext === 'yml' || ext === 'yaml') {
    if (checkOutfile(path)) {
      if (force) {
        noon.save(path, tofile)
        console.log(chalk.white(`Overwrote ${path} with data.`))
      } else {
        console.log(chalk.white(`${path} exists, use -f to force overwrite.`))
      }
    } else {
      noon.save(path, tofile)
      console.log(chalk.white(`Wrote data to ${path}.`))
    }
  } else if (ext !== 'xml' || ext !== 'cson' || ext !== 'json' || ext !== 'noon' || ext !== 'plist' || ext !== 'yml' || ext !== 'yaml') throw new Error(`Format ${ext} not supported.`)
}
<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(scope) {
  var dispatcher = scope.dispatcher;
  var findTarget = scope.findTarget;
  var allShadows = scope.targetFinding.allShadows.bind(scope.targetFinding);
  var pointermap = dispatcher.pointermap;
  var touchMap = Array.prototype.map.call.bind(Array.prototype.map);
  // This should be long enough to ignore compat mouse events made by touch
  var DEDUP_TIMEOUT = 2500;
  var ATTRIB = 'touch-action';
  var INSTALLER;
  var HAS_TOUCH_ACTION = (typeof document.head.style.touchAction) === 'string';

  // handler block for native touch events
  var touchEvents = {
    scrollType: new scope.SideTable,
    events: [
      'touchstart',
      'touchmove',
      'touchend',
      'touchcancel'
    ],
    register: function(target) {
      if (HAS_TOUCH_ACTION) {
        dispatcher.listen(target, this.events);
      } else {
        INSTALLER.enableOnSubtree(target);
      }
    },
    unregister: function(target) {
      if (HAS_TOUCH_ACTION) {
        dispatcher.unlisten(target, this.events);
      } else {
        // TODO(dfreedman): is it worth it to disconnect the MO?
      }
    },
    elementAdded: function(el) {
      var a = el.getAttribute(ATTRIB);
      var st = this.touchActionToScrollType(a);
      if (st) {
        this.scrollType.set(el, st);
        dispatcher.listen(el, this.events);
        // set touch-action on shadows as well
        allShadows(el).forEach(function(s) {
          this.scrollType.set(s, st);
          dispatcher.listen(s, this.events);
        }, this);
      }
    },
    elementRemoved: function(el) {
      this.scrollType.delete(el);
      dispatcher.unlisten(el, this.events);
      // remove touch-action from shadow
      allShadows(el).forEach(function(s) {
        this.scrollType.delete(s);
        dispatcher.unlisten(s, this.events);
      }, this);
    },
    elementChanged: function(el, oldValue) {
      var a = el.getAttribute(ATTRIB);
      var st = this.touchActiontoScrollType(a);
      var oldSt = this.touchActionToScrollType(oldValue);
      // simply update scrollType if listeners are already established
      if (st && oldSt) {
        this.scrollType.set(el, st);
        allShadows(el).forEach(function(s) {
          this.scrollType.set(s, st);
        }, this);
      } else if (oldSt) {
        this.elementRemoved(el);
      } else if (st) {
        this.elementAdded(el);
      }
    },
    scrollTypes: {
      EMITTER: 'none',
      XSCROLLER: 'pan-x',
      YSCROLLER: 'pan-y',
      SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/,
    },
    touchActionToScrollType: function(touchAction) {
      var t = touchAction;
      var st = this.scrollTypes;
      if (t === 'none') {
        return 'none';
      } else if (t === st.XSCROLLER) {
        return 'X';
      } else if (t === st.YSCROLLER) {
        return 'Y';
      } else if (st.SCROLLER.exec(t)) {
        return 'XY';
      }
    },
    POINTER_TYPE: 'touch',
    firstTouch: null,
    isPrimaryTouch: function(inTouch) {
      return this.firstTouch === inTouch.identifier;
    },
    setPrimaryTouch: function(inTouch) {
      if (this.firstTouch === null) {
        this.firstTouch = inTouch.identifier;
        this.firstXY = {X: inTouch.clientX, Y: inTouch.clientY};
        this.scrolling = false;
      }
    },
    removePrimaryTouch: function(inTouch) {
      if (this.isPrimaryTouch(inTouch)) {
        this.firstTouch = null;
        this.firstXY = null;
      }
    },
    touchToPointer: function(inTouch) {
      var e = dispatcher.cloneEvent(inTouch);
      // Spec specifies that pointerId 1 is reserved for Mouse.
      // Touch identifiers can start at 0.
      // Add 2 to the touch identifier for compatibility.
      e.pointerId = inTouch.identifier + 2;
      e.target = findTarget(e);
      e.bubbles = true;
      e.cancelable = true;
      e.button = 0;
      e.buttons = 1;
      e.width = inTouch.webkitRadiusX || inTouch.radiusX || 0;
      e.height = inTouch.webkitRadiusY || inTouch.radiusY || 0;
      e.pressure = inTouch.webkitForce || inTouch.force || 0.5;
      e.isPrimary = this.isPrimaryTouch(inTouch);
      e.pointerType = this.POINTER_TYPE;
      return e;
    },
    processTouches: function(inEvent, inFunction) {
      var tl = inEvent.changedTouches;
      var pointers = touchMap(tl, this.touchToPointer, this);
      pointers.forEach(inFunction, this);
    },
    // For single axis scrollers, determines whether the element should emit
    // pointer events or behave as a scroller
    shouldScroll: function(inEvent) {
      if (this.firstXY) {
        var ret;
        var scrollAxis = this.scrollType.get(inEvent.currentTarget);
        if (scrollAxis === 'none') {
          // this element is a touch-action: none, should never scroll
          ret = false;
        } else if (scrollAxis === 'XY') {
          // this element should always scroll
          ret = true;
        } else {
          var t = inEvent.changedTouches[0];
          // check the intended scroll axis, and other axis
          var a = scrollAxis;
          var oa = scrollAxis === 'Y' ? 'X' : 'Y';
          var da = Math.abs(t['client' + a] - this.firstXY[a]);
          var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
          // if delta in the scroll axis > delta other axis, scroll instead of
          // making events
          ret = da >= doa;
        }
        this.firstXY = null;
        return ret;
      }
    },
    findTouch: function(inTL, inId) {
      for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
        if (t.identifier === inId) {
          return true;
        }
      }
    },
    // In some instances, a touchstart can happen without a touchend. This
    // leaves the pointermap in a broken state.
    // Therefore, on every touchstart, we remove the touches that did not fire a
    // touchend event.
    // To keep state globally consistent, we fire a
    // pointercancel for this "abandoned" touch
    vacuumTouches: function(inEvent) {
      var tl = inEvent.touches;
      // pointermap.size should be < tl.length here, as the touchstart has not
      // been processed yet.
      if (pointermap.size >= tl.length) {
        var d = [];
        pointermap.forEach(function(key, value) {
          // Never remove pointerId == 1, which is mouse.
          // Touch identifiers are 2 smaller than their pointerId, which is the
          // index in pointermap.
          if (key !== 1 && !this.findTouch(tl, key - 2)) {
            var p = value.out;
            d.push(this.touchToPointer(p));
          }
        }, this);
        d.forEach(this.cancelOut, this);
      }
    },
    touchstart: function(inEvent) {
      this.vacuumTouches(inEvent);
      this.setPrimaryTouch(inEvent.changedTouches[0]);
      this.dedupSynthMouse(inEvent);
      if (!this.scrolling) {
        this.processTouches(inEvent, this.overDown);
      }
    },
    overDown: function(inPointer) {
      var p = pointermap.set(inPointer.pointerId, {
        target: inPointer.target,
        out: inPointer,
        outTarget: inPointer.target
      });
      dispatcher.over(inPointer);
      dispatcher.down(inPointer);
    },
    touchmove: function(inEvent) {
      if (!this.scrolling) {
        if (this.shouldScroll(inEvent)) {
          this.scrolling = true;
          this.touchcancel(inEvent);
        } else {
          inEvent.preventDefault();
          this.processTouches(inEvent, this.moveOverOut);
        }
      }
    },
    moveOverOut: function(inPointer) {
      var event = inPointer;
      var pointer = pointermap.get(event.pointerId);
      // a finger drifted off the screen, ignore it
      if (!pointer) {
        return;
      }
      var outEvent = pointer.out;
      var outTarget = pointer.outTarget;
      dispatcher.move(event);
      if (outEvent && outTarget !== event.target) {
        outEvent.relatedTarget = event.target;
        event.relatedTarget = outTarget;
        // recover from retargeting by shadow
        outEvent.target = outTarget;
        if (event.target) {
          dispatcher.leaveOut(outEvent);
          dispatcher.enterOver(event);
        } else {
          // clean up case when finger leaves the screen
          event.target = outTarget;
          event.relatedTarget = null;
          this.cancelOut(event);
        }
      }
      pointer.out = event;
      pointer.outTarget = event.target;
    },
    touchend: function(inEvent) {
      this.dedupSynthMouse(inEvent);
      this.processTouches(inEvent, this.upOut);
    },
    upOut: function(inPointer) {
      if (!this.scrolling) {
        dispatcher.up(inPointer);
        dispatcher.out(inPointer);
      }
      this.cleanUpPointer(inPointer);
    },
    touchcancel: function(inEvent) {
      this.processTouches(inEvent, this.cancelOut);
    },
    cancelOut: function(inPointer) {
      dispatcher.cancel(inPointer);
      dispatcher.out(inPointer);
      this.cleanUpPointer(inPointer);
    },
    cleanUpPointer: function(inPointer) {
      pointermap.delete(inPointer.pointerId);
      this.removePrimaryTouch(inPointer);
    },
    // prevent synth mouse events from creating pointer events
    dedupSynthMouse: function(inEvent) {
      var lts = scope.mouseEvents.lastTouches;
      var t = inEvent.changedTouches[0];
      // only the primary finger will synth mouse events
      if (this.isPrimaryTouch(t)) {
        // remember x/y of last touch
        var lt = {x: t.clientX, y: t.clientY};
        lts.push(lt);
        var fn = (function(lts, lt){
          var i = lts.indexOf(lt);
          if (i > -1) {
            lts.splice(i, 1)
          }
        }).bind(null, lts, lt);
        setTimeout(fn, DEDUP_TIMEOUT);
      }
    }
  };

  if (!HAS_TOUCH_ACTION) {
    INSTALLER = new scope.Installer(touchEvents.elementAdded, touchEvents.elementRemoved, touchEvents.elementChanged, touchEvents);
  }

  scope.touchEvents = touchEvents;
})(window.PointerEventsPolyfill);
<commit_msg>fix small typo<commit_after>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(scope) {
  var dispatcher = scope.dispatcher;
  var findTarget = scope.findTarget;
  var allShadows = scope.targetFinding.allShadows.bind(scope.targetFinding);
  var pointermap = dispatcher.pointermap;
  var touchMap = Array.prototype.map.call.bind(Array.prototype.map);
  // This should be long enough to ignore compat mouse events made by touch
  var DEDUP_TIMEOUT = 2500;
  var ATTRIB = 'touch-action';
  var INSTALLER;
  var HAS_TOUCH_ACTION = (typeof document.head.style.touchAction) === 'string';

  // handler block for native touch events
  var touchEvents = {
    scrollType: new scope.SideTable,
    events: [
      'touchstart',
      'touchmove',
      'touchend',
      'touchcancel'
    ],
    register: function(target) {
      if (HAS_TOUCH_ACTION) {
        dispatcher.listen(target, this.events);
      } else {
        INSTALLER.enableOnSubtree(target);
      }
    },
    unregister: function(target) {
      if (HAS_TOUCH_ACTION) {
        dispatcher.unlisten(target, this.events);
      } else {
        // TODO(dfreedman): is it worth it to disconnect the MO?
      }
    },
    elementAdded: function(el) {
      var a = el.getAttribute(ATTRIB);
      var st = this.touchActionToScrollType(a);
      if (st) {
        this.scrollType.set(el, st);
        dispatcher.listen(el, this.events);
        // set touch-action on shadows as well
        allShadows(el).forEach(function(s) {
          this.scrollType.set(s, st);
          dispatcher.listen(s, this.events);
        }, this);
      }
    },
    elementRemoved: function(el) {
      this.scrollType.delete(el);
      dispatcher.unlisten(el, this.events);
      // remove touch-action from shadow
      allShadows(el).forEach(function(s) {
        this.scrollType.delete(s);
        dispatcher.unlisten(s, this.events);
      }, this);
    },
    elementChanged: function(el, oldValue) {
      var a = el.getAttribute(ATTRIB);
      var st = this.touchActionToScrollType(a);
      var oldSt = this.touchActionToScrollType(oldValue);
      // simply update scrollType if listeners are already established
      if (st && oldSt) {
        this.scrollType.set(el, st);
        allShadows(el).forEach(function(s) {
          this.scrollType.set(s, st);
        }, this);
      } else if (oldSt) {
        this.elementRemoved(el);
      } else if (st) {
        this.elementAdded(el);
      }
    },
    scrollTypes: {
      EMITTER: 'none',
      XSCROLLER: 'pan-x',
      YSCROLLER: 'pan-y',
      SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/,
    },
    touchActionToScrollType: function(touchAction) {
      var t = touchAction;
      var st = this.scrollTypes;
      if (t === 'none') {
        return 'none';
      } else if (t === st.XSCROLLER) {
        return 'X';
      } else if (t === st.YSCROLLER) {
        return 'Y';
      } else if (st.SCROLLER.exec(t)) {
        return 'XY';
      }
    },
    POINTER_TYPE: 'touch',
    firstTouch: null,
    isPrimaryTouch: function(inTouch) {
      return this.firstTouch === inTouch.identifier;
    },
    setPrimaryTouch: function(inTouch) {
      if (this.firstTouch === null) {
        this.firstTouch = inTouch.identifier;
        this.firstXY = {X: inTouch.clientX, Y: inTouch.clientY};
        this.scrolling = false;
      }
    },
    removePrimaryTouch: function(inTouch) {
      if (this.isPrimaryTouch(inTouch)) {
        this.firstTouch = null;
        this.firstXY = null;
      }
    },
    touchToPointer: function(inTouch) {
      var e = dispatcher.cloneEvent(inTouch);
      // Spec specifies that pointerId 1 is reserved for Mouse.
      // Touch identifiers can start at 0.
      // Add 2 to the touch identifier for compatibility.
      e.pointerId = inTouch.identifier + 2;
      e.target = findTarget(e);
      e.bubbles = true;
      e.cancelable = true;
      e.button = 0;
      e.buttons = 1;
      e.width = inTouch.webkitRadiusX || inTouch.radiusX || 0;
      e.height = inTouch.webkitRadiusY || inTouch.radiusY || 0;
      e.pressure = inTouch.webkitForce || inTouch.force || 0.5;
      e.isPrimary = this.isPrimaryTouch(inTouch);
      e.pointerType = this.POINTER_TYPE;
      return e;
    },
    processTouches: function(inEvent, inFunction) {
      var tl = inEvent.changedTouches;
      var pointers = touchMap(tl, this.touchToPointer, this);
      pointers.forEach(inFunction, this);
    },
    // For single axis scrollers, determines whether the element should emit
    // pointer events or behave as a scroller
    shouldScroll: function(inEvent) {
      if (this.firstXY) {
        var ret;
        var scrollAxis = this.scrollType.get(inEvent.currentTarget);
        if (scrollAxis === 'none') {
          // this element is a touch-action: none, should never scroll
          ret = false;
        } else if (scrollAxis === 'XY') {
          // this element should always scroll
          ret = true;
        } else {
          var t = inEvent.changedTouches[0];
          // check the intended scroll axis, and other axis
          var a = scrollAxis;
          var oa = scrollAxis === 'Y' ? 'X' : 'Y';
          var da = Math.abs(t['client' + a] - this.firstXY[a]);
          var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
          // if delta in the scroll axis > delta other axis, scroll instead of
          // making events
          ret = da >= doa;
        }
        this.firstXY = null;
        return ret;
      }
    },
    findTouch: function(inTL, inId) {
      for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
        if (t.identifier === inId) {
          return true;
        }
      }
    },
    // In some instances, a touchstart can happen without a touchend. This
    // leaves the pointermap in a broken state.
    // Therefore, on every touchstart, we remove the touches that did not fire a
    // touchend event.
    // To keep state globally consistent, we fire a
    // pointercancel for this "abandoned" touch
    vacuumTouches: function(inEvent) {
      var tl = inEvent.touches;
      // pointermap.size should be < tl.length here, as the touchstart has not
      // been processed yet.
      if (pointermap.size >= tl.length) {
        var d = [];
        pointermap.forEach(function(key, value) {
          // Never remove pointerId == 1, which is mouse.
          // Touch identifiers are 2 smaller than their pointerId, which is the
          // index in pointermap.
          if (key !== 1 && !this.findTouch(tl, key - 2)) {
            var p = value.out;
            d.push(this.touchToPointer(p));
          }
        }, this);
        d.forEach(this.cancelOut, this);
      }
    },
    touchstart: function(inEvent) {
      this.vacuumTouches(inEvent);
      this.setPrimaryTouch(inEvent.changedTouches[0]);
      this.dedupSynthMouse(inEvent);
      if (!this.scrolling) {
        this.processTouches(inEvent, this.overDown);
      }
    },
    overDown: function(inPointer) {
      var p = pointermap.set(inPointer.pointerId, {
        target: inPointer.target,
        out: inPointer,
        outTarget: inPointer.target
      });
      dispatcher.over(inPointer);
      dispatcher.down(inPointer);
    },
    touchmove: function(inEvent) {
      if (!this.scrolling) {
        if (this.shouldScroll(inEvent)) {
          this.scrolling = true;
          this.touchcancel(inEvent);
        } else {
          inEvent.preventDefault();
          this.processTouches(inEvent, this.moveOverOut);
        }
      }
    },
    moveOverOut: function(inPointer) {
      var event = inPointer;
      var pointer = pointermap.get(event.pointerId);
      // a finger drifted off the screen, ignore it
      if (!pointer) {
        return;
      }
      var outEvent = pointer.out;
      var outTarget = pointer.outTarget;
      dispatcher.move(event);
      if (outEvent && outTarget !== event.target) {
        outEvent.relatedTarget = event.target;
        event.relatedTarget = outTarget;
        // recover from retargeting by shadow
        outEvent.target = outTarget;
        if (event.target) {
          dispatcher.leaveOut(outEvent);
          dispatcher.enterOver(event);
        } else {
          // clean up case when finger leaves the screen
          event.target = outTarget;
          event.relatedTarget = null;
          this.cancelOut(event);
        }
      }
      pointer.out = event;
      pointer.outTarget = event.target;
    },
    touchend: function(inEvent) {
      this.dedupSynthMouse(inEvent);
      this.processTouches(inEvent, this.upOut);
    },
    upOut: function(inPointer) {
      if (!this.scrolling) {
        dispatcher.up(inPointer);
        dispatcher.out(inPointer);
      }
      this.cleanUpPointer(inPointer);
    },
    touchcancel: function(inEvent) {
      this.processTouches(inEvent, this.cancelOut);
    },
    cancelOut: function(inPointer) {
      dispatcher.cancel(inPointer);
      dispatcher.out(inPointer);
      this.cleanUpPointer(inPointer);
    },
    cleanUpPointer: function(inPointer) {
      pointermap.delete(inPointer.pointerId);
      this.removePrimaryTouch(inPointer);
    },
    // prevent synth mouse events from creating pointer events
    dedupSynthMouse: function(inEvent) {
      var lts = scope.mouseEvents.lastTouches;
      var t = inEvent.changedTouches[0];
      // only the primary finger will synth mouse events
      if (this.isPrimaryTouch(t)) {
        // remember x/y of last touch
        var lt = {x: t.clientX, y: t.clientY};
        lts.push(lt);
        var fn = (function(lts, lt){
          var i = lts.indexOf(lt);
          if (i > -1) {
            lts.splice(i, 1)
          }
        }).bind(null, lts, lt);
        setTimeout(fn, DEDUP_TIMEOUT);
      }
    }
  };

  if (!HAS_TOUCH_ACTION) {
    INSTALLER = new scope.Installer(touchEvents.elementAdded, touchEvents.elementRemoved, touchEvents.elementChanged, touchEvents);
  }

  scope.touchEvents = touchEvents;
})(window.PointerEventsPolyfill);
<|endoftext|>


<commit_before>/**
 * Check if a value is a function.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isFunction(() => {})        // -> true
 * isFunction(Object.toString) // -> true
 * isFunction(class {})        // -> true
 */
export function isFunction(obj) {
    return typeof obj === 'function';
}
/**
 * Check if a value is a string.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isString('hello') // -> true
 * isString('2')     // -> true
 */
export function isString(obj) {
    return typeof obj === 'string';
}
/**
 * Check if a value is a number.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isNumber(2)   // -> true
 * isNumber('2') // -> false
 * isNumber(NaN) // -> false
 */
export function isNumber(obj) {
    return typeof obj === 'number' && !isNaN(obj);
}
/**
 * Check if a value is a bool.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isBoolean(false) // -> true
 * isBoolean(true)  // -> true
 */
export function isBoolean(obj) {
    return typeof obj === 'boolean';
}
/**
 * Check if a value is a date.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isDate(new Date())   // -> true
 * isDate('2017/05/12') // -> false
 */
export function isDate(obj) {
    return obj instanceof Date;
}
/**
 * Check if a value is an object.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isObject({})         // -> true
 * isObject(new Date()) // -> false
 */
export function isObject(obj) {
    return !isDate(obj) && !isArray(obj) && Object.prototype.toString.call(obj) === '[object Object]';
}
/**
 * Check if a value is undefined.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isUndefined(undefined) // -> true
 * isUndefined(null)      // -> false
 */
export function isUndefined(obj) {
    return typeof obj === 'undefined';
}
/**
 * Check if a value is an array.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isArray([1, 2, 3])              // -> true
 * isArray(document.body.children) // -> false
 */
export function isArray(obj) {
    return Array.isArray(obj);
}
/**
 * Check if falsy value.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isFalsy(null)      // -> true
 * isFalsy(undefined) // -> true
 * isFalsy(false)     // -> true
 * isFalsy(0)         // -> false
 * isFalsy('')        // -> false
 */
export function isFalsy(obj) {
    return isUndefined(obj) || obj === null || obj === false || (typeof obj === 'number' && isNaN(obj));
}
<commit_msg>chore: simplify isObject function<commit_after>/**
 * Check if a value is a function.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isFunction(() => {})        // -> true
 * isFunction(Object.toString) // -> true
 * isFunction(class {})        // -> true
 */
export function isFunction(obj) {
    return typeof obj === 'function';
}
/**
 * Check if a value is a string.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isString('hello') // -> true
 * isString('2')     // -> true
 */
export function isString(obj) {
    return typeof obj === 'string';
}
/**
 * Check if a value is a number.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isNumber(2)   // -> true
 * isNumber('2') // -> false
 * isNumber(NaN) // -> false
 */
export function isNumber(obj) {
    return typeof obj === 'number' && !isNaN(obj);
}
/**
 * Check if a value is a bool.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isBoolean(false) // -> true
 * isBoolean(true)  // -> true
 */
export function isBoolean(obj) {
    return typeof obj === 'boolean';
}
/**
 * Check if a value is a date.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isDate(new Date())   // -> true
 * isDate('2017/05/12') // -> false
 */
export function isDate(obj) {
    return obj instanceof Date;
}
/**
 * Check if a value is an object.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isObject({})         // -> true
 * isObject(new Date()) // -> false
 */
export function isObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]';
}
/**
 * Check if a value is undefined.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isUndefined(undefined) // -> true
 * isUndefined(null)      // -> false
 */
export function isUndefined(obj) {
    return typeof obj === 'undefined';
}
/**
 * Check if a value is an array.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isArray([1, 2, 3])              // -> true
 * isArray(document.body.children) // -> false
 */
export function isArray(obj) {
    return Array.isArray(obj);
}
/**
 * Check if falsy value.
 *
 * @param {*} obj The value to check.
 * @return {Boolean}
 *
 * @example
 * isFalsy(null)      // -> true
 * isFalsy(undefined) // -> true
 * isFalsy(false)     // -> true
 * isFalsy(0)         // -> false
 * isFalsy('')        // -> false
 */
export function isFalsy(obj) {
    return isUndefined(obj) || obj === null || obj === false || (typeof obj === 'number' && isNaN(obj));
}
<|endoftext|>


<commit_before>requirejs(["vendor/mithril"], function(mIgnore) {
    const root = document.body

    const Archive = {
        editorContents: "",
        lastLoadedContents: "",
        items: [],
        previousNextIndex: 0,

        setEditorContents(newContents) {
            Archive.editorContents = newContents
            Archive.lastLoadedContents = newContents
        },

        add: function() {
            Archive.items.push(Archive.editorContents)
            Archive.setEditorContents("")
        },

        confirmClear: function(promptText) {
            if (!Archive.editorContents) return true
            if (Archive.editorContents === Archive.lastLoadedContents) return true;
            if (!promptText) promptText = "You have unsaved editor changes; proceed?"
            return confirm(promptText)
        },

        clear: function() {
            if (!Archive.confirmClear()) return
            Archive.setEditorContents("")
        },

        eval: function () {
            Archive.setEditorContents(Archive.editorContents + "\n" + eval(Archive.editorContents))
        },

        importText: function() {
            if (!Archive.confirmClear()) return
            Archive.loadFromFile((fileName, fileContents) => {
                if (fileContents) {
                    console.log("updating editor")
                    const newContent = fileName + "\n---------------------------------------\n" + fileContents;
                    Archive.setEditorContents(newContent)
                    m.redraw()
                }
            })
        },

        loadFromFile: function (callback) {
            const fileControl = document.getElementById("fileInput");
            fileControl.addEventListener("change", function (event) {
                if (event.target.files.length < 1) return;
                const file = event.target.files[0];
                const reader = new FileReader();
                reader.onload = function(event) {
                    const contents = event.target.result;
                    callback(file.name, contents);
                };

                reader.onerror = function(event) {
                    console.error("File could not be read! Code " + event.target.error.code);
                    callback(null, null);
                };

                reader.readAsText(file);
            }, false);
            fileControl.click();
        },

        skip: function (offset) {
            if (!Archive.items.length) return
            Archive.previousNextIndex = (Archive.items.length + Archive.previousNextIndex + offset) % Archive.items.length
            console.log("Archive.previousNextIndex", Archive.previousNextIndex)
            Archive.setEditorContents(Archive.items[Archive.previousNextIndex])
        },

        previous: function () { Archive.skip(-1) },

        next: function () { Archive.skip(1) },

        textForLog: function() {
            return JSON.stringify(Archive.items, null, 4)
        },

        showLog: function () {
            console.log("items", Archive.items)
            if (!Archive.confirmClear()) return
            Archive.setEditorContents(Archive.textForLog())
        },

        loadLog: function () {
            if (!confirm("Replace all items with entered text for a log?")) return
            Archive.items = JSON.parse(Archive.editorContents)
            // Update in case pasted contents
            Archive.lastLoadedContents = Archive.editorContents
        },

        view: function() {
            return m("main.ma2", [
                m("h1.title.bw24.b--solid.b--blue", "Item count " + Archive.items.length),
                m("input#fileInput", { "type" : "file" , "hidden" : true } ),
                m("textarea", { value: Archive.editorContents, onchange: function (event) { Archive.editorContents = event.target.value } }),
                m("br"),
                m("button.ma1", { onclick: Archive.add }, "Add"),
                m("button.ma1", { onclick: Archive.clear }, "Clear"),
                m("button.ma1", { onclick: Archive.eval }, "Eval"),
                m("button.ma1", { onclick: Archive.importText }, "Import"),
                m("br"),
                m("button.ma1", { onclick: Archive.previous }, "Previous"),
                m("button.ma1", { onclick: Archive.next }, "Next"),
                m("br"),
                m("button.ma1", { onclick: Archive.showLog }, "Show log"),
                m("button.ma1", { onclick: Archive.loadLog }, "Load log")
            ])
        }
    }

    m.mount(root, Archive)
})<commit_msg>Add file save support<commit_after>requirejs(["vendor/mithril"], function(mIgnore) {
    const root = document.body

    const Archive = {
        editorContents: "",
        lastLoadedContents: "",
        items: [],
        previousNextIndex: 0,

        setEditorContents(newContents) {
            Archive.editorContents = newContents
            Archive.lastLoadedContents = newContents
        },

        add: function() {
            Archive.items.push(Archive.editorContents)
            Archive.setEditorContents("")
        },

        confirmClear: function(promptText) {
            if (!Archive.editorContents) return true
            if (Archive.editorContents === Archive.lastLoadedContents) return true;
            if (!promptText) promptText = "You have unsaved editor changes; proceed?"
            return confirm(promptText)
        },

        clear: function() {
            if (!Archive.confirmClear()) return
            Archive.setEditorContents("")
        },

        eval: function () {
            Archive.setEditorContents(Archive.editorContents + "\n" + eval(Archive.editorContents))
        },

        importText: function() {
            if (!Archive.confirmClear()) return
            Archive.loadFromFile((fileName, fileContents) => {
                if (fileContents) {
                    console.log("updating editor")
                    const newContent = fileName + "\n---------------------------------------\n" + fileContents;
                    Archive.setEditorContents(newContent)
                    m.redraw()
                }
            })
        },

        loadFromFile: function (callback) {
            const fileControl = document.getElementById("fileInput");
            fileControl.addEventListener("change", function (event) {
                if (event.target.files.length < 1) return;
                const file = event.target.files[0];
                const reader = new FileReader();
                reader.onload = function(event) {
                    const contents = event.target.result;
                    callback(file.name, contents);
                };

                reader.onerror = function(event) {
                    console.error("File could not be read! Code " + event.target.error.code);
                    callback(null, null);
                };

                reader.readAsText(file);
            }, false);
            fileControl.click();
        },

        exportText: function() {
            const fileContents = Archive.editorContents
            const provisionalFileName = fileContents.split("\n")[0]
            Archive.saveToFile(provisionalFileName, fileContents)
        },

        saveToFile: function (provisionalFileName, fileContents) {
            console.log("saveToFile")
            const fileName = prompt("Please enter a file name for saving", provisionalFileName)
            if (!fileName) return

            console.log("saving", fileName)
            const downloadLink = document.createElement("a")
            downloadLink.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(fileContents))
            downloadLink.setAttribute("download", fileName)
            downloadLink.style.display = "none"
            document.body.appendChild(downloadLink)
            downloadLink.click()
            document.body.removeChild(downloadLink)
            console.log("done saving", fileName)
        },

        skip: function (offset) {
            if (!Archive.items.length) return
            Archive.previousNextIndex = (Archive.items.length + Archive.previousNextIndex + offset) % Archive.items.length
            console.log("Archive.previousNextIndex", Archive.previousNextIndex)
            Archive.setEditorContents(Archive.items[Archive.previousNextIndex])
        },

        previous: function () { Archive.skip(-1) },

        next: function () { Archive.skip(1) },

        textForLog: function() {
            return JSON.stringify(Archive.items, null, 4)
        },

        showLog: function () {
            console.log("items", Archive.items)
            if (!Archive.confirmClear()) return
            Archive.setEditorContents(Archive.textForLog())
        },

        loadLog: function () {
            if (!confirm("Replace all items with entered text for a log?")) return
            Archive.items = JSON.parse(Archive.editorContents)
            // Update in case pasted contents
            Archive.lastLoadedContents = Archive.editorContents
        },

        view: function() {
            return m("main.ma2", [
                m("h1.title.bw24.b--solid.b--blue", "Item count " + Archive.items.length),
                m("input#fileInput", { "type" : "file" , "hidden" : true } ),
                m("textarea", { value: Archive.editorContents, onchange: function (event) { Archive.editorContents = event.target.value } }),
                m("br"),
                m("button.ma1", { onclick: Archive.add }, "Add"),
                m("button.ma1", { onclick: Archive.clear }, "Clear"),
                m("button.ma1", { onclick: Archive.eval }, "Eval"),
                m("button.ma1", { onclick: Archive.importText }, "Import"),
                m("button.ma1", { onclick: Archive.exportText }, "Export"),
                m("br"),
                m("button.ma1", { onclick: Archive.previous }, "Previous"),
                m("button.ma1", { onclick: Archive.next }, "Next"),
                m("br"),
                m("button.ma1", { onclick: Archive.showLog }, "Show log"),
                m("button.ma1", { onclick: Archive.loadLog }, "Load log")
            ])
        }
    }

    m.mount(root, Archive)
})<|endoftext|>


<commit_before>"use strict";
let _ = require("lodash");
let Promise = require('bluebird');
let readFile = Promise.promisify(require('fs').readFile);
let writeFile = Promise.promisify(require('fs').writeFile);
let remoteCSVtoJSON = require("./helpers/remote-csv-to-json");

const input = require("./input");
const output = require("./output");
const personModel = require("./input/person.json");

/**
 * Get full list of judges
 * @returns {Promise<Array>}
 */
module.exports = function scrapJudgesList() {
    if (process.env.LOCAL_JUDGES_JSON) {
        console.log("Use cached judges JSON.");
        return Promise.resolve(input.cachedList)
            .then((cachedList) => readFile(input.cachedList, 'utf8'))
            .then(data => JSON.parse(data))
            .then(data => _.take(data, process.env.PERSONS_LIMIT || Infinity));
    }

    return Promise.all([
        readFile(input.judgesPerRegionCSVLinksArray, 'utf8'),
        readFile(input.prosecutorsPerRegionCSVLinksArray, 'utf8')
    ])
        .spread(function (judgesLinks, prosecutorsLinks) {
            const data = judgesLinks.concat(prosecutorsLinks);

            return Promise.reduce(JSON.parse(data), function (regions, region) {
                console.log("Fetching: " + region.name);
                return remoteCSVtoJSON(region.link)
                    .then((json) => {
                        json.type = region.type;
                        return json;
                    })
                    .then((json) => regions.concat(json));
            }, []);
        })
        .then(function (judges) {
            return Promise.resolve(JSON.stringify(judges))
                .then((content) => writeFile(input.cachedJudges, content))
                .then(() => judges)
                .then(() => _.pick(judges, process.env.PERSONS_LIMIT || Infinity));
        })
        .then(function (judges) {
            console.log('Filter empty lines in scraped google sheets document.');
            return _.filter(judges, judge => judge[personModel.name] && !/\d/.test(judge[personModel.name]))
        });
};
<commit_msg>Scrap prosecutors<commit_after>"use strict";
let _ = require("lodash");
let Promise = require('bluebird');
let readFile = Promise.promisify(require('fs').readFile);
let writeFile = Promise.promisify(require('fs').writeFile);
let remoteCSVtoJSON = require("./helpers/remote-csv-to-json");

const input = require("./input");
const output = require("./output");
const personModel = require("./input/person.json");

/**
 * Get full list of judges
 * @returns {Promise<Array>}
 */
module.exports = function scrapJudgesList() {
    if (process.env.LOCAL_JUDGES_JSON) {
        console.log("Use cached judges JSON.");
        return Promise.resolve(input.cachedList)
            .then((cachedList) => readFile(input.cachedList, 'utf8'))
            .then(data => JSON.parse(data))
            .then(data => _.take(data, process.env.PERSONS_LIMIT || Infinity));
    }

    return Promise.all([
        readFile(input.judgesPerRegionCSVLinksArray, 'utf8').then(JSON.parse),
        readFile(input.prosecutorsPerRegionCSVLinksArray, 'utf8').then(JSON.parse)
    ])
        .spread(function (judgesLinks, prosecutorsLinks) {
            const data = judgesLinks.concat(prosecutorsLinks);

            return Promise.reduce(data, function (regions, region) {
                console.log("Fetching: " + region.name);
                return remoteCSVtoJSON(region.link)
                    .then((json) => {
                        json.type = region.type;
                        return json;
                    })
                    .then((json) => regions.concat(json));
            }, []);
        })
        .then(function (judges) {
            return Promise.resolve(JSON.stringify(judges))
                .then((content) => writeFile(input.cachedJudges, content))
                .then(() => judges)
                .then(() => _.pick(judges, process.env.PERSONS_LIMIT || Infinity));
        })
        .then(function (judges) {
            console.log('Filter empty lines in scraped google sheets document.');
            return _.filter(judges, judge => judge[personModel.name] && !/\d/.test(judge[personModel.name]))
        });
};
<|endoftext|>


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

'use strict';

function interpolateButtonStyles(themeOpts) {
    var buttonTheme = {};
    var backgroundColor = themeOpts.cardBackgroundColor ? tinycolor(themeOpts.cardBackgroundColor) : tinycolor('#FFF');
    if (backgroundColor.isLight()) {
        buttonThemeOpts.buttonTextColor = tinycolor('#000').lighten(40).toHexString();
        buttonThemeOpts.buttonHoverBackgroundColor = backgroundColor.darken(5).toHexString();
        buttonThemeOpts.buttonActiveBackgroundColor = backgroundColor.darken(15).toHexString();
        buttonThemeOpts.buttonBorderColor = 'rgba(0,0,0,0.3)';
    } else if (backgroundColor.isDark()) {
        buttonThemeOpts.buttonTextColor = tinycolor('#FFF').darken(40).toHexString();
        buttonThemeOpts.buttonHoverBackgroundColor = backgroundColor.lighten(5).toHexString();
        buttonThemeOpts.buttonActiveBackgroundColor = backgroundColor.lighten(15).toHexString();
        buttonThemeOpts.buttonBorderColor = 'rgba(0,0,0,0.5)';
    }
    return _.extend(buttonThemeOpts, themeOpts);
}

module.exports = {
    interpolateButtonStyles: interpolateButtonStyles
}
<commit_msg>Fix var name<commit_after>var _ = require('lodash');
var tinycolor = require('tinycolor');

'use strict';

function interpolateButtonStyles(themeOpts) {
    var buttonThemeOpts = {};
    var backgroundColor = themeOpts.cardBackgroundColor ? tinycolor(themeOpts.cardBackgroundColor) : tinycolor('#FFF');
    if (backgroundColor.isLight()) {
        buttonThemeOpts.buttonTextColor = tinycolor('#000').lighten(40).toHexString();
        buttonThemeOpts.buttonHoverBackgroundColor = backgroundColor.darken(5).toHexString();
        buttonThemeOpts.buttonActiveBackgroundColor = backgroundColor.darken(15).toHexString();
        buttonThemeOpts.buttonBorderColor = 'rgba(0,0,0,0.3)';
    } else if (backgroundColor.isDark()) {
        buttonThemeOpts.buttonTextColor = tinycolor('#FFF').darken(40).toHexString();
        buttonThemeOpts.buttonHoverBackgroundColor = backgroundColor.lighten(5).toHexString();
        buttonThemeOpts.buttonActiveBackgroundColor = backgroundColor.lighten(15).toHexString();
        buttonThemeOpts.buttonBorderColor = 'rgba(0,0,0,0.5)';
    }
    return _.extend(buttonThemeOpts, themeOpts);
}

module.exports = {
    interpolateButtonStyles: interpolateButtonStyles
}
<|endoftext|>