<commit_before>
// State for event handlers
var state = 'init';

// Used only to remember last song title
var clipTitle = '';

// Timeout to scrobble track ater minimum time passes
var scrobbleTimeout = null;

$(function(){

   // bindings to trigger song recognition on various (classic, profile) pages
   if (document.location.toString().indexOf('/watch#!v=') > -1) {
      // === AJAX page load =======================================================

      // Hook up for changes in header (Loading... -> Artist - Title) on CLASSIC page
      $('#watch-pagetop-section').bind('DOMSubtreeModified', function(e) {

         // simple FSM (not only) to prevent multiple calls of updateNowPlaying()

         // init ----> loading
         if (state == 'init' && $('#watch-loading').length > 0) {
            state = 'loading';
            return;
         }

         // watching ----> loading
         if (state == 'watching' &&
             $('#watch-headline-title > span[title][id!=chrome-scrobbler-status]').length>0 &&
             $('#watch-headline-title > span[title][id!=chrome-scrobbler-status]').attr('title') != clipTitle
            ) {
            // fake loading state to match the next condition and reload the clip info
            state = 'loading';
            // By now, scrobbler.js should have info about song which has been marked
            // as 'now playing', but has not been submitted (scrobbled) yet.
            // Let's submit it before we load another clip!
            //scrobbleTrack();
         }

         // loading --[updateNowPlaying(), set clipTitle]--> watching
         if (state == 'loading' && $('#watch-headline-title').length > 0) {
            state = 'watching';
            clipTitle = $('#watch-headline-title > span[title][id!=chrome-scrobbler-status]').attr('title');

            updateNowPlaying();

            return;
         }

      });

   } else if ( $('#playnav-player').length > 0 ) {

      // Hook up for changes in title on users profile page
      $('#playnav-video-details').bind('DOMSubtreeModified', function(e) {

         if ($('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]').length > 0) {

            // just check changes in the song title
            var titleEl = $('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]');
            if (clipTitle != titleEl.text()) {
               updateNowPlaying();
               clipTitle = titleEl.text();
            }
         }

      });

      // fire the DOMSubtreeModified event on first pageload (the binding above is executed after full DOM load)
      $('#playnav-video-details').trigger('DOMSubtreeModified');

   } else {
      // === regular page load ====================================================

      /*
      // inject stats code
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-16968457-1']);

      (function() {
         var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
         ga.src = 'https://ssl.google-analytics.com/ga.js';
         (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
      })();
      */

      // start scrobbler
      updateNowPlaying();
   }

   // bind page unload function to discard current "now listening"
   $(window).unload(function() {
      // cancel the timeout
      if (scrobbleTimeout != null)
         window.clearTimeout(scrobbleTimeout);

      // reset the background scrobbler song data
      chrome.extension.sendRequest({type: 'reset'});

      return true;
   });

});

/**
 * Parse given string into artist and track
 * @return {artist, track}
 */
function parseInfo(artistTitle) {
   var artist = '';
   var track = '';

   // Figure out where to split; use " - " rather than "-"
   if (artistTitle.indexOf(' - ') > -1) {
      artist = artistTitle.substring(0, artistTitle.indexOf(' - '));
      track = artistTitle.substring(artistTitle.indexOf(' - ') + 3);
   } else if (artistTitle.indexOf('-') > -1) {
      artist = artistTitle.substring(0, artistTitle.indexOf('-'));
      track = artistTitle.substring(artistTitle.indexOf('-') + 1);
   } else if (artistTitle.indexOf(':') > -1) {
      artist = artistTitle.substring(0, artistTitle.indexOf(':'));
      track = artistTitle.substring(artistTitle.indexOf(':') + 1);
   } else {
      // can't parse
      return {artist:'', track:''};
   }

   return cleanArtistTrack(artist, track);
}

function cleanArtistTrack(artist, track) {

   // Do some cleanup
   artist = artist.replace(/^\s+|\s+$/g,'');
   track = track.replace(/^\s+|\s+$/g,'');

   // Strip crap
   track = track.replace(/\*+[^\*]+\*+$/, ''); // **NEW**
   track = track.replace(/\[[^\]]+\]$/, ''); // [whatever]
   track = track.replace(/\([^\)]+\)$/, ''); // (whatever)
   track = track.replace(/\.(avi|wmv|mpg|mpeg)$/i, ''); // video extensions
   track = track.replace(/of+icial video/i, ''); // official video
   track = track.replace(/video[ ]?clip/i, ''); // video clip
   track = track.replace(/music\s*video/i, ''); // music video
   track = track.replace(/,?[ ]?live$/i, ''); // live

   return {artist: artist, track: track};
}

/**
 * Display message in front of clip title,
 * call without parameter to clean the message.
 */
function displayMsg(msg) {
   if (msg) {
      // regular page
      if ($('#watch-headline-title > span[title][id!=chrome-scrobbler-status]').length>0)
         $(''+msg+'').insertBefore($('#watch-headline-title > span[title][id!=chrome-scrobbler-status]'));
      // user profile
      if ($('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]').length>0)
         $(''+msg+'').insertBefore($('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]'));
   } else {
      $('#chrome-scrobbler-status').remove();
   }
}

/**
 * Called every time the player reloads
 */
function updateNowPlaying() {

   // get the video ID
   var videoID = document.URL.match(/^[^v]+v.(.{11}).*/);
   if (videoID && videoID.length > 0)
      videoID = videoID[1];
   else
      videoID = null;

   // videoID from title at profile page
   if (!videoID && $('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]').length > 0) {
      videoID = $('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]').attr('onclick').toString().match(/\?v=(.{11})/);
      if (videoID && videoID.length > 0)
         videoID = videoID[1];
   }

   // something changed?
   if (!videoID) {
      alert('YouTube has probably changed its code. Please get newer version of the Last.fm Scrobbler extension');
      return;
   }

   // http://code.google.com/intl/cs/apis/youtube/2.0/developers_guide_protocol_video_entries.html
   var googleURL = "http://gdata.youtube.com/feeds/api/videos/" + videoID + "?alt=json";

   // clear the message
   displayMsg();

   // Get clip info from youtube api
   chrome.extension.sendRequest({type: "xhr", url: googleURL}, function(response) {
   	var info = JSON.parse(response.text);
   	var parsedInfo = parseInfo(info.entry.title.$t);

      artist = null; // global!
      track = null; // global!

      // Use the #eow-title #watch-headline-show-title if available
      var track_dom = $('#eow-title').clone();
      var artist_dom = $('#watch-headline-show-title', track_dom);
      if (artist_dom) {
        artist = artist_dom.text();
        artist_dom.remove();
        track = track_dom.text();
        track = track.replace(/^[\s-]+/, ''); // trim starting white chars and dash separating artist from track
        track = track.replace(/[\s-]+$/, ''); // trim trailing white chars and dash
        parsedInfo = cleanArtistTrack(artist, track);
      } else if (parsedInfo['artist'] != '') {
        parsedInfo = parseInfo(track_dom.text());
      }
      artist = parsedInfo['artist'];
      track = parsedInfo['track'];

      duration = ''; // global!
   	if (info.entry.media$group.media$content != undefined)
         duration = info.entry.media$group.media$content[0].duration;
      else if (info.entry.media$group.yt$duration.seconds != undefined)
         duration = info.entry.media$group.yt$duration.seconds;

   	if (artist == '' || track == '') {
         displayMsg('Not recognized');
         return;
      }

      // Validate given artist and track
      chrome.extension.sendRequest({type: 'validate', artist: artist, track: track}, function(response) {
   		if (response == true)
               chrome.extension.sendRequest({type: 'nowPlaying', artist: artist, track: track, duration: duration});
         else
            displayMsg('Not recognized');
   	});

   });

}

/**
 * Simply request the scrobbler.js to submit song previusly specified by calling updateNowPlaying()
 */
function scrobbleTrack() {
   // stats
   chrome.extension.sendRequest({type: 'trackStats', text: 'YouTube video scrobbled'});

   // scrobble
   chrome.extension.sendRequest({type: 'submit'});
}

/**
 * Listen for requests from scrobbler.js
 */
chrome.extension.onRequest.addListener(
   function(request, sender, sendResponse) {
         switch(request.type) {
            // called after track has been successfully marked as 'now playing' at the server
            case 'nowPlayingOK':
               displayMsg('Scrobbling');
               var min_time = (240 < (duration/2)) ? 240 : (duration/2); //The minimum time is 240 seconds or half the track's total length. Duration comes from updateNowPlaying()

               // cancel any previous timeout
               if (scrobbleTimeout != null)
                  clearTimeout(scrobbleTimeout);

               // set up a new timeout
               scrobbleTimeout = setTimeout(
                  function(){
                     // Turns status message into black when half of videos time has been played, to indicate that we are past the minimum time for a scrobble.
                     //$("#chrome-scrobbler-status").addClass("scrobbled");
                     //$("#chrome-scrobbler-status").attr("title","The minimum time for a scrobble has past");
                     setTimeout(scrobbleTrack, 2000);
                  }, min_time*1000
               );
               break;

            // not used yet
            case 'submitOK':
               break;

            // not used yet
            case 'submitFAIL':
               //alert('submit fail');
               break;
         }
   }
);
<commit_msg>A slightly safer *NONSENSE* detector<commit_after>
// State for event handlers
var state = 'init';

// Used only to remember last song title
var clipTitle = '';

// Timeout to scrobble track ater minimum time passes
var scrobbleTimeout = null;

$(function(){

   // bindings to trigger song recognition on various (classic, profile) pages
   if (document.location.toString().indexOf('/watch#!v=') > -1) {
      // === AJAX page load =======================================================

      // Hook up for changes in header (Loading... -> Artist - Title) on CLASSIC page
      $('#watch-pagetop-section').bind('DOMSubtreeModified', function(e) {

         // simple FSM (not only) to prevent multiple calls of updateNowPlaying()

         // init ----> loading
         if (state == 'init' && $('#watch-loading').length > 0) {
            state = 'loading';
            return;
         }

         // watching ----> loading
         if (state == 'watching' &&
             $('#watch-headline-title > span[title][id!=chrome-scrobbler-status]').length>0 &&
             $('#watch-headline-title > span[title][id!=chrome-scrobbler-status]').attr('title') != clipTitle
            ) {
            // fake loading state to match the next condition and reload the clip info
            state = 'loading';
            // By now, scrobbler.js should have info about song which has been marked
            // as 'now playing', but has not been submitted (scrobbled) yet.
            // Let's submit it before we load another clip!
            //scrobbleTrack();
         }

         // loading --[updateNowPlaying(), set clipTitle]--> watching
         if (state == 'loading' && $('#watch-headline-title').length > 0) {
            state = 'watching';
            clipTitle = $('#watch-headline-title > span[title][id!=chrome-scrobbler-status]').attr('title');

            updateNowPlaying();

            return;
         }

      });

   } else if ( $('#playnav-player').length > 0 ) {

      // Hook up for changes in title on users profile page
      $('#playnav-video-details').bind('DOMSubtreeModified', function(e) {

         if ($('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]').length > 0) {

            // just check changes in the song title
            var titleEl = $('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]');
            if (clipTitle != titleEl.text()) {
               updateNowPlaying();
               clipTitle = titleEl.text();
            }
         }

      });

      // fire the DOMSubtreeModified event on first pageload (the binding above is executed after full DOM load)
      $('#playnav-video-details').trigger('DOMSubtreeModified');

   } else {
      // === regular page load ====================================================

      /*
      // inject stats code
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-16968457-1']);

      (function() {
         var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
         ga.src = 'https://ssl.google-analytics.com/ga.js';
         (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
      })();
      */

      // start scrobbler
      updateNowPlaying();
   }

   // bind page unload function to discard current "now listening"
   $(window).unload(function() {
      // cancel the timeout
      if (scrobbleTimeout != null)
         window.clearTimeout(scrobbleTimeout);

      // reset the background scrobbler song data
      chrome.extension.sendRequest({type: 'reset'});

      return true;
   });

});

/**
 * Parse given string into artist and track
 * @return {artist, track}
 */
function parseInfo(artistTitle) {
   var artist = '';
   var track = '';

   // Figure out where to split; use " - " rather than "-"
   if (artistTitle.indexOf(' - ') > -1) {
      artist = artistTitle.substring(0, artistTitle.indexOf(' - '));
      track = artistTitle.substring(artistTitle.indexOf(' - ') + 3);
   } else if (artistTitle.indexOf('-') > -1) {
      artist = artistTitle.substring(0, artistTitle.indexOf('-'));
      track = artistTitle.substring(artistTitle.indexOf('-') + 1);
   } else if (artistTitle.indexOf(':') > -1) {
      artist = artistTitle.substring(0, artistTitle.indexOf(':'));
      track = artistTitle.substring(artistTitle.indexOf(':') + 1);
   } else {
      // can't parse
      return {artist:'', track:''};
   }

   return cleanArtistTrack(artist, track);
}

function cleanArtistTrack(artist, track) {

   // Do some cleanup
   artist = artist.replace(/^\s+|\s+$/g,'');
   track = track.replace(/^\s+|\s+$/g,'');

   // Strip crap
   track = track.replace(/\s*\*+\s?\S+\s?\*+$/, ''); // **NEW**
   track = track.replace(/\[[^\]]+\]$/, ''); // [whatever]
   track = track.replace(/\([^\)]+\)$/, ''); // (whatever)
   track = track.replace(/\.(avi|wmv|mpg|mpeg)$/i, ''); // video extensions
   track = track.replace(/of+icial video/i, ''); // official video
   track = track.replace(/video[ ]?clip/i, ''); // video clip
   track = track.replace(/music\s*video/i, ''); // music video
   track = track.replace(/,?[ ]?live$/i, ''); // live

   return {artist: artist, track: track};
}

/**
 * Display message in front of clip title,
 * call without parameter to clean the message.
 */
function displayMsg(msg) {
   if (msg) {
      // regular page
      if ($('#watch-headline-title > span[title][id!=chrome-scrobbler-status]').length>0)
         $(''+msg+'').insertBefore($('#watch-headline-title > span[title][id!=chrome-scrobbler-status]'));
      // user profile
      if ($('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]').length>0)
         $(''+msg+'').insertBefore($('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]'));
   } else {
      $('#chrome-scrobbler-status').remove();
   }
}

/**
 * Called every time the player reloads
 */
function updateNowPlaying() {

   // get the video ID
   var videoID = document.URL.match(/^[^v]+v.(.{11}).*/);
   if (videoID && videoID.length > 0)
      videoID = videoID[1];
   else
      videoID = null;

   // videoID from title at profile page
   if (!videoID && $('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]').length > 0) {
      videoID = $('#playnav-curvideo-title > span[id!=chrome-scrobbler-status]').attr('onclick').toString().match(/\?v=(.{11})/);
      if (videoID && videoID.length > 0)
         videoID = videoID[1];
   }

   // something changed?
   if (!videoID) {
      alert('YouTube has probably changed its code. Please get newer version of the Last.fm Scrobbler extension');
      return;
   }

   // http://code.google.com/intl/cs/apis/youtube/2.0/developers_guide_protocol_video_entries.html
   var googleURL = "http://gdata.youtube.com/feeds/api/videos/" + videoID + "?alt=json";

   // clear the message
   displayMsg();

   // Get clip info from youtube api
   chrome.extension.sendRequest({type: "xhr", url: googleURL}, function(response) {
   	var info = JSON.parse(response.text);
   	var parsedInfo = parseInfo(info.entry.title.$t);

      artist = null; // global!
      track = null; // global!

      // Use the #eow-title #watch-headline-show-title if available
      var track_dom = $('#eow-title').clone();
      var artist_dom = $('#watch-headline-show-title', track_dom);
      if (artist_dom) {
        artist = artist_dom.text();
        artist_dom.remove();
        track = track_dom.text();
        track = track.replace(/^[\s-]+/, ''); // trim starting white chars and dash separating artist from track
        track = track.replace(/[\s-]+$/, ''); // trim trailing white chars and dash
        parsedInfo = cleanArtistTrack(artist, track);
      } else if (parsedInfo['artist'] != '') {
        parsedInfo = parseInfo(track_dom.text());
      }
      artist = parsedInfo['artist'];
      track = parsedInfo['track'];

      duration = ''; // global!
   	if (info.entry.media$group.media$content != undefined)
         duration = info.entry.media$group.media$content[0].duration;
      else if (info.entry.media$group.yt$duration.seconds != undefined)
         duration = info.entry.media$group.yt$duration.seconds;

   	if (artist == '' || track == '') {
         displayMsg('Not recognized');
         return;
      }

      // Validate given artist and track
      chrome.extension.sendRequest({type: 'validate', artist: artist, track: track}, function(response) {
   		if (response == true)
               chrome.extension.sendRequest({type: 'nowPlaying', artist: artist, track: track, duration: duration});
         else
            displayMsg('Not recognized');
   	});

   });

}

/**
 * Simply request the scrobbler.js to submit song previusly specified by calling updateNowPlaying()
 */
function scrobbleTrack() {
   // stats
   chrome.extension.sendRequest({type: 'trackStats', text: 'YouTube video scrobbled'});

   // scrobble
   chrome.extension.sendRequest({type: 'submit'});
}

/**
 * Listen for requests from scrobbler.js
 */
chrome.extension.onRequest.addListener(
   function(request, sender, sendResponse) {
         switch(request.type) {
            // called after track has been successfully marked as 'now playing' at the server
            case 'nowPlayingOK':
               displayMsg('Scrobbling');
               var min_time = (240 < (duration/2)) ? 240 : (duration/2); //The minimum time is 240 seconds or half the track's total length. Duration comes from updateNowPlaying()

               // cancel any previous timeout
               if (scrobbleTimeout != null)
                  clearTimeout(scrobbleTimeout);

               // set up a new timeout
               scrobbleTimeout = setTimeout(
                  function(){
                     // Turns status message into black when half of videos time has been played, to indicate that we are past the minimum time for a scrobble.
                     //$("#chrome-scrobbler-status").addClass("scrobbled");
                     //$("#chrome-scrobbler-status").attr("title","The minimum time for a scrobble has past");
                     setTimeout(scrobbleTrack, 2000);
                  }, min_time*1000
               );
               break;

            // not used yet
            case 'submitOK':
               break;

            // not used yet
            case 'submitFAIL':
               //alert('submit fail');
               break;
         }
   }
);
<|endoftext|>


<commit_before>function SVGBaseElement(data,parentContainer,globalData,comp, placeholder){
    this.globalData = globalData;
    this.comp = comp;
    this.data = data;
    this.matteElement = null;
    this.parentContainer = parentContainer;
    this.layerId = placeholder ? placeholder.layerId : 'ly_'+randomString(10);
    this.placeholder = placeholder;
    this.init();
};

createElement(BaseElement, SVGBaseElement);

SVGBaseElement.prototype.createElements = function(){
    if(this.data.td){
        if(this.data.td == 3 || this.data.td == 1){
            this.layerElement = document.createElementNS(svgNS,'g');
            var masker = document.createElementNS(svgNS,'mask');
            masker.setAttribute('id',this.layerId);
            masker.setAttribute('mask-type',this.data.td == 3 ? 'luminance':'alpha');
            masker.appendChild(this.layerElement);
            this.globalData.defs.appendChild(masker);
            ////// This is only for IE and Edge when mask if of type alpha
            if(!featureSupport.maskType && this.data.td == 1){
                masker.setAttribute('mask-type','luminance');
                var filId = randomString(10);
                var fil = filtersFactory.createFilter(filId);
                this.globalData.defs.appendChild(fil);
                fil.appendChild(filtersFactory.createAlphaToLuminanceFilter());
                var gg = document.createElementNS(svgNS,'g');
                gg.appendChild(this.layerElement);
                masker.appendChild(gg);
                gg.setAttribute('filter','url(#'+filId+')');
            }
        }else if(this.data.td == 2){
            var maskGroup = document.createElementNS(svgNS,'mask');
            maskGroup.setAttribute('id',this.layerId);
            maskGroup.setAttribute('mask-type','alpha');
            var maskGrouper = document.createElementNS(svgNS,'g');
            maskGroup.appendChild(maskGrouper);
            this.layerElement = document.createElementNS(svgNS,'g');
            var filId = randomString(10);
            var fil = filtersFactory.createFilter(filId);
            var feCTr = document.createElementNS(svgNS,'feComponentTransfer');
            feCTr.setAttribute('in','SourceGraphic');
            fil.appendChild(feCTr);
            var feFunc = document.createElementNS(svgNS,'feFuncA');
            feFunc.setAttribute('type','table');
            feFunc.setAttribute('tableValues','1.0 0.0');
            feCTr.appendChild(feFunc);
            this.globalData.defs.appendChild(fil);
            var alphaRect = document.createElementNS(svgNS,'rect');
            alphaRect.setAttribute('width',this.comp.data ? this.comp.data.w : this.globalData.compSize.w);
            alphaRect.setAttribute('height',this.comp.data ? this.comp.data.h : this.globalData.compSize.h);
            alphaRect.setAttribute('x','0');
            alphaRect.setAttribute('y','0');
            alphaRect.setAttribute('fill','#ffffff');
            alphaRect.setAttribute('opacity','0');
            maskGrouper.setAttribute('filter','url(#'+filId+')');
            maskGrouper.appendChild(alphaRect);
            maskGrouper.appendChild(this.layerElement);
            if(!featureSupport.maskType){
                maskGroup.setAttribute('mask-type','luminance');
                fil.appendChild(filtersFactory.createAlphaToLuminanceFilter());
                var gg = document.createElementNS(svgNS,'g');
                maskGrouper.appendChild(alphaRect);
                gg.appendChild(this.layerElement);
                maskGrouper.appendChild(gg);
            }
            this.globalData.defs.appendChild(maskGroup);
        }else{
            this.layerElement = document.createElementNS(svgNS,'g');
        }
        if(this.data.hasMask){
            this.maskedElement = this.layerElement;
        }
    }else if(this.data.hasMask || this.data.tt){
        this.layerElement = document.createElementNS(svgNS,'g');
        if(this.data.tt){
            this.matteElement = document.createElementNS(svgNS,'g');
            this.matteElement.appendChild(this.layerElement);
            this.baseElement = this.matteElement;
            //this.appendNodeToParent(this.matteElement);
        }else{
            this.baseElement = this.layerElement;
            //this.appendNodeToParent(this.layerElement);
        }
        if(this.data.hasMask){
            this.maskedElement = this.layerElement;
        }
    }else{
        this.layerElement = document.createElementNS(svgNS,'g');
        this.baseElement = this.layerElement;
        //this.appendNodeToParent(this.layerElement);
    }
    if((this.data.ln || this.data.cl) && (this.data.ty === 4 || this.data.ty === 0)){
        if(this.data.ln){
            this.layerElement.setAttribute('id',this.data.ln);
        }
        if(this.data.cl){
            this.layerElement.setAttribute('class',this.data.cl);
        }
    }
    if(this.data.ty === 0 && !this.checkMasks()){
        var cp = document.createElementNS(svgNS, 'clipPath');
        var pt = document.createElementNS(svgNS,'path');
        pt.setAttribute('d','M0,0 L'+this.data.w+',0'+' L'+this.data.w+','+this.data.h+' L0,'+this.data.h+'z');
        var clipId = 'cp_'+randomString(8);
        cp.setAttribute('id',clipId);
        this.layerElement.setAttribute('clip-path','url(#'+clipId+')');
        cp.appendChild(pt);
        this.globalData.defs.appendChild(cp);
    }
    if(this.data.bm !== 0){
        this.setBlendMode();
    }
    if(this.layerElement !== this.parentContainer){
        this.placeholder = null;
    }
    /* Todo performance killer
    if(this.data.sy){
        var filterID = 'st_'+randomString(10);
        var c = this.data.sy[0].c.k;
        var r = this.data.sy[0].s.k;
        var expansor = document.createElementNS(svgNS,'filter');
        expansor.setAttribute('id',filterID);
        var feFlood = document.createElementNS(svgNS,'feFlood');
        this.feFlood = feFlood;
        if(!c[0].e){
            feFlood.setAttribute('flood-color','rgb('+c[0]+','+c[1]+','+c[2]+')');
        }
        feFlood.setAttribute('result','base');
        expansor.appendChild(feFlood);
        var feMorph = document.createElementNS(svgNS,'feMorphology');
        feMorph.setAttribute('operator','dilate');
        feMorph.setAttribute('in','SourceGraphic');
        feMorph.setAttribute('result','bigger');
        this.feMorph = feMorph;
        if(!r.length){
            feMorph.setAttribute('radius',this.data.sy[0].s.k);
        }
        expansor.appendChild(feMorph);
        var feColorMatrix = document.createElementNS(svgNS,'feColorMatrix');
        feColorMatrix.setAttribute('result','mask');
        feColorMatrix.setAttribute('in','bigger');
        feColorMatrix.setAttribute('type','matrix');
        feColorMatrix.setAttribute('values','0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0');
        expansor.appendChild(feColorMatrix);
        var feComposite = document.createElementNS(svgNS,'feComposite');
        feComposite.setAttribute('result','drop');
        feComposite.setAttribute('in','base');
        feComposite.setAttribute('in2','mask');
        feComposite.setAttribute('operator','in');
        expansor.appendChild(feComposite);
        var feBlend = document.createElementNS(svgNS,'feBlend');
        feBlend.setAttribute('in','SourceGraphic');
        feBlend.setAttribute('in2','drop');
        feBlend.setAttribute('mode','normal');
        expansor.appendChild(feBlend);
        this.globalData.defs.appendChild(expansor);
        var cont = document.createElementNS(svgNS,'g');
        if(this.layerElement === this.parentContainer){
            this.layerElement = cont;
        }else{
            cont.appendChild(this.layerElement);
        }
        cont.setAttribute('filter','url(#'+filterID+')');
        if(this.data.td){
            cont.setAttribute('data-td',this.data.td);
        }
        if(this.data.td == 3){
            this.globalData.defs.appendChild(cont);
        }else if(this.data.td == 2){
            maskGrouper.appendChild(cont);
        }else if(this.data.td == 1){
            masker.appendChild(cont);
        }else{
            if(this.data.hasMask && this.data.tt){
                this.matteElement.appendChild(cont);
            }else{
                this.appendNodeToParent(cont);
            }
        }
    }*/
    if(this.data.ef){
        this.effectsManager = new SVGEffects(this);
    }
    this.checkParenting();
};

SVGBaseElement.prototype.setBlendMode = BaseElement.prototype.setBlendMode;

SVGBaseElement.prototype.renderFrame = function(parentTransform){
    if(this.data.ty === 3 || this.data.hd){
        return false;
    }

    if(!this.isVisible){
        return this.isVisible;
    }
    this.lastNum = this.currentFrameNum;
    this.finalTransform.opMdf = this.finalTransform.op.mdf;
    this.finalTransform.matMdf = this.finalTransform.mProp.mdf;
    this.finalTransform.opacity = this.finalTransform.op.v;
    if(this.firstFrame){
        this.finalTransform.opMdf = true;
        this.finalTransform.matMdf = true;
    }

    var mat;
    var finalMat = this.finalTransform.mat;

    if(this.hierarchy){
        var i, len = this.hierarchy.length;

        mat = this.finalTransform.mProp.v.props;
        finalMat.cloneFromProps(mat);
        for(i=0;i<len;i+=1){
            this.finalTransform.matMdf = this.hierarchy[i].finalTransform.mProp.mdf ? true : this.finalTransform.matMdf;
            mat = this.hierarchy[i].finalTransform.mProp.v.props;
            finalMat.transform(mat[0],mat[1],mat[2],mat[3],mat[4],mat[5],mat[6],mat[7],mat[8],mat[9],mat[10],mat[11],mat[12],mat[13],mat[14],mat[15]);
        }
    }else{
        if(this.isVisible){
            finalMat.cloneFromProps(this.finalTransform.mProp.v.props);
        }
    }
    if(parentTransform){
        mat = parentTransform.mat.props;
        finalMat.transform(mat[0],mat[1],mat[2],mat[3],mat[4],mat[5],mat[6],mat[7],mat[8],mat[9],mat[10],mat[11],mat[12],mat[13],mat[14],mat[15]);
        this.finalTransform.opacity *= parentTransform.opacity;
        this.finalTransform.opMdf = parentTransform.opMdf ? true : this.finalTransform.opMdf;
        this.finalTransform.matMdf = parentTransform.matMdf ? true : this.finalTransform.matMdf;
    }
    if(this.finalTransform.matMdf && this.layerElement){
        this.layerElement.setAttribute('transform',finalMat.to2dCSS());
    }
    if(this.finalTransform.opMdf && this.layerElement){
        this.layerElement.setAttribute('opacity',this.finalTransform.opacity);
    }

    if(this.data.hasMask){
        this.maskManager.renderFrame(finalMat);
    }
    if(this.effectsManager){
        this.effectsManager.renderFrame(this.firstFrame);
    }
    return this.isVisible;
};

SVGBaseElement.prototype.destroy = function(){
    this.layerElement = null;
    this.parentContainer = null;
    if(this.matteElement) {
        this.matteElement = null;
    }
    if(this.maskManager) {
        this.maskManager.destroy();
    }
};

SVGBaseElement.prototype.getBaseElement = function(){
    return this.baseElement;
};
SVGBaseElement.prototype.addMasks = function(data){
    this.maskManager = new MaskElement(data,this,this.globalData);
};

SVGBaseElement.prototype.setMatte = function(id){
    if(!this.matteElement){
        return;
    }
    this.matteElement.setAttribute("mask", "url(#" + id + ")");
};

SVGBaseElement.prototype.setMatte = function(id){
    if(!this.matteElement){
        return;
    }
    this.matteElement.setAttribute("mask", "url(#" + id + ")");
};

SVGBaseElement.prototype.hide = function(){

};
<commit_msg>inverting alpha with matrix<commit_after>function SVGBaseElement(data,parentContainer,globalData,comp, placeholder){
    this.globalData = globalData;
    this.comp = comp;
    this.data = data;
    this.matteElement = null;
    this.parentContainer = parentContainer;
    this.layerId = placeholder ? placeholder.layerId : 'ly_'+randomString(10);
    this.placeholder = placeholder;
    this.init();
};

createElement(BaseElement, SVGBaseElement);

SVGBaseElement.prototype.createElements = function(){
    if(this.data.td){
        if(this.data.td == 3 || this.data.td == 1){
            this.layerElement = document.createElementNS(svgNS,'g');
            var masker = document.createElementNS(svgNS,'mask');
            masker.setAttribute('id',this.layerId);
            masker.setAttribute('mask-type',this.data.td == 3 ? 'luminance':'alpha');
            masker.appendChild(this.layerElement);
            this.globalData.defs.appendChild(masker);
            ////// This is only for IE and Edge when mask if of type alpha
            if(!featureSupport.maskType && this.data.td == 1){
                masker.setAttribute('mask-type','luminance');
                var filId = randomString(10);
                var fil = filtersFactory.createFilter(filId);
                this.globalData.defs.appendChild(fil);
                fil.appendChild(filtersFactory.createAlphaToLuminanceFilter());
                var gg = document.createElementNS(svgNS,'g');
                gg.appendChild(this.layerElement);
                masker.appendChild(gg);
                gg.setAttribute('filter','url(#'+filId+')');
            }
        }else if(this.data.td == 2){
            var maskGroup = document.createElementNS(svgNS,'mask');
            maskGroup.setAttribute('id',this.layerId);
            maskGroup.setAttribute('mask-type','alpha');
            var maskGrouper = document.createElementNS(svgNS,'g');
            maskGroup.appendChild(maskGrouper);
            this.layerElement = document.createElementNS(svgNS,'g');
            var filId = randomString(10);
            var fil = filtersFactory.createFilter(filId);
            ////

            var feColorMatrix = document.createElementNS(svgNS,'feColorMatrix');
            feColorMatrix.setAttribute('type','matrix');
            feColorMatrix.setAttribute('color-interpolation-filters','sRGB');
            feColorMatrix.setAttribute('values','1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 -1 1');
            fil.appendChild(feColorMatrix);

            ////
            /*var feCTr = document.createElementNS(svgNS,'feComponentTransfer');
            feCTr.setAttribute('in','SourceGraphic');
            fil.appendChild(feCTr);
            var feFunc = document.createElementNS(svgNS,'feFuncA');
            feFunc.setAttribute('type','table');
            feFunc.setAttribute('tableValues','1.0 0.0');
            feCTr.appendChild(feFunc);*/
            this.globalData.defs.appendChild(fil);
            var alphaRect = document.createElementNS(svgNS,'rect');
            alphaRect.setAttribute('width',this.comp.data ? this.comp.data.w : this.globalData.compSize.w);
            alphaRect.setAttribute('height',this.comp.data ? this.comp.data.h : this.globalData.compSize.h);
            alphaRect.setAttribute('x','0');
            alphaRect.setAttribute('y','0');
            alphaRect.setAttribute('fill','#ffffff');
            alphaRect.setAttribute('opacity','0');
            maskGrouper.setAttribute('filter','url(#'+filId+')');
            maskGrouper.appendChild(alphaRect);
            maskGrouper.appendChild(this.layerElement);
            if(!featureSupport.maskType){
                maskGroup.setAttribute('mask-type','luminance');
                fil.appendChild(filtersFactory.createAlphaToLuminanceFilter());
                var gg = document.createElementNS(svgNS,'g');
                maskGrouper.appendChild(alphaRect);
                gg.appendChild(this.layerElement);
                maskGrouper.appendChild(gg);
            }
            this.globalData.defs.appendChild(maskGroup);
        }else{
            this.layerElement = document.createElementNS(svgNS,'g');
        }
        if(this.data.hasMask){
            this.maskedElement = this.layerElement;
        }
    }else if(this.data.hasMask || this.data.tt){
        this.layerElement = document.createElementNS(svgNS,'g');
        if(this.data.tt){
            this.matteElement = document.createElementNS(svgNS,'g');
            this.matteElement.appendChild(this.layerElement);
            this.baseElement = this.matteElement;
            //this.appendNodeToParent(this.matteElement);
        }else{
            this.baseElement = this.layerElement;
            //this.appendNodeToParent(this.layerElement);
        }
        if(this.data.hasMask){
            this.maskedElement = this.layerElement;
        }
    }else{
        this.layerElement = document.createElementNS(svgNS,'g');
        this.baseElement = this.layerElement;
        //this.appendNodeToParent(this.layerElement);
    }
    if((this.data.ln || this.data.cl) && (this.data.ty === 4 || this.data.ty === 0)){
        if(this.data.ln){
            this.layerElement.setAttribute('id',this.data.ln);
        }
        if(this.data.cl){
            this.layerElement.setAttribute('class',this.data.cl);
        }
    }
    if(this.data.ty === 0 && !this.checkMasks()){
        var cp = document.createElementNS(svgNS, 'clipPath');
        var pt = document.createElementNS(svgNS,'path');
        pt.setAttribute('d','M0,0 L'+this.data.w+',0'+' L'+this.data.w+','+this.data.h+' L0,'+this.data.h+'z');
        var clipId = 'cp_'+randomString(8);
        cp.setAttribute('id',clipId);
        this.layerElement.setAttribute('clip-path','url(#'+clipId+')');
        cp.appendChild(pt);
        this.globalData.defs.appendChild(cp);
    }
    if(this.data.bm !== 0){
        this.setBlendMode();
    }
    if(this.layerElement !== this.parentContainer){
        this.placeholder = null;
    }
    /* Todo performance killer
    if(this.data.sy){
        var filterID = 'st_'+randomString(10);
        var c = this.data.sy[0].c.k;
        var r = this.data.sy[0].s.k;
        var expansor = document.createElementNS(svgNS,'filter');
        expansor.setAttribute('id',filterID);
        var feFlood = document.createElementNS(svgNS,'feFlood');
        this.feFlood = feFlood;
        if(!c[0].e){
            feFlood.setAttribute('flood-color','rgb('+c[0]+','+c[1]+','+c[2]+')');
        }
        feFlood.setAttribute('result','base');
        expansor.appendChild(feFlood);
        var feMorph = document.createElementNS(svgNS,'feMorphology');
        feMorph.setAttribute('operator','dilate');
        feMorph.setAttribute('in','SourceGraphic');
        feMorph.setAttribute('result','bigger');
        this.feMorph = feMorph;
        if(!r.length){
            feMorph.setAttribute('radius',this.data.sy[0].s.k);
        }
        expansor.appendChild(feMorph);
        var feColorMatrix = document.createElementNS(svgNS,'feColorMatrix');
        feColorMatrix.setAttribute('result','mask');
        feColorMatrix.setAttribute('in','bigger');
        feColorMatrix.setAttribute('type','matrix');
        feColorMatrix.setAttribute('values','0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0');
        expansor.appendChild(feColorMatrix);
        var feComposite = document.createElementNS(svgNS,'feComposite');
        feComposite.setAttribute('result','drop');
        feComposite.setAttribute('in','base');
        feComposite.setAttribute('in2','mask');
        feComposite.setAttribute('operator','in');
        expansor.appendChild(feComposite);
        var feBlend = document.createElementNS(svgNS,'feBlend');
        feBlend.setAttribute('in','SourceGraphic');
        feBlend.setAttribute('in2','drop');
        feBlend.setAttribute('mode','normal');
        expansor.appendChild(feBlend);
        this.globalData.defs.appendChild(expansor);
        var cont = document.createElementNS(svgNS,'g');
        if(this.layerElement === this.parentContainer){
            this.layerElement = cont;
        }else{
            cont.appendChild(this.layerElement);
        }
        cont.setAttribute('filter','url(#'+filterID+')');
        if(this.data.td){
            cont.setAttribute('data-td',this.data.td);
        }
        if(this.data.td == 3){
            this.globalData.defs.appendChild(cont);
        }else if(this.data.td == 2){
            maskGrouper.appendChild(cont);
        }else if(this.data.td == 1){
            masker.appendChild(cont);
        }else{
            if(this.data.hasMask && this.data.tt){
                this.matteElement.appendChild(cont);
            }else{
                this.appendNodeToParent(cont);
            }
        }
    }*/
    if(this.data.ef){
        this.effectsManager = new SVGEffects(this);
    }
    this.checkParenting();
};

SVGBaseElement.prototype.setBlendMode = BaseElement.prototype.setBlendMode;

SVGBaseElement.prototype.renderFrame = function(parentTransform){
    if(this.data.ty === 3 || this.data.hd){
        return false;
    }

    if(!this.isVisible){
        return this.isVisible;
    }
    this.lastNum = this.currentFrameNum;
    this.finalTransform.opMdf = this.finalTransform.op.mdf;
    this.finalTransform.matMdf = this.finalTransform.mProp.mdf;
    this.finalTransform.opacity = this.finalTransform.op.v;
    if(this.firstFrame){
        this.finalTransform.opMdf = true;
        this.finalTransform.matMdf = true;
    }

    var mat;
    var finalMat = this.finalTransform.mat;

    if(this.hierarchy){
        var i, len = this.hierarchy.length;

        mat = this.finalTransform.mProp.v.props;
        finalMat.cloneFromProps(mat);
        for(i=0;i<len;i+=1){
            this.finalTransform.matMdf = this.hierarchy[i].finalTransform.mProp.mdf ? true : this.finalTransform.matMdf;
            mat = this.hierarchy[i].finalTransform.mProp.v.props;
            finalMat.transform(mat[0],mat[1],mat[2],mat[3],mat[4],mat[5],mat[6],mat[7],mat[8],mat[9],mat[10],mat[11],mat[12],mat[13],mat[14],mat[15]);
        }
    }else{
        if(this.isVisible){
            finalMat.cloneFromProps(this.finalTransform.mProp.v.props);
        }
    }
    if(parentTransform){
        mat = parentTransform.mat.props;
        finalMat.transform(mat[0],mat[1],mat[2],mat[3],mat[4],mat[5],mat[6],mat[7],mat[8],mat[9],mat[10],mat[11],mat[12],mat[13],mat[14],mat[15]);
        this.finalTransform.opacity *= parentTransform.opacity;
        this.finalTransform.opMdf = parentTransform.opMdf ? true : this.finalTransform.opMdf;
        this.finalTransform.matMdf = parentTransform.matMdf ? true : this.finalTransform.matMdf;
    }
    if(this.finalTransform.matMdf && this.layerElement){
        this.layerElement.setAttribute('transform',finalMat.to2dCSS());
    }
    if(this.finalTransform.opMdf && this.layerElement){
        this.layerElement.setAttribute('opacity',this.finalTransform.opacity);
    }

    if(this.data.hasMask){
        this.maskManager.renderFrame(finalMat);
    }
    if(this.effectsManager){
        this.effectsManager.renderFrame(this.firstFrame);
    }
    return this.isVisible;
};

SVGBaseElement.prototype.destroy = function(){
    this.layerElement = null;
    this.parentContainer = null;
    if(this.matteElement) {
        this.matteElement = null;
    }
    if(this.maskManager) {
        this.maskManager.destroy();
    }
};

SVGBaseElement.prototype.getBaseElement = function(){
    return this.baseElement;
};
SVGBaseElement.prototype.addMasks = function(data){
    this.maskManager = new MaskElement(data,this,this.globalData);
};

SVGBaseElement.prototype.setMatte = function(id){
    if(!this.matteElement){
        return;
    }
    this.matteElement.setAttribute("mask", "url(#" + id + ")");
};

SVGBaseElement.prototype.setMatte = function(id){
    if(!this.matteElement){
        return;
    }
    this.matteElement.setAttribute("mask", "url(#" + id + ")");
};

SVGBaseElement.prototype.hide = function(){

};
<|endoftext|>


<commit_before>"use strict";

angular.module('arethusa.core').service('arethusaGrid', [
  'gridsterConfig',
  '$window',
  'plugins',
  '$rootScope',
  'notifier',
  function(gridsterConfig, $window, plugins, $rootScope, notifier) {
    var self = this;

    var win = angular.element($window);

    this.settings = {
      dragging: true,
      resizing: true,
      pushing:  true,
      floating: true,
    };

    this.setDragging = function(val) { self.options.draggable.enabled = val; };
    this.setResizing = function(val) { self.options.resizable.enabled = val; };
    this.setPushing  = function(val) { self.options.pushing  = val; };
    this.setFloating = function(val) { self.options.floating = val; };

    this.options = angular.extend(gridsterConfig, {
      columns: 20,
      rowHeight: 'match',
      defaultSizeX: 6,
      defaultSizeY: 4,
      resizable: {
        enabled: true,
        handles: ['n', 'e', 's', 'w', 'ne', 'nw', 'se', 'sw'],
        stop: function() { win.triggerHandler('resize'); }
      }
    });

    function Item(plugin, size, position, style) {
      size = size || [];
      position = position || [];
      return {
        sizeX: size[0],
        sizeY: size[1],
        row: position[0],
        col: position[1],
        plugin: plugin,
        style: style
      };
    }

    this.items = [
      new Item('text',     [14, 1], [0, 0]),
      new Item('depTree',  [9, 8],  [2, 0], { overflow: 'hidden'} ),
      new Item('comments', [5, 8],  [1, 9]),
      new Item('search',   [6, 2],  [0, 14]),
      new Item('morph',    [6, 4],  [2, 14]),
      new Item('relation', [6, 3],  [7, 14])
    ];

    this.addItem = function(name) {
      self.items.push(new Item(name));
      notifier.success(name + ' added to the grid!');
    };

    function findItem(name) {
      var res;
      for (var i = self.items.length - 1; i >= 0; i--){
        var el = self.items[i];
        if (el.plugin === name) {
          res = el;
          break;
        }
      }
      return res;
    }

    this.removeItem = function(name) {
      var i = self.items.indexOf(findItem(name));
      self.items.splice(i, 1);
      notifier.info(name + ' removed from grid!');
    };

    this.toggleItem = function(name) {
      // Mind that these function is inverted due to its
      // usage in an input checkbox.
      // We already can read the updated value here and
      // therefore need to invert our action.
      if (self.itemList[name]) {
        self.addItem(name);
      } else {
        self.removeItem(name);
        //self.itemList[name] ;
      }
    };

    this.init = function() {
      self.itemList = arethusaUtil.inject({}, plugins.all, function(memo, name, pl) {
        memo[name] = false;
      });

      angular.forEach(self.items, function(el, i) {
        self.itemList[el.plugin] = true;
      });
    };

    $rootScope.$on('pluginsLoaded', self.init);
  }
]);
<commit_msg>Change default grid layout a bit<commit_after>"use strict";

angular.module('arethusa.core').service('arethusaGrid', [
  'gridsterConfig',
  '$window',
  'plugins',
  '$rootScope',
  'notifier',
  function(gridsterConfig, $window, plugins, $rootScope, notifier) {
    var self = this;

    var win = angular.element($window);

    this.settings = {
      dragging: true,
      resizing: true,
      pushing:  true,
      floating: true,
    };

    this.setDragging = function(val) { self.options.draggable.enabled = val; };
    this.setResizing = function(val) { self.options.resizable.enabled = val; };
    this.setPushing  = function(val) { self.options.pushing  = val; };
    this.setFloating = function(val) { self.options.floating = val; };

    this.options = angular.extend(gridsterConfig, {
      columns: 20,
      rowHeight: 'match',
      defaultSizeX: 6,
      defaultSizeY: 4,
      resizable: {
        enabled: true,
        handles: ['n', 'e', 's', 'w', 'ne', 'nw', 'se', 'sw'],
        stop: function() { win.triggerHandler('resize'); }
      }
    });

    function Item(plugin, size, position, style) {
      size = size || [];
      position = position || [];
      return {
        sizeX: size[0],
        sizeY: size[1],
        row: position[0],
        col: position[1],
        plugin: plugin,
        style: style
      };
    }

    this.items = [
      new Item('text',     [14, 1], [0, 0]),
      new Item('depTree',  [9, 8],  [2, 0], { overflow: 'hidden'} ),
      new Item('morph',    [5, 8],  [1, 9]),
      new Item('search',   [6, 2],  [0, 14]),
      new Item('relation', [6, 4],  [2, 14]),
      new Item('artificialToken', [6, 4],  [7, 14])
    ];

    this.addItem = function(name) {
      self.items.push(new Item(name));
      notifier.success(name + ' added to the grid!');
    };

    function findItem(name) {
      var res;
      for (var i = self.items.length - 1; i >= 0; i--){
        var el = self.items[i];
        if (el.plugin === name) {
          res = el;
          break;
        }
      }
      return res;
    }

    this.removeItem = function(name) {
      var i = self.items.indexOf(findItem(name));
      self.items.splice(i, 1);
      notifier.info(name + ' removed from grid!');
    };

    this.toggleItem = function(name) {
      // Mind that these function is inverted due to its
      // usage in an input checkbox.
      // We already can read the updated value here and
      // therefore need to invert our action.
      if (self.itemList[name]) {
        self.addItem(name);
      } else {
        self.removeItem(name);
        //self.itemList[name] ;
      }
    };

    this.init = function() {
      self.itemList = arethusaUtil.inject({}, plugins.all, function(memo, name, pl) {
        memo[name] = false;
      });

      angular.forEach(self.items, function(el, i) {
        self.itemList[el.plugin] = true;
      });
    };

    $rootScope.$on('pluginsLoaded', self.init);
  }
]);
<|endoftext|>


<commit_before>angular.module('fleetonrails.directives', [])

    .directive('navbar', function() {
        return {
            restrict: 'E',
            templateUrl: 'partials/navbar.html'
        }
    });<commit_msg>Controller inside directive<commit_after>angular.module('fleetonrails.directives', [])

    .directive('navbar',function() {
        return {
            restrict: 'E',
            templateUrl: 'partials/navbar.html',
            controller: function($scope,MeService,$location,loginService){
                MeService.get(function (user) {
                    $scope.user = user;
                }, function(data) {
                    alert('Not authorized')
                    $location.path('/')
                });

                $scope.logout = function () {
                    loginService.logout();
                    $location.path('/');
                };
            }
        }
    });<|endoftext|>


<commit_before>'use strict';

class Singleton {
    constructor(data) {
        if (Singleton.prototype.Instance === undefined) {
            this.data = data;
            Singleton.prototype.Instance = this;
        }
        return Singleton.prototype.Instance;
    }
}

let ob1 = new Singleton("one");
let ob2 = new Singleton("two");
let ob3 = new Singleton("Three");
ob2.init = '111';

console.log(ob1 === ob2);
console.log(ob1 === ob3);

console.log(ob1);
console.log(ob2);
console.log(ob3);<commit_msg>update<commit_after>'use strict';

class Singleton {
    constructor(data) {
        if (Singleton.prototype.Instance === undefined) {
            this.data = data;
            Singleton.prototype.Instance = this;
        }
        return Singleton.prototype.Instance;
    }
}

let ob1 = new Singleton("one");
let ob2 = new Singleton("two");
let ob3 = new Singleton("Three");
ob2.init = 'Object flg';

console.log(ob1 === ob2);
console.log(ob1 === ob3);

console.log(ob1);
console.log(ob2);
console.log(ob3);<|endoftext|>


<commit_before>/*global module, require*/
var util = require('util'),
    sys = require('sys'),
    fs = require('fs'),
    path = require('path'),
    step = require('step'),
    relations = require('./relations'),
    _ = require('underscore'),
    graphviz = require('graphviz'),
    error = require('./error'),
    allIndices = {
        relation: ['id', 'type', 'from', 'to'],
        asset: ['id', 'url', 'type']
    };

var SiteGraph = module.exports = function (config) {
    _.extend(this, config || {});
    this.assets = [];
    this.relations = [];
    this.indices = {};
    _.each(allIndices, function (indexNames, indexType) {
       this.indices[indexType] = {};
       indexNames.forEach(function (indexName) {
           this.indices[indexType][indexName] = {};
       }, this);
    }, this);
};

SiteGraph.prototype = {
    addToIndices: function (indexType, obj) {
        allIndices[indexType].forEach(function (indexName) {
            if (indexName in obj) {
                var type = typeof obj[indexName],
                    key;
                if (type === 'string' || type === 'number' || type === 'boolean') {
                    key = obj[indexName];
                } else if (type === 'object' && 'id' in obj[indexName]) {
                    key = obj[indexName].id;
                }
                if (typeof key !== 'undefined') {
                    var index = this.indices[indexType][indexName];
                    if (!(key in index)) {
                        index[key] = [obj];
                    } else {
                        index[key].push(obj);
                    }
                }
            }
        }, this);
    },

    removeFromIndices: function (indexType, obj) {
        allIndices[indexType].forEach(function (indexName) {
            if (indexName in obj) {
                var type = typeof obj[indexName],
                    key;
                if (type === 'string' || type === 'number' || type === 'boolean') {
                    key = obj[indexName];
                } else if (type === 'object' && 'id' in obj[indexName]) {
                    key = obj[indexName].id;
                }
                if (typeof key !== 'undefined') {
                    var index = this.indices[indexType][indexName],
                        i = index[key].indexOf(obj);
                    if (i !== -1) {
                        index[key].splice(i, 1);
                    } else {
                        throw "removeFromIndices: object not found in index!";
                    }
                }
            }
        }, this);
    },

    lookupIndex: function (indexType, indexName, value) {
        return this.indices[indexType][indexName][typeof value === 'object' ? value.id : value] || [];
    },

    existsInIndex: function (indexType, indexName, value) {
        return this.lookupIndex(indexType, indexName, value).length > 0;
    },

    findRelations: function (indexName, value) {
        return this.lookupIndex('relation', indexName, value);
    },

    findAssets: function (indexName, value) {
        return this.lookupIndex('asset', indexName, value);
    },

    registerAsset: function (asset) {
        this.assets.push(asset);
        this.addToIndices('asset', asset);
    },

    unregisterAsset: function (asset) {
        this.relations.splice(this.assets.indexOf(asset), 1);
        this.removeFromIndices('relation', asset);
    },

    // Relations must be registered in order
    registerRelation: function (relation, position, adjacentRelation) { // position and adjacentRelation are optional,
        position = position || 'last';

        if (!relation.node) { // Assume there's a node if it's already attached
            if (adjacentRelation.from !== relation.from) {
                throw "registerRelation: adjacentRelation.from !== relation.from!";
            }
            relation.from.attachRelation(relation, position, adjacentRelation);
        }
        if (position === 'last') {
            this.relations.push(relation);
        } else if (position === 'first') {
            this.relations.unshift(relation);
        } else { // Assume 'before' or 'after'
            var i = this.relations.indexOf(adjacentRelation) + (position === 'after' ? 1 : 0);
            this.relations.splice(i, 0, relation);
        }
        this.addToIndices('relation', relation); //, adjacentRelation, position... have to be there to preserve order
    },

    unregisterRelation: function (relation) {
        this.relations.splice(this.relations.indexOf(relation), 1);
        this.removeFromIndices('relation', relation);
    },

    // This cries out for a rich query facility/DSL!
    lookupSubgraph: function (startAsset, relationLambda) { // preorder
        var that = this,
            subgraph = new SiteGraph();
        function traverse (asset) {
            if (!subgraph.existsInIndex('asset', 'id', asset)) {
                subgraph.registerAsset(asset);
                that.lookupIndex('relation', 'from', asset).forEach(function (relation) {
                    traverse(relation.to);
                    if (!subgraph.existsInIndex('relation', 'id', relation)) {
                        subgraph.registerRelation(relation);
                    }
                });
            }
        }
        traverse(startAsset);
        return subgraph;
    },

    toGraphViz: function () {
        var g = graphviz.digraph("G");
        this.assets.forEach(function (asset) {
            g.addNode(asset.id.toString(), {label: 'url' in asset ? path.basename(asset.url) : 'inline'});
        }, this);
        this.relations.forEach(function (relation) {
            var edge = g.addEdge(relation.from.id.toString(), relation.to.id.toString());
        }, this);
        console.log(g.to_dot());
        g.output('png', 'graph.png');
    }
};
<commit_msg>SiteGraph.registerRelation: Propagating 'position' and 'adjacentRelation' into addToIndex.<commit_after>/*global module, require*/
var util = require('util'),
    sys = require('sys'),
    fs = require('fs'),
    path = require('path'),
    step = require('step'),
    relations = require('./relations'),
    _ = require('underscore'),
    graphviz = require('graphviz'),
    error = require('./error'),
    allIndices = {
        relation: ['id', 'type', 'from', 'to'],
        asset: ['id', 'url', 'type']
    };

var SiteGraph = module.exports = function (config) {
    _.extend(this, config || {});
    this.assets = [];
    this.relations = [];
    this.indices = {};
    _.each(allIndices, function (indexNames, indexType) {
       this.indices[indexType] = {};
       indexNames.forEach(function (indexName) {
           this.indices[indexType][indexName] = {};
       }, this);
    }, this);
};

SiteGraph.prototype = {
    addToIndices: function (indexType, obj, position, adjacentObj) { // position and adjacentRelation are optional
        allIndices[indexType].forEach(function (indexName) {
            position = position || 'last';
            if (indexName in obj) {
                var type = typeof obj[indexName],
                    key;
                if (type === 'string' || type === 'number' || type === 'boolean') {
                    key = obj[indexName];
                } else if (type === 'object' && 'id' in obj[indexName]) {
                    key = obj[indexName].id;
                }
                if (typeof key !== 'undefined') {
                    var index = this.indices[indexType][indexName];
                    if (!(key in index)) {
                        index[key] = [obj];
                    } else {
                        if (position === 'last') {
                            index[key].push(obj);
                        } else if (position === 'first') {
                            index[key].unshift(obj);
                        } else { // 'before' or 'after'
                            var i = index[key].indexOf(adjacentObj) + (position === 'after' ? 1 : 0);
                            index[key].splice(i, 0, obj);
                        }
                    }
                }
            }
        }, this);
    },

    removeFromIndices: function (indexType, obj) {
        allIndices[indexType].forEach(function (indexName) {
            if (indexName in obj) {
                var type = typeof obj[indexName],
                    key;
                if (type === 'string' || type === 'number' || type === 'boolean') {
                    key = obj[indexName];
                } else if (type === 'object' && 'id' in obj[indexName]) {
                    key = obj[indexName].id;
                }
                if (typeof key !== 'undefined') {
                    var index = this.indices[indexType][indexName],
                        i = index[key].indexOf(obj);
                    if (i !== -1) {
                        index[key].splice(i, 1);
                    } else {
                        throw "removeFromIndices: object not found in index!";
                    }
                }
            }
        }, this);
    },

    lookupIndex: function (indexType, indexName, value) {
        return this.indices[indexType][indexName][typeof value === 'object' ? value.id : value] || [];
    },

    existsInIndex: function (indexType, indexName, value) {
        return this.lookupIndex(indexType, indexName, value).length > 0;
    },

    findRelations: function (indexName, value) {
        return this.lookupIndex('relation', indexName, value);
    },

    findAssets: function (indexName, value) {
        return this.lookupIndex('asset', indexName, value);
    },

    registerAsset: function (asset) {
        this.assets.push(asset);
        this.addToIndices('asset', asset);
    },

    unregisterAsset: function (asset) {
        this.relations.splice(this.assets.indexOf(asset), 1);
        this.removeFromIndices('relation', asset);
    },

    // Relations must be registered in order
    registerRelation: function (relation, position, adjacentRelation) { // position and adjacentRelation are optional,
        position = position || 'last';
        if (!relation.node) { // Assume there's a node if it's already attached
            if (adjacentRelation.from !== relation.from) {
                throw "registerRelation: adjacentRelation.from !== relation.from!";
            }
            relation.from.attachRelation(relation, position, adjacentRelation);
        }
        if (position === 'last') {
            this.relations.push(relation);
        } else if (position === 'first') {
            this.relations.unshift(relation);
        } else { // Assume 'before' or 'after'
            var i = this.relations.indexOf(adjacentRelation) + (position === 'after' ? 1 : 0);
            this.relations.splice(i, 0, relation);
        }
        this.addToIndices('relation', relation, position, adjacentRelation);
    },

    unregisterRelation: function (relation) {
        this.relations.splice(this.relations.indexOf(relation), 1);
        this.removeFromIndices('relation', relation);
    },

    // This cries out for a rich query facility/DSL!
    lookupSubgraph: function (startAsset, relationLambda) { // preorder
        var that = this,
            subgraph = new SiteGraph();
        function traverse (asset) {
            if (!subgraph.existsInIndex('asset', 'id', asset)) {
                subgraph.registerAsset(asset);
                that.lookupIndex('relation', 'from', asset).forEach(function (relation) {
                    traverse(relation.to);
                    if (!subgraph.existsInIndex('relation', 'id', relation)) {
                        subgraph.registerRelation(relation);
                    }
                });
            }
        }
        traverse(startAsset);
        return subgraph;
    },

    toGraphViz: function () {
        var g = graphviz.digraph("G");
        this.assets.forEach(function (asset) {
            g.addNode(asset.id.toString(), {label: 'url' in asset ? path.basename(asset.url) : 'inline'});
        }, this);
        this.relations.forEach(function (relation) {
            var edge = g.addEdge(relation.from.id.toString(), relation.to.id.toString());
        }, this);
        console.log(g.to_dot());
        g.output('png', 'graph.png');
    }
};
<|endoftext|>


<commit_before>(function () {
	var $D = Date;
	var __ = function (key) {
		var output, split, length, last;
		if (Date.CultureStrings && Date.CultureStrings[key]) {
			output = Date.CultureStrings[key];
		} else {
			output = key;
			split = key.split("_");
			length = split.length;
			if (length > 1 && key.charAt(0) !== "^") {
				// if the key isn't a regex and it has a split.
				last = split[(length - 1)].toLowerCase();
				if (last === "initial" || last === "abbr") {
					output = split[0];
				}
			}
		}
		if (key.charAt(0) === "^") {
			// it's a regex
			output = new RegExp(key, "i");
		}
		return output;
	};

	var CultureInfo = function () {
		var buildTimeZones = function (data) {
			var zone;
			for (zone in data.abbreviatedTimeZoneStandard) {
				if (data.abbreviatedTimeZoneStandard.hasOwnProperty(zone)) {
					data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneStandard[zone]});
				}
			}
			for (zone in data.abbreviatedTimeZoneDST) {
				if (data.abbreviatedTimeZoneDST.hasOwnProperty(zone)) {
					data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneDST[zone], dst: true});
				}
			}
			return data.timezones;
		};
		var info =  {
			name: __("name"),
			englishName: __("englishName"),
			nativeName: __("nativeName"),
			/* Day Name Strings */
			dayNames: [
				__("Sunday"),
				__("Monday"),
				__("Tuesday"),
				__("Wednesday"),
				__("Thursday"),
				__("Friday"),
				__("Saturday")
			],
			abbreviatedDayNames: [
				__("Sun"),
				__("Mon"),
				__("Tue"),
				__("Wed"),
				__("Thu"),
				__("Fri"),
				__("Sat")
			],
			shortestDayNames: [
				__("Su"),
				__("Mo"),
				__("Tu"),
				__("We"),
				__("Th"),
				__("Fr"),
				__("Sa")
			],
			firstLetterDayNames: [
				__("S_Sun_Initial"),
				__("M_Mon_Initial"),
				__("T_Tues_Initial"),
				__("W_Wed_Initial"),
				__("T_Thu_Initial"),
				__("F_Fri_Initial"),
				__("S_Sat_Initial")
			],

			/* Month Name Strings */
			monthNames: [
				__("January"),
				__("February"),
				__("March"),
				__("April"),
				__("May"),
				__("June"),
				__("July"),
				__("August"),
				__("September"),
				__("October"),
				__("November"),
				__("December")
			],
			abbreviatedMonthNames: [
				__("Jan_Abbr"),
				__("Feb_Abbr"),
				__("Mar_Abbr"),
				__("Apr_Abbr"),
				__("May_Abbr"),
				__("Jun_Abbr"),
				__("Jul_Abbr"),
				__("Aug_Abbr"),
				__("Sep_Abbr"),
				__("Oct_Abbr"),
				__("Nov_Abbr"),
				__("Dec_Abbr")
			],
			/* AM/PM Designators */
			amDesignator: __("AM"),
			pmDesignator: __("PM"),
			firstDayOfWeek: __("firstDayOfWeek"),
			twoDigitYearMax: __("twoDigitYearMax"),
			dateElementOrder: __("mdy"),
			/* Standard date and time format patterns */
			formatPatterns: {
				shortDate: __("M/d/yyyy"),
				longDate: __("dddd, MMMM dd, yyyy"),
				shortTime: __("h:mm tt"),
				longTime: __("h:mm:ss tt"),
				fullDateTime: __("dddd, MMMM dd, yyyy h:mm:ss tt"),
				sortableDateTime: __("yyyy-MM-ddTHH:mm:ss"),
				universalSortableDateTime: __("yyyy-MM-dd HH:mm:ssZ"),
				rfc1123: __("ddd, dd MMM yyyy HH:mm:ss"),
				monthDay: __("MMMM dd"),
				yearMonth: __("MMMM, yyyy")
			},
			regexPatterns: {
				jan: __("^jan(uary)?"),
				feb: __("^feb(ruary)?"),
				mar: __("^mar(ch)?"),
				apr: __("^apr(il)?"),
				may: __("^may"),
				jun: __("^jun(e)?"),
				jul: __("^jul(y)?"),
				aug: __("^aug(ust)?"),
				sep: __("^sep(t(ember)?)?"),
				oct: __("^oct(ober)?"),
				nov: __("^nov(ember)?"),
				dec: __("^dec(ember)?"),
				sun: __("^su(n(day)?)?"),
				mon: __("^mo(n(day)?)?"),
				tue: __("^tu(e(s(day)?)?)?"),
				wed: __("^we(d(nesday)?)?"),
				thu: __("^th(u(r(s(day)?)?)?)?"),
				fri: __("^fr(i(day)?)?"),
				sat: __("^sa(t(urday)?)?"),
				future: __("^next"),
				past: __("^last|past|prev(ious)?"),
				add: __("^(\\+|aft(er)?|from|hence)"),
				subtract: __("^(\\-|bef(ore)?|ago)"),
				yesterday: __("^yes(terday)?"),
				today: __("^t(od(ay)?)?"),
				tomorrow: __("^tom(orrow)?"),
				now: __("^n(ow)?"),
				millisecond: __("^ms|milli(second)?s?"),
				second: __("^sec(ond)?s?"),
				minute: __("^mn|min(ute)?s?"),
				hour: __("^h(our)?s?"),
				week: __("^w(eek)?s?"),
				month: __("^m(onth)?s?"),
				day: __("^d(ay)?s?"),
				year: __("^y(ear)?s?"),
				shortMeridian: __("^(a|p)"),
				longMeridian: __("^(a\\.?m?\\.?|p\\.?m?\\.?)"),
				timezone: __("^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)"),
				ordinalSuffix: __("^\\s*(st|nd|rd|th)"),
				timeContext: __("^\\s*(\\:|a(?!u|p)|p)")
			},
			timezones: [],
			abbreviatedTimeZoneDST: {},
			abbreviatedTimeZoneStandard: {}
		};

		info.abbreviatedTimeZoneDST[__("CHADT")] = "+1345";
		info.abbreviatedTimeZoneDST[__("NZDT")] = "+1300";
		info.abbreviatedTimeZoneDST[__("AEDT")] = "+1100";
		info.abbreviatedTimeZoneDST[__("ACDT")] = "+1030";
		info.abbreviatedTimeZoneDST[__("AZST")] = "+0500";
		info.abbreviatedTimeZoneDST[__("IRDT")] = "+0430";
		info.abbreviatedTimeZoneDST[__("EEST")] = "+0300";
		info.abbreviatedTimeZoneDST[__("CEST")] = "+0200";
		info.abbreviatedTimeZoneDST[__("BST")] = "+0100";
		info.abbreviatedTimeZoneDST[__("PMDT")] = "-0200";
		info.abbreviatedTimeZoneDST[__("ADT")] = "-0300";
		info.abbreviatedTimeZoneDST[__("NDT")] = "-0230";
		info.abbreviatedTimeZoneDST[__("EDT")] = "-0400";
		info.abbreviatedTimeZoneDST[__("CDT")] = "-0500";
		info.abbreviatedTimeZoneDST[__("MDT")] = "-0600";
		info.abbreviatedTimeZoneDST[__("PDT")] = "-0700";
		info.abbreviatedTimeZoneDST[__("AKDT")] = "-0800";
		info.abbreviatedTimeZoneDST[__("HADT")] = "-0900";

		info.abbreviatedTimeZoneStandard[__("LINT")] = "+1400";
		info.abbreviatedTimeZoneStandard[__("TOT")] = "+1300";
		info.abbreviatedTimeZoneStandard[__("CHAST")] = "+1245";
		info.abbreviatedTimeZoneStandard[__("NZST")] = "+1200";
		info.abbreviatedTimeZoneStandard[__("NFT")] = "+1130";
		info.abbreviatedTimeZoneStandard[__("SBT")] = "+1100";
		info.abbreviatedTimeZoneStandard[__("AEST")] = "+1000";
		info.abbreviatedTimeZoneStandard[__("ACST")] = "+0930";
		info.abbreviatedTimeZoneStandard[__("JST")] = "+0900";
		info.abbreviatedTimeZoneStandard[__("CWST")] = "+0845";
		info.abbreviatedTimeZoneStandard[__("CT")] = "+0800";
		info.abbreviatedTimeZoneStandard[__("ICT")] = "+0700";
		info.abbreviatedTimeZoneStandard[__("MMT")] = "+0630";
		info.abbreviatedTimeZoneStandard[__("BST")] = "+0600";
		info.abbreviatedTimeZoneStandard[__("NPT")] = "+0545";
		info.abbreviatedTimeZoneStandard[__("IST")] = "+0530";
		info.abbreviatedTimeZoneStandard[__("PKT")] = "+0500";
		info.abbreviatedTimeZoneStandard[__("AFT")] = "+0430";
		info.abbreviatedTimeZoneStandard[__("MSK")] = "+0400";
		info.abbreviatedTimeZoneStandard[__("IRST")] = "+0330";
		info.abbreviatedTimeZoneStandard[__("FET")] = "+0300";
		info.abbreviatedTimeZoneStandard[__("EET")] = "+0200";
		info.abbreviatedTimeZoneStandard[__("CET")] = "+0100";
		info.abbreviatedTimeZoneStandard[__("GMT")] = "+0000";
		info.abbreviatedTimeZoneStandard[__("UTC")] = "+0000";
		info.abbreviatedTimeZoneStandard[__("CVT")] = "-0100";
		info.abbreviatedTimeZoneStandard[__("GST")] = "-0200";
		info.abbreviatedTimeZoneStandard[__("BRT")] = "-0300";
		info.abbreviatedTimeZoneStandard[__("NST")] = "-0330";
		info.abbreviatedTimeZoneStandard[__("AST")] = "-0400";
		info.abbreviatedTimeZoneStandard[__("EST")] = "-0500";
		info.abbreviatedTimeZoneStandard[__("CST")] = "-0600";
		info.abbreviatedTimeZoneStandard[__("MST")] = "-0700";
		info.abbreviatedTimeZoneStandard[__("PST")] = "-0800";
		info.abbreviatedTimeZoneStandard[__("AKST")] = "-0900";
		info.abbreviatedTimeZoneStandard[__("MIT")] = "-0930";
		info.abbreviatedTimeZoneStandard[__("HST")] = "-1000";
		info.abbreviatedTimeZoneStandard[__("SST")] = "-1100";
		info.abbreviatedTimeZoneStandard[__("BIT")] = "-1200";

		buildTimeZones(info);

		return info;
	};

	$D.l18n = {
		__: function (key) {
			return __(key);
		},
		updateCultureInfo: function () {
			Date.CultureInfo = CultureInfo();
		}
	};
	$D.l18n.updateCultureInfo(); // run automatically
}());<commit_msg>fixing dumb spelling mistake<commit_after>(function () {
	var $D = Date;
	var __ = function (key) {
		var output, split, length, last;
		if (Date.CultureStrings && Date.CultureStrings[key]) {
			output = Date.CultureStrings[key];
		} else {
			output = key;
			split = key.split("_");
			length = split.length;
			if (length > 1 && key.charAt(0) !== "^") {
				// if the key isn't a regex and it has a split.
				last = split[(length - 1)].toLowerCase();
				if (last === "initial" || last === "abbr") {
					output = split[0];
				}
			}
		}
		if (key.charAt(0) === "^") {
			// it's a regex
			output = new RegExp(key, "i");
		}
		return output;
	};

	var CultureInfo = function () {
		var buildTimeZones = function (data) {
			var zone;
			for (zone in data.abbreviatedTimeZoneStandard) {
				if (data.abbreviatedTimeZoneStandard.hasOwnProperty(zone)) {
					data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneStandard[zone]});
				}
			}
			for (zone in data.abbreviatedTimeZoneDST) {
				if (data.abbreviatedTimeZoneDST.hasOwnProperty(zone)) {
					data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneDST[zone], dst: true});
				}
			}
			return data.timezones;
		};
		var info =  {
			name: __("name"),
			englishName: __("englishName"),
			nativeName: __("nativeName"),
			/* Day Name Strings */
			dayNames: [
				__("Sunday"),
				__("Monday"),
				__("Tuesday"),
				__("Wednesday"),
				__("Thursday"),
				__("Friday"),
				__("Saturday")
			],
			abbreviatedDayNames: [
				__("Sun"),
				__("Mon"),
				__("Tue"),
				__("Wed"),
				__("Thu"),
				__("Fri"),
				__("Sat")
			],
			shortestDayNames: [
				__("Su"),
				__("Mo"),
				__("Tu"),
				__("We"),
				__("Th"),
				__("Fr"),
				__("Sa")
			],
			firstLetterDayNames: [
				__("S_Sun_Initial"),
				__("M_Mon_Initial"),
				__("T_Tues_Initial"),
				__("W_Wed_Initial"),
				__("T_Thu_Initial"),
				__("F_Fri_Initial"),
				__("S_Sat_Initial")
			],

			/* Month Name Strings */
			monthNames: [
				__("January"),
				__("February"),
				__("March"),
				__("April"),
				__("May"),
				__("June"),
				__("July"),
				__("August"),
				__("September"),
				__("October"),
				__("November"),
				__("December")
			],
			abbreviatedMonthNames: [
				__("Jan_Abbr"),
				__("Feb_Abbr"),
				__("Mar_Abbr"),
				__("Apr_Abbr"),
				__("May_Abbr"),
				__("Jun_Abbr"),
				__("Jul_Abbr"),
				__("Aug_Abbr"),
				__("Sep_Abbr"),
				__("Oct_Abbr"),
				__("Nov_Abbr"),
				__("Dec_Abbr")
			],
			/* AM/PM Designators */
			amDesignator: __("AM"),
			pmDesignator: __("PM"),
			firstDayOfWeek: __("firstDayOfWeek"),
			twoDigitYearMax: __("twoDigitYearMax"),
			dateElementOrder: __("mdy"),
			/* Standard date and time format patterns */
			formatPatterns: {
				shortDate: __("M/d/yyyy"),
				longDate: __("dddd, MMMM dd, yyyy"),
				shortTime: __("h:mm tt"),
				longTime: __("h:mm:ss tt"),
				fullDateTime: __("dddd, MMMM dd, yyyy h:mm:ss tt"),
				sortableDateTime: __("yyyy-MM-ddTHH:mm:ss"),
				universalSortableDateTime: __("yyyy-MM-dd HH:mm:ssZ"),
				rfc1123: __("ddd, dd MMM yyyy HH:mm:ss"),
				monthDay: __("MMMM dd"),
				yearMonth: __("MMMM, yyyy")
			},
			regexPatterns: {
				jan: __("^jan(uary)?"),
				feb: __("^feb(ruary)?"),
				mar: __("^mar(ch)?"),
				apr: __("^apr(il)?"),
				may: __("^may"),
				jun: __("^jun(e)?"),
				jul: __("^jul(y)?"),
				aug: __("^aug(ust)?"),
				sep: __("^sep(t(ember)?)?"),
				oct: __("^oct(ober)?"),
				nov: __("^nov(ember)?"),
				dec: __("^dec(ember)?"),
				sun: __("^su(n(day)?)?"),
				mon: __("^mo(n(day)?)?"),
				tue: __("^tu(e(s(day)?)?)?"),
				wed: __("^we(d(nesday)?)?"),
				thu: __("^th(u(r(s(day)?)?)?)?"),
				fri: __("^fr(i(day)?)?"),
				sat: __("^sa(t(urday)?)?"),
				future: __("^next"),
				past: __("^last|past|prev(ious)?"),
				add: __("^(\\+|aft(er)?|from|hence)"),
				subtract: __("^(\\-|bef(ore)?|ago)"),
				yesterday: __("^yes(terday)?"),
				today: __("^t(od(ay)?)?"),
				tomorrow: __("^tom(orrow)?"),
				now: __("^n(ow)?"),
				millisecond: __("^ms|milli(second)?s?"),
				second: __("^sec(ond)?s?"),
				minute: __("^mn|min(ute)?s?"),
				hour: __("^h(our)?s?"),
				week: __("^w(eek)?s?"),
				month: __("^m(onth)?s?"),
				day: __("^d(ay)?s?"),
				year: __("^y(ear)?s?"),
				shortMeridian: __("^(a|p)"),
				longMeridian: __("^(a\\.?m?\\.?|p\\.?m?\\.?)"),
				timezone: __("^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)"),
				ordinalSuffix: __("^\\s*(st|nd|rd|th)"),
				timeContext: __("^\\s*(\\:|a(?!u|p)|p)")
			},
			timezones: [],
			abbreviatedTimeZoneDST: {},
			abbreviatedTimeZoneStandard: {}
		};

		info.abbreviatedTimeZoneDST[__("CHADT")] = "+1345";
		info.abbreviatedTimeZoneDST[__("NZDT")] = "+1300";
		info.abbreviatedTimeZoneDST[__("AEDT")] = "+1100";
		info.abbreviatedTimeZoneDST[__("ACDT")] = "+1030";
		info.abbreviatedTimeZoneDST[__("AZST")] = "+0500";
		info.abbreviatedTimeZoneDST[__("IRDT")] = "+0430";
		info.abbreviatedTimeZoneDST[__("EEST")] = "+0300";
		info.abbreviatedTimeZoneDST[__("CEST")] = "+0200";
		info.abbreviatedTimeZoneDST[__("BST")] = "+0100";
		info.abbreviatedTimeZoneDST[__("PMDT")] = "-0200";
		info.abbreviatedTimeZoneDST[__("ADT")] = "-0300";
		info.abbreviatedTimeZoneDST[__("NDT")] = "-0230";
		info.abbreviatedTimeZoneDST[__("EDT")] = "-0400";
		info.abbreviatedTimeZoneDST[__("CDT")] = "-0500";
		info.abbreviatedTimeZoneDST[__("MDT")] = "-0600";
		info.abbreviatedTimeZoneDST[__("PDT")] = "-0700";
		info.abbreviatedTimeZoneDST[__("AKDT")] = "-0800";
		info.abbreviatedTimeZoneDST[__("HADT")] = "-0900";

		info.abbreviatedTimeZoneStandard[__("LINT")] = "+1400";
		info.abbreviatedTimeZoneStandard[__("TOT")] = "+1300";
		info.abbreviatedTimeZoneStandard[__("CHAST")] = "+1245";
		info.abbreviatedTimeZoneStandard[__("NZST")] = "+1200";
		info.abbreviatedTimeZoneStandard[__("NFT")] = "+1130";
		info.abbreviatedTimeZoneStandard[__("SBT")] = "+1100";
		info.abbreviatedTimeZoneStandard[__("AEST")] = "+1000";
		info.abbreviatedTimeZoneStandard[__("ACST")] = "+0930";
		info.abbreviatedTimeZoneStandard[__("JST")] = "+0900";
		info.abbreviatedTimeZoneStandard[__("CWST")] = "+0845";
		info.abbreviatedTimeZoneStandard[__("CT")] = "+0800";
		info.abbreviatedTimeZoneStandard[__("ICT")] = "+0700";
		info.abbreviatedTimeZoneStandard[__("MMT")] = "+0630";
		info.abbreviatedTimeZoneStandard[__("BST")] = "+0600";
		info.abbreviatedTimeZoneStandard[__("NPT")] = "+0545";
		info.abbreviatedTimeZoneStandard[__("IST")] = "+0530";
		info.abbreviatedTimeZoneStandard[__("PKT")] = "+0500";
		info.abbreviatedTimeZoneStandard[__("AFT")] = "+0430";
		info.abbreviatedTimeZoneStandard[__("MSK")] = "+0400";
		info.abbreviatedTimeZoneStandard[__("IRST")] = "+0330";
		info.abbreviatedTimeZoneStandard[__("FET")] = "+0300";
		info.abbreviatedTimeZoneStandard[__("EET")] = "+0200";
		info.abbreviatedTimeZoneStandard[__("CET")] = "+0100";
		info.abbreviatedTimeZoneStandard[__("GMT")] = "+0000";
		info.abbreviatedTimeZoneStandard[__("UTC")] = "+0000";
		info.abbreviatedTimeZoneStandard[__("CVT")] = "-0100";
		info.abbreviatedTimeZoneStandard[__("GST")] = "-0200";
		info.abbreviatedTimeZoneStandard[__("BRT")] = "-0300";
		info.abbreviatedTimeZoneStandard[__("NST")] = "-0330";
		info.abbreviatedTimeZoneStandard[__("AST")] = "-0400";
		info.abbreviatedTimeZoneStandard[__("EST")] = "-0500";
		info.abbreviatedTimeZoneStandard[__("CST")] = "-0600";
		info.abbreviatedTimeZoneStandard[__("MST")] = "-0700";
		info.abbreviatedTimeZoneStandard[__("PST")] = "-0800";
		info.abbreviatedTimeZoneStandard[__("AKST")] = "-0900";
		info.abbreviatedTimeZoneStandard[__("MIT")] = "-0930";
		info.abbreviatedTimeZoneStandard[__("HST")] = "-1000";
		info.abbreviatedTimeZoneStandard[__("SST")] = "-1100";
		info.abbreviatedTimeZoneStandard[__("BIT")] = "-1200";

		buildTimeZones(info);

		return info;
	};

	$D.i18n = {
		__: function (key) {
			return __(key);
		},
		updateCultureInfo: function () {
			Date.CultureInfo = CultureInfo();
		}
	};
	$D.i18n.updateCultureInfo(); // run automatically
}());<|endoftext|>


<commit_before>var vscode = require('vscode');
var Promise = require('bluebird');
var request = Promise.promisify(require("request"));
var auth = require("./auth");
var api = "https://api.github.com";

exports.PRIVATE = 0;
exports.PUBLIC = 1;
exports.ANONYMOUS = 2;

function send(method, path, auth_type, body) {
  var oauth = auth.getToken();
  var promise = auth_type !== exports.ANONYMOUS && !oauth ? auth.getCredentials() : Promise.resolve();
  return promise.then(function (creds) {
    console.log(creds);
    var options = {
      method: method,
      uri: api + path,
      json: true,
      headers: {
        "User-Agent": "VSCode-Gist-Extention"
      },
      body: body
    };
    if (auth_type !== exports.ANONYMOUS) {
      if (oauth) {
        options.headers["Authorization"] = "token " + oauth;
      } else {
        options.auth = creds;
      }
    }
    return request(options);
  })
}

exports.create = function (type, description, file_name, text_content) {
  var body = {
    description: description,
    public: type !== exports.PRIVATE,
    files: {}
  }
  body.files[file_name] = {
    content: text_content
  }
  return send("POST", "/gists", type, body);
};

<commit_msg>filled out the api<commit_after>var vscode = require('vscode');
var Promise = require('bluebird');
var request = Promise.promisify(require("request"));
var auth = require("./auth");
var api = "https://api.github.com";

exports.PRIVATE = 0;
exports.PUBLIC = 1;
exports.ANONYMOUS = 2;

function send(method, path, auth_type, body) {
  var oauth = auth.getToken();
  var promise = auth_type !== exports.ANONYMOUS && !oauth ? auth.getCredentials() : Promise.resolve();
  return promise.then(function (creds) {
    console.log(creds);
    var options = {
      method: method,
      uri: api + path,
      json: true,
      headers: {
        "User-Agent": "VSCode-Gist-Extention"
      },
      body: body
    };
    if (auth_type !== exports.ANONYMOUS) {
      if (oauth) {
        options.headers["Authorization"] = "token " + oauth;
      } else {
        options.auth = creds;
      }
    }
    return request(options);
  })
}

exports.create = function (type, description, file_name, text_content) {
  var body = {
    description: description,
    public: type !== exports.PRIVATE,
    files: {}
  }
  body.files[file_name] = {
    content: text_content
  }
  return send("POST", "/gists", type, body);
};

exports.list = function() { return send("GET", "/gists") };
exports.listUser = function(user) { return send("GET", "/users/"+user+"/gists") };
exports.listStarred = function() { return send("GET", "/gists/starred") };
exports.listPublic = function() { return send("GET", "/gists/public") };

exports.get = function(id) { return send("GET", "/gist/"+id)};
exports.remove = function(id) { return send("DELETE", "/gist/"+id)};
exports.getRevision = function(id, sha) { return send("GET", "/gist/"+id +"/" + sha)};
exports.getCommits = function(id) {return send("GET", "gists/" + id + "/commits")};

exports.edit = function(id, file_name, description, files) {
  return send("PATCH", "/gists/" + id, undefined, {
    file_name: file_name,
    description: description,
    files: files
  });
};

exports.star = function(id) { return send("PUT", "/gist/"+id+ "/star")};
exports.unstar = function(id) { return send("DELETE", "/gist/"+id+ "/star")};
exports.isStarred = function(id) { return send("GET", "/gist/"+id+ "/star")};

exports.fork = function(id) { return send("POST", "/gist/"+id+ "/forks")};
exports.listForks = function(id) { return send("GET", "/gist/"+id+ "/forks")};
<|endoftext|>


<commit_before>#! /usr/bin/env node

const fs = require('fs');
const chalk = require('chalk');
const inquirer = require('inquirer');
const template = require('lodash.template');
const {die, done, fail, Git, log, makePromise, Package} = require('tools/common');

const git = Git(process.cwd());

const confirm_tmpl = template('Your repository will be modified:'
	+ '\n' + '  - version will be bumped to: <%= release %>'
	+ '\n' + '  - changelog changelogs/v<%= release %> will be drafted'
	+ '\n' + '  - branch release/v<%= release %> will be created'
);

const changelog_tmpl = template('## Release <%= releaseTag %>'
	+ '\n'
	+ '\n' + `date: ${(new Date()).toDateString()}`
	+ '\n'
	+ '\n' + '### Changes'
	+ '\n' + '- ...'
	+ '\n'
	+ '\n' + '### Fixes'
	+ '\n' + '- ...'
	+ '\n'
);

function check_branch() {
	return git.branch().then(branch => {
		if (branch !== 'develop') {
			throw new Error(
				'The current branch is not develop. '
				+ 'Checkout develop branch before anything.'
			);
		}
	});
}

function bump_version(pkg, {release}) {
	log('- bump package version ... ');
	pkg.version = release;
	return pkg.dump()
		.then(done)
		.catch(fail);
}

function create_changelog(pkg) {
	log('- creating changelog ... ');
	return makePromise(fs.writeFile, pkg.changelog, changelog_tmpl(pkg))
		.then(done)
		.catch(fail);
}

function create_branch(pkg, {release}) {
	const stage = () => {
		const files = ['package.json', pkg.changelog];
		log(`- stage ${files.join(', ')} ... `);
		return git.stage(...files).then(done);
	};

	const commit = () => {
		log('- commit release draft ... ');
		return git.commit(`draft release ${release}`).then(done);
	};

	const branch = () => {
		log(`- create branch ${pkg.releaseBranch} ... `);
		return git.branch(pkg.releaseBranch).then(done);
	};

	return Promise.resolve()
		.then(branch)
		.then(stage)
		.then(commit)
		.catch(fail);
}

function draft_release({pkg, draft}) {
	if (draft.confirmed) {
		return Promise.resolve()
			.then(() => bump_version(pkg, draft))
			.then(() => create_changelog(pkg, draft))
			.then(() => create_branch(pkg, draft));
	}
}

function prompt() {
	return Package().then(pkg => inquirer.prompt([{
		name: 'release',
		type: 'list',
		choices: ['major', 'minor', 'patch', 'custom'],
		default: 2,
		message: 'What kind of release are you drafting ?',
		filter: release => {
			if (release !== 'custom') {
				return pkg.bump(release);
			}
			return release;
		}
	}, {
		name: 'release',
		type: 'input',
		message: 'Please type the desired version you want: ',
		filter: version => pkg.bump(version),
		when: answers => answers.release === 'custom'
	}, {
		name: 'confirmed',
		type: 'confirm',
		default: false,
		message: answers => {
			const ui = new inquirer.ui.BottomBar();
			ui.log.write(chalk.yellow(confirm_tmpl(answers)));
			return 'Are you sure you want to continue ?';
		}
	}]).then(draft => ({draft, pkg})));
}

check_branch()
	.then(prompt)
	.then(draft_release)
	.catch(die);
<commit_msg>update changelog template<commit_after>#! /usr/bin/env node

const fs = require('fs');
const chalk = require('chalk');
const inquirer = require('inquirer');
const template = require('lodash.template');
const {die, done, fail, Git, log, makePromise, Package} = require('tools/common');

const git = Git(process.cwd());

const confirm_tmpl = template('Your repository will be modified:'
	+ '\n' + '  - version will be bumped to: <%= release %>'
	+ '\n' + '  - changelog changelogs/v<%= release %> will be drafted'
	+ '\n' + '  - branch release/v<%= release %> will be created'
);

const changelog_tmpl = template('---'
	+ '\n' + 'title: Release <%= releaseTag %>'
	+ '\n' + `date: ${(new Date()).toDateString()}`
	+ '\n' + '---'
	+ '\n' + '### Changes'
	+ '\n' + '- ...'
	+ '\n'
	+ '\n' + '### Fixes'
	+ '\n' + '- ...'
	+ '\n'
);

function check_branch() {
	return git.branch().then(branch => {
		if (branch !== 'develop') {
			throw new Error(
				'The current branch is not develop. '
				+ 'Checkout develop branch before anything.'
			);
		}
	});
}

function bump_version(pkg, {release}) {
	log('- bump package version ... ');
	pkg.version = release;
	return pkg.dump()
		.then(done)
		.catch(fail);
}

function create_changelog(pkg) {
	log('- creating changelog ... ');
	return makePromise(fs.writeFile, pkg.changelog, changelog_tmpl(pkg))
		.then(done)
		.catch(fail);
}

function create_branch(pkg, {release}) {
	const stage = () => {
		const files = ['package.json', pkg.changelog];
		log(`- stage ${files.join(', ')} ... `);
		return git.stage(...files).then(done);
	};

	const commit = () => {
		log('- commit release draft ... ');
		return git.commit(`draft release ${release}`).then(done);
	};

	const branch = () => {
		log(`- create branch ${pkg.releaseBranch} ... `);
		return git.branch(pkg.releaseBranch).then(done);
	};

	return Promise.resolve()
		.then(branch)
		.then(stage)
		.then(commit)
		.catch(fail);
}

function draft_release({pkg, draft}) {
	if (draft.confirmed) {
		return Promise.resolve()
			.then(() => bump_version(pkg, draft))
			.then(() => create_changelog(pkg, draft))
			.then(() => create_branch(pkg, draft));
	}
}

function prompt() {
	return Package().then(pkg => inquirer.prompt([{
		name: 'release',
		type: 'list',
		choices: ['major', 'minor', 'patch', 'custom'],
		default: 2,
		message: 'What kind of release are you drafting ?',
		filter: release => {
			if (release !== 'custom') {
				return pkg.bump(release);
			}
			return release;
		}
	}, {
		name: 'release',
		type: 'input',
		message: 'Please type the desired version you want: ',
		filter: version => pkg.bump(version),
		when: answers => answers.release === 'custom'
	}, {
		name: 'confirmed',
		type: 'confirm',
		default: false,
		message: answers => {
			const ui = new inquirer.ui.BottomBar();
			ui.log.write(chalk.yellow(confirm_tmpl(answers)));
			return 'Are you sure you want to continue ?';
		}
	}]).then(draft => ({draft, pkg})));
}

check_branch()
	.then(prompt)
	.then(draft_release)
	.catch(die);
<|endoftext|>


<commit_before>"use strict";

var $ = require('jquery');

var DataLoader = function() {
	return {
		get: function(uniprotID) {
			return $.ajax('http://ves-ebi-ca:8082/us/rest/features/' + uniprotID, {
				params: {
					//put things in here if we need
				}
			}).done(function(d) {
				return processData(d);
			}).fail(function(e){
				return(e);
			});
		}
	};
} ();

var processData = function(d) {
	var consecutive = 1;
	_.each(d, function(datum) {
		if (datum.features) {
			_.each(datum.features, function(feature) {
				feature.internalId = "ft_" + consecutive;
				consecutive++;
			});
		}
	});
	d.totalFeatureCount = consecutive;
    return d;
};

module.exports = DataLoader;<commit_msg>Add underscore dependency to data loader<commit_after>"use strict";

var $ = require('jquery');
var _ = require('underscore');

var DataLoader = function() {
	return {
		get: function(uniprotID) {
			return $.ajax('http://ves-ebi-ca:8082/us/rest/features/' + uniprotID, {
			//return $.ajax('data/features.json', {
				params: {
					//put things in here if we need
				}
			}).done(function(d) {
				return processData(d);
			}).fail(function(e){
				return(e);
			});
		}
	};
} ();

var processData = function(d) {
	var consecutive = 1;
	_.each(d, function(datum) {
		if (datum.features) {
			_.each(datum.features, function(feature) {
				feature.internalId = "ft_" + consecutive;
				consecutive++;
			});
		}
	});
	d.totalFeatureCount = consecutive;
    return d;
};

module.exports = DataLoader;<|endoftext|>


<commit_before>var sqlite3 = require('sqlite3');

var db = null;

exports.prepareDatabase = function(dbfile, callback) {
  this.openDatabase(dbfile);
  // set up database and create tables
  db.serialize(function() {
    db.run("CREATE TABLE IF NOT EXISTS jobs(id TEXT PRIMARY KEY, status TEXT, progress REAL, duration INTEGER, filesize INTEGER, opts TEXT, message TEXT, created_at INTEGER, updated_at INTEGER);");
    db.run("UPDATE jobs SET status='failed', message='transcoder quit unexpectedly', updated_at=strftime('%s', 'now') WHERE status LIKE 'processing';", callback);
  });
}

exports.insertJob = function(job, callback) {
  var stmt = db.prepare("INSERT INTO jobs VALUES (?,?,?,?,?,?,?,strftime('%s', 'now'),strftime('%s', 'now'))");
  stmt.run(job.id, job.status, job.progress, job.duration, job.filesize, JSON.stringify(job.opts), job.message, callback);
}

exports.updateJob = function(job, callback) {
  var stmt = db.prepare("UPDATE jobs SET status=?, progress=?, duration=?, filesize=?, message=?, updated_at=strftime('%s', 'now') WHERE id LIKE ?");
  stmt.run(job.status, job.progress, job.duration, job.filesize, job.message, job.id, callback);
}

exports.getJob = function(id, callback) {
  var stmt = db.prepare("SELECT * FROM jobs WHERE id LIKE ? LIMIT 1");
  stmt.get(id, callback);
}

exports.closeDatabase = function() {
  db.close();
}

exports.openDatabase = function(dbfile) {
  db = new sqlite3.Database(dbfile);
}<commit_msg>db-handler tweak.<commit_after>var sqlite3 = require('sqlite3');

var db = null;

exports.prepareDatabase = function(dbfile, callback) {
  db = this.openDatabase(dbfile);
  // set up database and create tables
  db.serialize(function() {
    db.run("CREATE TABLE IF NOT EXISTS jobs(id TEXT PRIMARY KEY, status TEXT, progress REAL, duration INTEGER, filesize INTEGER, opts TEXT, message TEXT, created_at INTEGER, updated_at INTEGER);");
    db.run("UPDATE jobs SET status='failed', message='transcoder quit unexpectedly', updated_at=strftime('%s', 'now') WHERE status LIKE 'processing';", callback);
  });
}

exports.insertJob = function(job, callback) {
  var stmt = db.prepare("INSERT INTO jobs VALUES (?,?,?,?,?,?,?,strftime('%s', 'now'),strftime('%s', 'now'))");
  stmt.run(job.id, job.status, job.progress, job.duration, job.filesize, JSON.stringify(job.opts), job.message, callback);
}

exports.updateJob = function(job, callback) {
  var stmt = db.prepare("UPDATE jobs SET status=?, progress=?, duration=?, filesize=?, message=?, updated_at=strftime('%s', 'now') WHERE id LIKE ?");
  stmt.run(job.status, job.progress, job.duration, job.filesize, job.message, job.id, callback);
}

exports.getJob = function(id, callback) {
  var stmt = db.prepare("SELECT * FROM jobs WHERE id LIKE ? LIMIT 1");
  stmt.get(id, callback);
}

exports.closeDatabase = function() {
  db.close();
}

exports.openDatabase = function(dbfile) {
  return new sqlite3.Database(dbfile);
}<|endoftext|>