<commit_before>// Copyright 2019, University of Colorado Boulder

/* eslint-disable */

/**
 * Prototyping for https://github.com/phetsims/chipper/issues/820
 *
 * @param {Object} grunt
 * @param {Object} gruntConfig
 */

'use strict';

const fs = require( 'fs' );
const grunt = require( 'grunt' );

const replace = ( str, search, replacement ) => {
  return str.split( search ).join( replacement );
};

const migrateFile = async ( repo, relativeFile ) => {
  if ( relativeFile.endsWith( '/PhetioIDUtils.js' ) ) {
    return;
  }
  if ( relativeFile.endsWith( '/copyWithSortedKeys.js' ) ) {
    return;
  }
  console.log( repo, relativeFile );
  const path = '../' + repo + '/' + relativeFile;
  let contents = fs.readFileSync( path, 'utf-8' );
  contents = replace( contents, '= require( \'string!', '= (\'' );
  contents = replace( contents, '= require( \'ifphetio!', '= function(){return function(){ return function(){}; };}; // ' );
  contents = replace( contents, 'require( \'mipmap!BRAND/logo.png\' )', 'require( \'BRAND/../images/logo.png\' ).default' );
  contents = replace( contents, 'require( \'mipmap!BRAND/logo-on-white.png\' )', 'require( \'BRAND/../images/logo-on-white.png\' ).default' );
  contents = replace( contents, 'require( \'image!EXAMPLE_SIM/barMagnet.png\' )', 'require( \'EXAMPLE_SIM/../images/barMagnet.png\' ).default' );
  contents = replace( contents, 'require( \'mipmap!JOIST/keyboard-icon-on-white.png\' )', 'require( \'JOIST/../images/keyboard-icon-on-white.png\' ).default' );
  contents = replace( contents, 'require( \'mipmap!JOIST/keyboard-icon.png\' )', 'require( \'JOIST/../images/keyboard-icon.png\' ).default' );
  contents = replace( contents, 'require( \'sound!TAMBO/empty_apartment_bedroom_06_resampled.mp3\' )', 'require( \'TAMBO/../sounds/empty_apartment_bedroom_06_resampled.mp3\' ).default' );
  contents = replace( contents, 'require( \'sound!TAMBO/short-silence.wav\' )', 'require( \'TAMBO/../sounds/short-silence.wav\' ).default' );
  contents = replace( contents, 'require( \'sound!TAMBO/reset-all.mp3\' )', 'require( \'TAMBO/../sounds/reset-all.mp3\' ).default' );
  contents = replace( contents, 'require( \'sound!TAMBO/general-button-v4.mp3\' )', 'require( \'TAMBO/../sounds/general-button-v4.mp3\' ).default' );
  contents = replace( contents, 'assert && assert( Array.isArray( brightIconMipmap ), \'icon must be a mipmap\' );', '//assert && assert( Array.isArray( brightIconMipmap ), \'icon must be a mipmap\' );' );
  contents = replace( contents, 'assert && assert( Array.isArray( brightLogoMipmap ), \'logo must be a mipmap\' );', '// assert && assert( Array.isArray( brightLogoMipmap ), \'logo must be a mipmap\' );' );
  contents = replace( contents, 'brightIconMipmap[ 0 ].height', '12' );
  contents = replace( contents, 'brightLogoMipmap[ 0 ].height', '12' );

  contents = replace( contents, `  // text
  const packageString = require( 'text!REPOSITORY/package.json' );

  // constants
  const packageJSON = JSON.parse( packageString ); // Tandem can't depend on joist, so cannot use packageJSON module`, `const packageJSON = require('REPOSITORY/package.json');` );

  contents = replace( contents, `  // modules
  const joist = require( 'JOIST/joist' );

  // strings
  const packageString = require( 'text!REPOSITORY/package.json' );

  const packageJSON = JSON.parse( packageString );

  joist.register( 'packageJSON', packageJSON );`, `const packageJSON = require( 'REPOSITORY/package.json' );` );

  contents = replace( contents, `define( require => {`, `//define( require => {` );

  if ( !contents.endsWith( '} )();' ) ) {
    const lastIndex = contents.lastIndexOf( '} );' );
    contents = contents.substring( 0, lastIndex ) + '//' + contents.substring( lastIndex );
  }

  const returnInherit = contents.lastIndexOf( 'return inherit( ' );
  if ( returnInherit >= 0 ) {
    contents = replace( contents, `return inherit( `, `export default inherit( ` );
  }

  const lastReturn = contents.lastIndexOf( 'return ' );
  if ( lastReturn >= 0 && returnInherit === -1 ) {
    contents = contents.substring( 0, lastReturn ) + 'export default ' + contents.substring( lastReturn + 'return '.length );
  }

  // contents = replace(contents,`return inherit( Node, ScreenView, {`,`export default inherit( Node, ScreenView, {`);
  // contents = replace(contents,`export default Math.min( width / this.layoutBounds.width, height / this.layoutBounds.height );`,`return Math.min( width / this.layoutBounds.width, height / this.layoutBounds.height );`);

  // const Namespace = require( 'PHET_CORE/Namespace' );
  contents = replace( contents, `const Namespace = require( 'PHET_CORE/Namespace' );`, `import Namespace from 'PHET_CORE/Namespace'` );

  let lines = contents.split( /\r?\n/ );
  lines = lines.map( line => {
    // return 'hello ' + line;
    if ( line.trim().startsWith( 'const ' ) && line.indexOf( ' = require( ' ) >= 0 ) {
      // const Bounds2 = require( 'DOT/Bounds2' );
      // becomes
      // import Bounds2 from 'DOT/Bounds2';
      line = replace( line, 'const ', 'import ' );
      line = replace( line, ' = require( ', ' from ' );
      line = replace( line, '\' );', '\';' );
    }
    return line;
  } );
  contents = lines.join( '\n' );

  contents = replace( contents, `return inherit;`, `export default inherit;` );
  contents = replace( contents, `' ).default;`, `';` );

  fs.writeFileSync( path, contents, 'utf-8' );
};

module.exports = function( repo, cache ) {

  // const repos = fs.readFileSync( '../perennial/data/migrate-repos', 'utf-8' ).trim().split( /\r?\n/ ).map( sim => sim.trim() );
  const repos = `axon
brand
dot
joist
kite
phetcommon
phet-core
phet-io
example-sim
scenery
scenery-phet
sun
tambo
tandem
utterance-queue`.trim().split( /\r?\n/ ).map( sim => sim.trim() );
  repos.forEach( ( repo, index ) => {

    console.log( index + '/' + repos.length );

    let relativeFiles = [];
    grunt.file.recurse( `../${repo}`, ( abspath, rootdir, subdir, filename ) => {
      relativeFiles.push( `${subdir}/${filename}` );
    } );
    relativeFiles = relativeFiles.filter( file => file.startsWith( 'js/' ) ||

                                                  // that's for brand
                                                  file.startsWith( 'phet/js' ) );

    relativeFiles.forEach( ( rel, i ) => {
      console.log( '    ' + i + '/' + relativeFiles.length );
      migrateFile( repo, rel );
    } );
  } );
};<commit_msg>Fix logo size, see https://github.com/phetsims/chipper/issues/820<commit_after>// Copyright 2019, University of Colorado Boulder

/* eslint-disable */

/**
 * Prototyping for https://github.com/phetsims/chipper/issues/820
 *
 * @param {Object} grunt
 * @param {Object} gruntConfig
 */

'use strict';

const fs = require( 'fs' );
const grunt = require( 'grunt' );

const replace = ( str, search, replacement ) => {
  return str.split( search ).join( replacement );
};

const migrateFile = async ( repo, relativeFile ) => {
  if ( relativeFile.endsWith( '/PhetioIDUtils.js' ) ) {
    return;
  }
  if ( relativeFile.endsWith( '/copyWithSortedKeys.js' ) ) {
    return;
  }
  console.log( repo, relativeFile );
  const path = '../' + repo + '/' + relativeFile;
  let contents = fs.readFileSync( path, 'utf-8' );
  contents = replace( contents, '= require( \'string!', '= (\'' );
  contents = replace( contents, '= require( \'ifphetio!', '= function(){return function(){ return function(){}; };}; // ' );
  contents = replace( contents, 'require( \'mipmap!BRAND/logo.png\' )', 'require( \'BRAND/../images/logo.png\' ).default' );
  contents = replace( contents, 'require( \'mipmap!BRAND/logo-on-white.png\' )', 'require( \'BRAND/../images/logo-on-white.png\' ).default' );
  contents = replace( contents, 'require( \'image!EXAMPLE_SIM/barMagnet.png\' )', 'require( \'EXAMPLE_SIM/../images/barMagnet.png\' ).default' );
  contents = replace( contents, 'require( \'mipmap!JOIST/keyboard-icon-on-white.png\' )', 'require( \'JOIST/../images/keyboard-icon-on-white.png\' ).default' );
  contents = replace( contents, 'require( \'mipmap!JOIST/keyboard-icon.png\' )', 'require( \'JOIST/../images/keyboard-icon.png\' ).default' );
  contents = replace( contents, 'require( \'sound!TAMBO/empty_apartment_bedroom_06_resampled.mp3\' )', 'require( \'TAMBO/../sounds/empty_apartment_bedroom_06_resampled.mp3\' ).default' );
  contents = replace( contents, 'require( \'sound!TAMBO/short-silence.wav\' )', 'require( \'TAMBO/../sounds/short-silence.wav\' ).default' );
  contents = replace( contents, 'require( \'sound!TAMBO/reset-all.mp3\' )', 'require( \'TAMBO/../sounds/reset-all.mp3\' ).default' );
  contents = replace( contents, 'require( \'sound!TAMBO/general-button-v4.mp3\' )', 'require( \'TAMBO/../sounds/general-button-v4.mp3\' ).default' );
  contents = replace( contents, 'assert && assert( Array.isArray( brightIconMipmap ), \'icon must be a mipmap\' );', '//assert && assert( Array.isArray( brightIconMipmap ), \'icon must be a mipmap\' );' );
  contents = replace( contents, 'assert && assert( Array.isArray( brightLogoMipmap ), \'logo must be a mipmap\' );', '// assert && assert( Array.isArray( brightLogoMipmap ), \'logo must be a mipmap\' );' );
  contents = replace( contents, 'brightIconMipmap[ 0 ].height', '108' );
  contents = replace( contents, 'brightLogoMipmap[ 0 ].height', '108' );

  contents = replace( contents, `  // text
  const packageString = require( 'text!REPOSITORY/package.json' );

  // constants
  const packageJSON = JSON.parse( packageString ); // Tandem can't depend on joist, so cannot use packageJSON module`, `const packageJSON = require('REPOSITORY/package.json');` );

  contents = replace( contents, `  // modules
  const joist = require( 'JOIST/joist' );

  // strings
  const packageString = require( 'text!REPOSITORY/package.json' );

  const packageJSON = JSON.parse( packageString );

  joist.register( 'packageJSON', packageJSON );`, `const packageJSON = require( 'REPOSITORY/package.json' );` );

  contents = replace( contents, `define( require => {`, `//define( require => {` );

  if ( !contents.endsWith( '} )();' ) ) {
    const lastIndex = contents.lastIndexOf( '} );' );
    contents = contents.substring( 0, lastIndex ) + '//' + contents.substring( lastIndex );
  }

  const returnInherit = contents.lastIndexOf( 'return inherit( ' );
  if ( returnInherit >= 0 ) {
    contents = replace( contents, `return inherit( `, `export default inherit( ` );
  }

  const lastReturn = contents.lastIndexOf( 'return ' );
  if ( lastReturn >= 0 && returnInherit === -1 ) {
    contents = contents.substring( 0, lastReturn ) + 'export default ' + contents.substring( lastReturn + 'return '.length );
  }

  // contents = replace(contents,`return inherit( Node, ScreenView, {`,`export default inherit( Node, ScreenView, {`);
  // contents = replace(contents,`export default Math.min( width / this.layoutBounds.width, height / this.layoutBounds.height );`,`return Math.min( width / this.layoutBounds.width, height / this.layoutBounds.height );`);

  // const Namespace = require( 'PHET_CORE/Namespace' );
  contents = replace( contents, `const Namespace = require( 'PHET_CORE/Namespace' );`, `import Namespace from 'PHET_CORE/Namespace'` );

  let lines = contents.split( /\r?\n/ );
  lines = lines.map( line => {
    // return 'hello ' + line;
    if ( line.trim().startsWith( 'const ' ) && line.indexOf( ' = require( ' ) >= 0 ) {
      // const Bounds2 = require( 'DOT/Bounds2' );
      // becomes
      // import Bounds2 from 'DOT/Bounds2';
      line = replace( line, 'const ', 'import ' );
      line = replace( line, ' = require( ', ' from ' );
      line = replace( line, '\' );', '\';' );
    }
    return line;
  } );
  contents = lines.join( '\n' );

  contents = replace( contents, `return inherit;`, `export default inherit;` );
  contents = replace( contents, `' ).default;`, `';` );

  // contents = replace(contents,`from 'AXON/`,`from '/axon/js/`);
  // contents = replace(contents,`from 'BRAND/`,`from '/brand/phet/js/`);
  // contents = replace(contents,`from 'DOT/`,`from '/dot/js/`);
  // contents = replace(contents,`from 'EXAMPLE_SIM/`,`from '/example-sim/js/`);
  // contents = replace(contents,`from 'JOIST/`,`from '/joist/js/`);
  // contents = replace(contents,`from 'KITE/`,`from '/kite/js/`);
  // contents = replace(contents,`from 'PHETCOMMON/`,`from '/phetcommon/js/`);
  // contents = replace(contents,`from 'PHET_CORE/`,`from '/phet-core/js/`);
  // contents = replace(contents,`from 'PHET_IO/`,`from '/phet-io/js/`);
  // contents = replace(contents,`from 'REPOSITORY/`,`from '/example-sim/js/`);
  // contents = replace(contents,`from 'SCENERY/`,`from '/scenery/js/`);
  // contents = replace(contents,`from 'SCENERY_PHET/`,`from '/scenery-phet/js/`);
  // contents = replace(contents,`from 'SUN/`,`from '/sun/js/`);
  // contents = replace(contents,`from 'TAMBO/`,`from '/tambo/js/`);
  // contents = replace(contents,`from 'TANDEM/`,`from '/tandem/js/`);
  // contents = replace(contents,`from 'UTTERANCE_QUEUE/`,`from '/utterance-queue/js/`);

  // AXON
  // BRAND
  // DOT
  // EXAMPLE_SIM
  // JOIST
  // KITE
  // PHETCOMMON
  // PHET_CORE
  // PHET_IO
  // REPOSITORY
  // SCENERY
  // SCENERY_PHET
  // SUN
  // TAMBO
  // TANDEM
  // UTTERANCE_QUEUE

  // : '../../axon/js',
  //   : '../../brand/' + phet.chipper.brand + '/js',
  //   : '../../dot/js',
  //   : '.',
  //   : '../../joist/js',
  //   : '../../kite/js',
  //   : '../../phetcommon/js',
  //   : '../../phet-core/js',
  //   : '../../phet-io/js',
  //   : '..',
  //   : '../../scenery/js',
  //   : '../../scenery-phet/js',
  //   : '../../sun/js',
  //   : '../../tambo/js',
  //   : '../../tandem/js',
  //   : '../../utterance-queue/js'

  fs.writeFileSync( path, contents, 'utf-8' );
};

module.exports = function( repo, cache ) {

  // const repos = fs.readFileSync( '../perennial/data/migrate-repos', 'utf-8' ).trim().split( /\r?\n/ ).map( sim => sim.trim() );
  const repos = `axon
brand
dot
joist
kite
phetcommon
phet-core
phet-io
example-sim
scenery
scenery-phet
sun
tambo
tandem
utterance-queue`.trim().split( /\r?\n/ ).map( sim => sim.trim() );
  repos.forEach( ( repo, index ) => {

    console.log( index + '/' + repos.length );

    let relativeFiles = [];
    grunt.file.recurse( `../${repo}`, ( abspath, rootdir, subdir, filename ) => {
      relativeFiles.push( `${subdir}/${filename}` );
    } );
    relativeFiles = relativeFiles.filter( file => file.startsWith( 'js/' ) ||

                                                  // that's for brand
                                                  file.startsWith( 'phet/js' ) );

    relativeFiles.forEach( ( rel, i ) => {
      console.log( '    ' + i + '/' + relativeFiles.length );
      migrateFile( repo, rel );
    } );
  } );
};<|endoftext|>


<commit_before>var recommend = {
    searchName: mw.config.get('wgPageName'),
    myId: mw.config.get('wgArticleId'),
    category: '',
    pageRec: mw.config.get('wgRecByUser')||[],
    arr: [],
    item: 0,
    netData:'',

    funAddBox: function(){
        $('.comments-body').before('

');
    },

    funGetPageRec: function(){
        var self = this;
        this.pageRec.forEach(function(item,i){
            if(i<4) {
                var content = '';
                content += '
' +
                    '
' +
                    item.title + '' + item.siteName + '

';
                self.arr.push(item.title+item.siteName);
                self.funGetImg(item.title, i, item.site);
                $('.recommend').append(content);
            }
        });
    },

    funGetCategory: function(){
        var self = this;
        if($('#mw-normal-catlinks').length!=0) {
            $('#mw-normal-catlinks li:not(.last)').each(function () {
                self.category += $(this).text() + ' ';
            });
        }
    },

    funGetNetRec: function(){
        var self = this;
        $.ajax({
            url:'http://121.42.179.100:8080/queryService/webapi/page/recommend/',
            data:{content:self.searchName,category:self.category,sitePrefix:mw.config.get('wgHuijiPrefix')},
            success: function (data) {
                var content = '';
                var len = self.pageRec.length;
                self.netData = data;
                if (data.length == 0) return;

                //除去指定推荐，剩下的进行遍历
                if(document.body.clientWidth>768) {
                    for (var i = len; i < 10; i++) {
                        var item = data[i - len];
                        var searchtitle = item.title;
                        var id = item.id;

                        //排除本词条和重复词条
//                    if (id != self.myId && self.arr.indexOf(searchtitle+item.siteName)<0) {
                        var sitePrefix = item.sitePrefix;

                        //去em标签
                        searchtitle = searchtitle.replace(//g, '').replace(/<\/em>/g, '');

                        content += '

' + item.title + '' + item.siteName + '

';
                        self.funGetImg(searchtitle, i, sitePrefix, item.address, false);
                    }
                    self.item = i;
                }else{
                    for (var i = len; i < 4; i++) {
                        var item = data[i - len];
                        var searchtitle = item.title;
                        var id = item.id;

                        //排除本词条和重复词条
//                    if (id != self.myId && self.arr.indexOf(searchtitle+item.siteName)<0) {
                        var sitePrefix = item.sitePrefix;

                        //去em标签
                        searchtitle = searchtitle.replace(//g, '').replace(/<\/em>/g, '');

                        content += '

' + item.title + '' + item.siteName + '

';
                        self.funGetImg(searchtitle, i, sitePrefix, false);
                    }
                    self.item = i;
                }
//                }
                $('.recommend').append(content);
            },
            type: 'post'
        });
    },

    funGetImg: function(title,id,sitePrefix,address,ajax){
        var self = this;
        $.ajax({
            url:'http://'+sitePrefix+'.huiji.wiki/api.php?action=query&prop=pageimages&format=json&pithumbsize=250&titles='+title,
            type: 'get',
            success: function(data){
                var x;
                for( x in data.query.pages) {
                    if (data.query.pages[x].thumbnail) {
                        var img = '';
                        var wid;
                        var wid2;
                        var percent = data.query.pages[x].thumbnail.width / data.query.pages[x].thumbnail.height;

                        $('#' + id ).prepend(img);
                        $('#' + id).removeClass('re-opacity');

                        //更宽裁剪两边
                        if (percent > 0.7) {
                            wid = percent * 100 - 70;
                            wid2 = percent * 100 + 70;
                            $('#' + id).find('img').css({'clip': 'rect(0,' + wid2 + 'px,200px,' + wid + 'px)', 'left': '-' + wid + 'px', 'height': '200px'});
                        }
                        //更高裁剪上下
                        else if (percent < 0.7) {
                            wid = 1 / percent * 70 - 100;
                            wid2 = 1 / percent * 70 + 100;
                            $('#' + id).find('img').css({'clip': 'rect(' + wid + 'px,140px,' + wid2 + 'px,0)', 'top': '-' + wid + 'px', 'width': '140px'});
                        }
                        else {
                            $('#' + id).find('img').css('height', '200px');
                            $('#' + id).removeClass('re-opacity');
                        }

                    } else {
                        $('#' + id).removeClass('re-opacity');
                        $('#' + id).prepend('');
                    }
                }
                if(sitePrefix!=mw.config.get('wgHuijiPrefix')){
                    $('#'+id+' .recommend-title>a:last-child').show();
                }
                if(ajax == false) {
                    if ($('.recommend-header').length == 0) {
                        $('.recommend').before('
更多推荐
');
                    }

                    //最后一次取图判断是否去掉推荐内容
                    if (id == self.item-1) {
                        if ($('.recommend .recommend-item').length == 0) $('.recommend').remove();
                        $("#recommend").owlCarousel({
                            items: 5,
//                            lazyLoad: true,
                            beforeMove: function () {
                                var sp = $('.owl-wrapper').css('transform').split(',');
                                var len = self.pageRec.length;
                                var data = self.netData;
                                var n = self.item;
                                sp = Math.abs(parseInt(sp[4]));

                                if(n<30&&document.body.clientWidth>768) {
                                    if (sp > ($('.owl-item').length - 5) * $('.owl-item').width()) {
                                        setTimeout(function(){
                                            var load = '

';
                                            $('#recommend').data('owlCarousel').addItem(load);
                                            $('#recommend').data('owlCarousel').jumpTo(n);
                                        },100);
                                        for (var i = n; i < n + 2; i++) {
                                            var item = data[i - len];
                                            var searchtitle = item.title;
                                            var id = item.id;
                                            //排除本词条和重复词条
//                                        if (id != self.myId && self.arr.indexOf(searchtitle+item.siteName)<0) {
                                            var sitePrefix = item.sitePrefix;

                                            //去em标签
                                            searchtitle = searchtitle.replace(//g, '').replace(/<\/em>/g, '');

                                            self.funGetImg2(searchtitle, i, sitePrefix, address, item, n, true);
//                                        }
                                            self.item++;
                                        }
                                    }
                                }else if(n>=30&&document.body.clientWidth>768){
                                    if (sp > ($('.owl-item').length - 5) * $('.owl-item').width()) {
                                        setTimeout(function(){
                                            for(var i=n; i<n+2; i++){
                                                var img = '

' +
                                                    'U FOUND ME
cool cool cool!

';
                                                $('#recommend').data('owlCarousel').addItem(img);
                                                $('#recommend').data('owlCarousel').jumpTo(n);
                                                self.item++;
                                            }
                                        },100);

                                    }
                                }
                            }
                        });
                    }
                }
            }
        });
    },
    funGetImg2: function(title,id,sitePrefix, address, item, n, ajax){
        var self = this;
        $.ajax({
            url: 'http://' + sitePrefix + '.huiji.wiki/api.php?action=query&prop=pageimages&format=json&pithumbsize=250&titles=' + title,
            type: 'get',
            success: function (data) {
                var x;
                var img;
                for (x in data.query.pages) {
                    if (data.query.pages[x].thumbnail) {
                        img = '

' +
                            '' + item.title + '' + item.siteName + '

';
                        var wid;
                        var wid2;
                        var percent = data.query.pages[x].thumbnail.width / data.query.pages[x].thumbnail.height;
                        if($('.recommend-load').length>0){
                            $('#recommend').data('owlCarousel').removeItem();
                        }
                        $('#recommend').data('owlCarousel').addItem(img);
//                        $('.owl-wrapper-outer').css('transform','translate3d(-'+(n-5)*$('.owl-item').width()+'px, 0px, 0px);');
                        $('#recommend').data('owlCarousel').jumpTo(n);
                        //更宽裁剪两边
                        if (percent > 0.7) {
                            wid = percent * 100 - 70;
                            wid2 = percent * 100 + 70;
                            $('#' + id).find('img').css({'clip': 'rect(0,' + wid2 + 'px,200px,' + wid + 'px)', 'left': '-' + wid + 'px', 'height': '200px'});
                        }
                        //更高裁剪上下
                        else if (percent < 0.7) {
                            wid = 1 / percent * 70 - 100;
                            wid2 = 1 / percent * 70 + 100;
                            $('#' + id).find('img').css({'clip': 'rect(' + wid + 'px,140px,' + wid2 + 'px,0)', 'top': '-' + wid + 'px', 'width': '140px'});
                        }
                        else {
                            $('#' + id).find('img').css('height', '200px');
                        }

                    } else {
                        img = '

' +
                            '' + item.title + '' + item.siteName + '

';
                    }
                    if(sitePrefix!=mw.config.get('wgHuijiPrefix')){
                        $('#'+id+' .recommend-title>a:last-child').show();
                    }
                }
            }
        });
    },

    init: function(){
        if(mw.config.get('wgRec')||$('body').hasClass('ns-0')&&!mw.config.get('wgNoRec')){
            this.funAddBox();
            this.funGetPageRec();
            this.funGetCategory();
            this.funGetNetRec();
        }
    }
}
$(function(){

    recommend.init();

});
<commit_msg>you found me<commit_after>var recommend = {
    searchName: mw.config.get('wgPageName'),
    myId: mw.config.get('wgArticleId'),
    category: '',
    pageRec: mw.config.get('wgRecByUser')||[],
    arr: [],
    item: 0,
    netData:'',

    funAddBox: function(){
        $('.comments-body').before('

');
    },

    funGetPageRec: function(){
        var self = this;
        this.pageRec.forEach(function(item,i){
            if(i<4) {
                var content = '';
                content += '
' +
                    '
' +
                    item.title + '' + item.siteName + '

';
                self.arr.push(item.title+item.siteName);
                self.funGetImg(item.title, i, item.site);
                $('.recommend').append(content);
            }
        });
    },

    funGetCategory: function(){
        var self = this;
        if($('#mw-normal-catlinks').length!=0) {
            $('#mw-normal-catlinks li:not(.last)').each(function () {
                self.category += $(this).text() + ' ';
            });
        }
    },

    funGetNetRec: function(){
        var self = this;
        $.ajax({
            url:'http://121.42.179.100:8080/queryService/webapi/page/recommend/',
            data:{content:self.searchName,category:self.category,sitePrefix:mw.config.get('wgHuijiPrefix')},
            success: function (data) {
                var content = '';
                var len = self.pageRec.length;
                self.netData = data;
                if (data.length == 0) return;

                //除去指定推荐，剩下的进行遍历
                if(document.body.clientWidth>768) {
                    for (var i = len; i < 10; i++) {
                        var item = data[i - len];
                        var searchtitle = item.title;
                        var id = item.id;

                        //排除本词条和重复词条
//                    if (id != self.myId && self.arr.indexOf(searchtitle+item.siteName)<0) {
                        var sitePrefix = item.sitePrefix;

                        //去em标签
                        searchtitle = searchtitle.replace(//g, '').replace(/<\/em>/g, '');

                        content += '

' + item.title + '' + item.siteName + '

';
                        self.funGetImg(searchtitle, i, sitePrefix, item.address, false);
                    }
                    self.item = i;
                }else{
                    for (var i = len; i < 4; i++) {
                        var item = data[i - len];
                        var searchtitle = item.title;
                        var id = item.id;

                        //排除本词条和重复词条
//                    if (id != self.myId && self.arr.indexOf(searchtitle+item.siteName)<0) {
                        var sitePrefix = item.sitePrefix;

                        //去em标签
                        searchtitle = searchtitle.replace(//g, '').replace(/<\/em>/g, '');

                        content += '

' + item.title + '' + item.siteName + '

';
                        self.funGetImg(searchtitle, i, sitePrefix, false);
                    }
                    self.item = i;
                }
//                }
                $('.recommend').append(content);
            },
            type: 'post'
        });
    },

    funGetImg: function(title,id,sitePrefix,address,ajax){
        var self = this;
        $.ajax({
            url:'http://'+sitePrefix+'.huiji.wiki/api.php?action=query&prop=pageimages&format=json&pithumbsize=250&titles='+title,
            type: 'get',
            success: function(data){
                var x;
                for( x in data.query.pages) {
                    if (data.query.pages[x].thumbnail) {
                        var img = '';
                        var wid;
                        var wid2;
                        var percent = data.query.pages[x].thumbnail.width / data.query.pages[x].thumbnail.height;

                        $('#' + id ).prepend(img);
                        $('#' + id).removeClass('re-opacity');

                        //更宽裁剪两边
                        if (percent > 0.7) {
                            wid = percent * 100 - 70;
                            wid2 = percent * 100 + 70;
                            $('#' + id).find('img').css({'clip': 'rect(0,' + wid2 + 'px,200px,' + wid + 'px)', 'left': '-' + wid + 'px', 'height': '200px'});
                        }
                        //更高裁剪上下
                        else if (percent < 0.7) {
                            wid = 1 / percent * 70 - 100;
                            wid2 = 1 / percent * 70 + 100;
                            $('#' + id).find('img').css({'clip': 'rect(' + wid + 'px,140px,' + wid2 + 'px,0)', 'top': '-' + wid + 'px', 'width': '140px'});
                        }
                        else {
                            $('#' + id).find('img').css('height', '200px');
                            $('#' + id).removeClass('re-opacity');
                        }

                    } else {
                        $('#' + id).removeClass('re-opacity');
                        $('#' + id).prepend('');
                    }
                }
                if(sitePrefix!=mw.config.get('wgHuijiPrefix')){
                    $('#'+id+' .recommend-title>a:last-child').show();
                }
                if(ajax == false) {
                    if ($('.recommend-header').length == 0) {
                        $('.recommend').before('
更多推荐
');
                    }

                    //最后一次取图判断是否去掉推荐内容
                    if (id == self.item-1) {
                        if ($('.recommend .recommend-item').length == 0) $('.recommend').remove();
                        $("#recommend").owlCarousel({
                            items: 5,
//                            lazyLoad: true,
                            beforeMove: function () {
                                var sp = $('.owl-wrapper').css('transform').split(',');
                                var len = self.pageRec.length;
                                var data = self.netData;
                                var n = self.item;
                                sp = Math.abs(parseInt(sp[4]));

                                if(n<30&&document.body.clientWidth>768) {
                                    if (sp > ($('.owl-item').length - 5) * $('.owl-item').width()) {
                                        setTimeout(function(){
                                            var load = '

';
                                            $('#recommend').data('owlCarousel').addItem(load);
                                            $('#recommend').data('owlCarousel').jumpTo(n);
                                        },100);
                                        for (var i = n; i < n + 2; i++) {
                                            var item = data[i - len];
                                            var searchtitle = item.title;
                                            var id = item.id;
                                            //排除本词条和重复词条
//                                        if (id != self.myId && self.arr.indexOf(searchtitle+item.siteName)<0) {
                                            var sitePrefix = item.sitePrefix;

                                            //去em标签
                                            searchtitle = searchtitle.replace(//g, '').replace(/<\/em>/g, '');

                                            self.funGetImg2(searchtitle, i, sitePrefix, address, item, n, true);
//                                        }
                                            self.item++;
                                        }
                                    }
                                }else if(n>=30&&document.body.clientWidth>768){
                                    if (sp > ($('.owl-item').length - 5) * $('.owl-item').width()) {
                                        setTimeout(function(){
                                            for(var i=n; i<n+2; i++){
                                                var img = '

' +
                                                    'U FOUND ME
cool cool cool!

';
                                                $('#recommend').data('owlCarousel').addItem(img);
                                                $('#recommend').data('owlCarousel').jumpTo(n);
                                                self.item++;
                                            }
                                        },100);

                                    }
                                }
                            }
                        });
                    }
                }
            }
        });
    },
    funGetImg2: function(title,id,sitePrefix, address, item, n, ajax){
        var self = this;
        $.ajax({
            url: 'http://' + sitePrefix + '.huiji.wiki/api.php?action=query&prop=pageimages&format=json&pithumbsize=250&titles=' + title,
            type: 'get',
            success: function (data) {
                var x;
                var img;
                for (x in data.query.pages) {
                    if (data.query.pages[x].thumbnail) {
                        img = '

' +
                            '' + item.title + '' + item.siteName + '

';
                        var wid;
                        var wid2;
                        var percent = data.query.pages[x].thumbnail.width / data.query.pages[x].thumbnail.height;
                        if($('.recommend-load').length>0){
                            $('#recommend').data('owlCarousel').removeItem();
                        }
                        $('#recommend').data('owlCarousel').addItem(img);
//                        $('.owl-wrapper-outer').css('transform','translate3d(-'+(n-5)*$('.owl-item').width()+'px, 0px, 0px);');
                        $('#recommend').data('owlCarousel').jumpTo(n);
                        //更宽裁剪两边
                        if (percent > 0.7) {
                            wid = percent * 100 - 70;
                            wid2 = percent * 100 + 70;
                            $('#' + id).find('img').css({'clip': 'rect(0,' + wid2 + 'px,200px,' + wid + 'px)', 'left': '-' + wid + 'px', 'height': '200px'});
                        }
                        //更高裁剪上下
                        else if (percent < 0.7) {
                            wid = 1 / percent * 70 - 100;
                            wid2 = 1 / percent * 70 + 100;
                            $('#' + id).find('img').css({'clip': 'rect(' + wid + 'px,140px,' + wid2 + 'px,0)', 'top': '-' + wid + 'px', 'width': '140px'});
                        }
                        else {
                            $('#' + id).find('img').css('height', '200px');
                        }

                    } else {
                        img = '

' +
                            '' + item.title + '' + item.siteName + '

';
                    }
                    if(sitePrefix!=mw.config.get('wgHuijiPrefix')){
                        $('#'+id+' .recommend-title>a:last-child').show();
                    }
                }
            }
        });
    },

    init: function(){
        if(mw.config.get('wgRec')||$('body').hasClass('ns-0')&&!mw.config.get('wgNoRec')){
            this.funAddBox();
            this.funGetPageRec();
            this.funGetCategory();
            this.funGetNetRec();
        }
    }
}
$(function(){

    recommend.init();

});
<|endoftext|>


<commit_before>iD.svg.Labels = function(projection, context) {

    // Replace with dict and iterate over entities tags instead?
    var label_stack = [
        ['line', 'aeroway'],
        ['line', 'highway'],
        ['line', 'railway'],
        ['line', 'waterway'],
        ['area', 'aeroway'],
        ['area', 'amenity'],
        ['area', 'building'],
        ['area', 'historic'],
        ['area', 'leisure'],
        ['area', 'man_made'],
        ['area', 'natural'],
        ['area', 'shop'],
        ['area', 'tourism'],
        ['point', 'aeroway'],
        ['point', 'amenity'],
        ['point', 'building'],
        ['point', 'historic'],
        ['point', 'leisure'],
        ['point', 'man_made'],
        ['point', 'natural'],
        ['point', 'shop'],
        ['point', 'tourism'],
        ['line', 'name'],
        ['area', 'name'],
        ['point', 'name']
    ];

    var default_size = 12;

    var font_sizes = label_stack.map(function(d) {
        var style = iD.util.getStyle('text.' + d[0] + '.tag-' + d[1]),
            m = style && style.cssText.match("font-size: ([0-9]{1,2})px;");
        if (m) return parseInt(m[1], 10);

        style = iD.util.getStyle('text.' + d[0]);
        m = style && style.cssText.match("font-size: ([0-9]{1,2})px;");
        if (m) return parseInt(m[1], 10);

        return default_size;
    });

    var iconSize = 18;

    var pointOffsets = [
        [15, -11, 'start'], // right
        [10, -11, 'start'], // unused right now
        [-15, -11, 'end']
    ];

    var lineOffsets = [50, 45, 55, 40, 60, 35, 65, 30, 70, 25,
        75, 20, 80, 15, 95, 10, 90, 5, 95];

    var noIcons = ['building', 'landuse', 'natural'];
    function blacklisted(preset) {
        return _.any(noIcons, function(s) {
            return preset.id.indexOf(s) >= 0;
        });
    }

    function get(array, prop) {
        return function(d, i) { return array[i][prop]; };
    }

    var textWidthCache = {};

    function textWidth(text, size, elem) {
        var c = textWidthCache[size];
        if (!c) c = textWidthCache[size] = {};

        if (c[text]) {
            return c[text];

        } else if (elem) {
            c[text] = elem.getComputedTextLength();
            return c[text];

        } else {
            var str = encodeURIComponent(text).match(/%[CDEFcdef]/g);
            if (str === null) {
                return size / 3 * 2 * text.length;
            } else {
                return size / 3 * (2 * text.length + str.length);
            }
        }
    }

    function drawLineLabels(group, entities, filter, classes, labels) {

        var texts = group.selectAll('text.' + classes)
            .filter(filter)
            .data(entities, iD.Entity.key);

        var tp = texts.enter()
            .append('text')
            .attr('class', function(d, i) { return classes + ' ' + labels[i].classes + ' ' + d.id; })
            .append('textPath')
            .attr('class', 'textpath');

        var tps = texts.selectAll('.textpath')
            .filter(filter)
            .data(entities, iD.Entity.key)
            .attr({
                'startOffset': '50%',
                'xlink:href': function(d) { return '#labelpath-' + d.id; }
            })
            .text(iD.util.displayName);

        texts.exit().remove();

    }

    function drawLinePaths(group, entities, filter, classes, labels) {

        var halos = group.selectAll('path')
            .filter(filter)
            .data(entities, iD.Entity.key);

        halos.enter()
            .append('path')
            .style('stroke-width', get(labels, 'font-size'))
            .attr('id', function(d) { return 'labelpath-' + d.id; })
            .attr('class', classes);

        halos.attr('d', get(labels, 'lineString'));

        halos.exit().remove();
    }

    function drawPointLabels(group, entities, filter, classes, labels) {

        var texts = group.selectAll('text.' + classes)
            .filter(filter)
            .data(entities, iD.Entity.key);

        texts.enter()
            .append('text')
            .attr('class', function(d, i) { return classes + ' ' + labels[i].classes + ' ' + d.id; });

        texts.attr('x', get(labels, 'x'))
            .attr('y', get(labels, 'y'))
            .style('text-anchor', get(labels, 'textAnchor'))
            .text(iD.util.displayName)
            .each(function(d, i) { textWidth(iD.util.displayName(d), labels[i].height, this); });

        texts.exit().remove();
        return texts;
    }

    function drawAreaLabels(group, entities, filter, classes, labels) {
        entities = entities.filter(hasText);
        labels = labels.filter(hasText);
        return drawPointLabels(group, entities, filter, classes, labels);

        function hasText(d, i) {
            return labels[i].hasOwnProperty('x') && labels[i].hasOwnProperty('y');
        }
    }

    function drawAreaIcons(group, entities, filter, classes, labels) {

        var icons = group.selectAll('use')
            .filter(filter)
            .data(entities, iD.Entity.key);

        icons.enter()
            .append('use')
            .attr('clip-path', 'url(#clip-square-18)')
            .attr('class', 'icon');

        icons.attr('transform', get(labels, 'transform'))
            .attr('xlink:href', function(d) {
                return '#maki-' + context.presets().match(d, context.graph()).icon + '-18';
            });

        icons.exit().remove();
    }

    function reverse(p) {
        var angle = Math.atan2(p[1][1] - p[0][1], p[1][0] - p[0][0]);
        return !(p[0][0] < p[p.length - 1][0] && angle < Math.PI/2 && angle > - Math.PI/2);
    }

    function lineString(nodes) {
        return 'M' + nodes.join('L');
    }

    function subpath(nodes, from, to) {
        function segmentLength(i) {
            var dx = nodes[i][0] - nodes[i + 1][0];
            var dy = nodes[i][1] - nodes[i + 1][1];
            return Math.sqrt(dx * dx + dy * dy);
        }

        var sofar = 0,
            start, end, i0, i1;
        for (var i = 0; i < nodes.length - 1; i++) {
            var current = segmentLength(i);
            var portion;
            if (!start && sofar + current >= from) {
                portion = (from - sofar) / current;
                start = [
                    nodes[i][0] + portion * (nodes[i + 1][0] - nodes[i][0]),
                    nodes[i][1] + portion * (nodes[i + 1][1] - nodes[i][1])
                ];
                i0 = i + 1;
            }
            if (!end && sofar + current >= to) {
                portion = (to - sofar) / current;
                end = [
                    nodes[i][0] + portion * (nodes[i + 1][0] - nodes[i][0]),
                    nodes[i][1] + portion * (nodes[i + 1][1] - nodes[i][1])
                ];
                i1 = i + 1;
            }
            sofar += current;

        }
        var ret = nodes.slice(i0, i1);
        ret.unshift(start);
        ret.push(end);
        return ret;

    }

    function hideOnMouseover() {
        var layers = d3.select(this)
            .selectAll('.layer-label, .layer-halo');

        layers.selectAll('.proximate')
            .classed('proximate', false);

        var mouse = context.mouse(),
            pad = 50,
            rect = [mouse[0] - pad, mouse[1] - pad, mouse[0] + pad, mouse[1] + pad],
            ids = _.pluck(rtree.search(rect), 'id');

        if (!ids.length) return;
        layers.selectAll('.' + ids.join(', .'))
            .classed('proximate', true);
    }

    var rtree = rbush(),
        rectangles = {};

    function labels(surface, graph, entities, filter, dimensions, fullRedraw) {

        var hidePoints = !surface.select('.node.point').node();

        var labelable = [], i, k, entity;
        for (i = 0; i < label_stack.length; i++) labelable.push([]);

        if (fullRedraw) {
            rtree.clear();
            rectangles = {};
        } else {
            for (i = 0; i < entities.length; i++) {
                rtree.remove(rectangles[entities[i].id]);
            }
        }

        // Split entities into groups specified by label_stack
        for (i = 0; i < entities.length; i++) {
            entity = entities[i];
            var geometry = entity.geometry(graph);

            if (geometry === 'vertex')
                continue;
            if (hidePoints && geometry === 'point')
                continue;

            var preset = geometry === 'area' && context.presets().match(entity, graph),
                icon = preset && !blacklisted(preset) && preset.icon;

            if (!icon && !iD.util.displayName(entity))
                continue;

            for (k = 0; k < label_stack.length; k ++) {
                if (geometry === label_stack[k][0] && entity.tags[label_stack[k][1]]) {
                    labelable[k].push(entity);
                    break;
                }
            }
        }

        var positions = {
            point: [],
            line: [],
            area: []
        };

        var labelled = {
            point: [],
            line: [],
            area: []
        };

        // Try and find a valid label for labellable entities
        for (k = 0; k < labelable.length; k++) {
            var font_size = font_sizes[k];
            for (i = 0; i < labelable[k].length; i ++) {
                entity = labelable[k][i];
                var name = iD.util.displayName(entity),
                    width = name && textWidth(name, font_size),
                    p;
                if (entity.geometry(graph) === 'point') {
                    p = getPointLabel(entity, width, font_size);
                } else if (entity.geometry(graph) === 'line') {
                    p = getLineLabel(entity, width, font_size);
                } else if (entity.geometry(graph) === 'area') {
                    p = getAreaLabel(entity, width, font_size);
                }
                if (p) {
                    p.classes = entity.geometry(graph) + ' tag-' + label_stack[k][1];
                    positions[entity.geometry(graph)].push(p);
                    labelled[entity.geometry(graph)].push(entity);
                }
            }
        }

        function getPointLabel(entity, width, height) {
            var coord = projection(entity.loc),
                m = 5,  // margin
                offset = pointOffsets[0],
                p = {
                    height: height,
                    width: width,
                    x: coord[0] + offset[0],
                    y: coord[1] + offset[1],
                    textAnchor: offset[2]
                };
            var rect = [p.x - m, p.y - m, p.x + width + m, p.y + height + m];
            if (tryInsert(rect, entity.id)) return p;
        }

        function getLineLabel(entity, width, height) {
            var nodes = _.pluck(graph.childNodes(entity), 'loc').map(projection),
                length = iD.geo.pathLength(nodes);
            if (length < width + 20) return;

            for (var i = 0; i < lineOffsets.length; i ++) {
                var offset = lineOffsets[i],
                    middle = offset / 100 * length,
                    start = middle - width/2;
                if (start < 0 || start + width > length) continue;
                var sub = subpath(nodes, start, start + width),
                    rev = reverse(sub),
                    rect = [
                        Math.min(sub[0][0], sub[sub.length - 1][0]) - 10,
                        Math.min(sub[0][1], sub[sub.length - 1][1]) - 10,
                        Math.max(sub[0][0], sub[sub.length - 1][0]) + 20,
                        Math.max(sub[0][1], sub[sub.length - 1][1]) + 30
                    ];
                if (rev) sub = sub.reverse();
                if (tryInsert(rect, entity.id)) return {
                    'font-size': height + 2,
                    lineString: lineString(sub),
                    startOffset: offset + '%'
                };
            }
        }

        function getAreaLabel(entity, width, height) {
            var path = d3.geo.path().projection(projection),
                centroid = path.centroid(entity.asGeoJSON(graph, true)),
                extent = entity.extent(graph),
                entitywidth = projection(extent[1])[0] - projection(extent[0])[0],
                rect;

            if (!centroid || entitywidth < 20) return;

            var iconX = centroid[0] - (iconSize/2),
                iconY = centroid[1] - (iconSize/2),
                textOffset = iconSize + 5;

            var p = {
                transform: 'translate(' + iconX + ',' + iconY + ')'
            };

            if (width && entitywidth >= width + 20) {
                p.x = centroid[0];
                p.y = centroid[1] + textOffset;
                p.textAnchor = 'middle';
                p.height = height;
                rect = [p.x - width/2, p.y, p.x + width/2, p.y + height + textOffset];
            } else {
                rect = [iconX, iconY, iconX + iconSize, iconY + iconSize];
            }

            if (tryInsert(rect, entity.id)) return p;

        }

        function tryInsert(rect, id) {
            // Check that label is visible
            if (rect[0] < 0 || rect[1] < 0 || rect[2] > dimensions[0] ||
                rect[3] > dimensions[1]) return false;
            var v = rtree.search(rect).length === 0;
            if (v) {
                rect.id = id;
                rtree.insert(rect);
                rectangles[id] = rect;
            }
            return v;
        }

        var label = surface.select('.layer-label'),
            halo = surface.select('.layer-halo');

        // points
        drawPointLabels(label, labelled.point, filter, 'pointlabel', positions.point);
        drawPointLabels(halo, labelled.point, filter, 'pointlabel-halo', positions.point);

        // lines
        drawLinePaths(halo, labelled.line, filter, '', positions.line);
        drawLineLabels(label, labelled.line, filter, 'linelabel', positions.line);
        drawLineLabels(halo, labelled.line, filter, 'linelabel-halo', positions.line);

        // areas
        drawAreaLabels(label, labelled.area, filter, 'arealabel', positions.area);
        drawAreaLabels(halo, labelled.area, filter, 'arealabel-halo', positions.area);
        drawAreaIcons(label, labelled.area, filter, 'arealabel-icon', positions.area);
    }

    labels.supersurface = function(supersurface) {
        supersurface
            .on('mousemove.hidelabels', hideOnMouseover)
            .on('mousedown.hidelabels', function () {
                supersurface.on('mousemove.hidelabels', null);
            })
            .on('mouseup.hidelabels', function () {
                supersurface.on('mousemove.hidelabels', hideOnMouseover);
            });
    };

    return labels;
};
<commit_msg>Cache path<commit_after>iD.svg.Labels = function(projection, context) {
    var path = d3.geo.path().projection(projection);

    // Replace with dict and iterate over entities tags instead?
    var label_stack = [
        ['line', 'aeroway'],
        ['line', 'highway'],
        ['line', 'railway'],
        ['line', 'waterway'],
        ['area', 'aeroway'],
        ['area', 'amenity'],
        ['area', 'building'],
        ['area', 'historic'],
        ['area', 'leisure'],
        ['area', 'man_made'],
        ['area', 'natural'],
        ['area', 'shop'],
        ['area', 'tourism'],
        ['point', 'aeroway'],
        ['point', 'amenity'],
        ['point', 'building'],
        ['point', 'historic'],
        ['point', 'leisure'],
        ['point', 'man_made'],
        ['point', 'natural'],
        ['point', 'shop'],
        ['point', 'tourism'],
        ['line', 'name'],
        ['area', 'name'],
        ['point', 'name']
    ];

    var default_size = 12;

    var font_sizes = label_stack.map(function(d) {
        var style = iD.util.getStyle('text.' + d[0] + '.tag-' + d[1]),
            m = style && style.cssText.match("font-size: ([0-9]{1,2})px;");
        if (m) return parseInt(m[1], 10);

        style = iD.util.getStyle('text.' + d[0]);
        m = style && style.cssText.match("font-size: ([0-9]{1,2})px;");
        if (m) return parseInt(m[1], 10);

        return default_size;
    });

    var iconSize = 18;

    var pointOffsets = [
        [15, -11, 'start'], // right
        [10, -11, 'start'], // unused right now
        [-15, -11, 'end']
    ];

    var lineOffsets = [50, 45, 55, 40, 60, 35, 65, 30, 70, 25,
        75, 20, 80, 15, 95, 10, 90, 5, 95];

    var noIcons = ['building', 'landuse', 'natural'];
    function blacklisted(preset) {
        return _.any(noIcons, function(s) {
            return preset.id.indexOf(s) >= 0;
        });
    }

    function get(array, prop) {
        return function(d, i) { return array[i][prop]; };
    }

    var textWidthCache = {};

    function textWidth(text, size, elem) {
        var c = textWidthCache[size];
        if (!c) c = textWidthCache[size] = {};

        if (c[text]) {
            return c[text];

        } else if (elem) {
            c[text] = elem.getComputedTextLength();
            return c[text];

        } else {
            var str = encodeURIComponent(text).match(/%[CDEFcdef]/g);
            if (str === null) {
                return size / 3 * 2 * text.length;
            } else {
                return size / 3 * (2 * text.length + str.length);
            }
        }
    }

    function drawLineLabels(group, entities, filter, classes, labels) {

        var texts = group.selectAll('text.' + classes)
            .filter(filter)
            .data(entities, iD.Entity.key);

        var tp = texts.enter()
            .append('text')
            .attr('class', function(d, i) { return classes + ' ' + labels[i].classes + ' ' + d.id; })
            .append('textPath')
            .attr('class', 'textpath');

        var tps = texts.selectAll('.textpath')
            .filter(filter)
            .data(entities, iD.Entity.key)
            .attr({
                'startOffset': '50%',
                'xlink:href': function(d) { return '#labelpath-' + d.id; }
            })
            .text(iD.util.displayName);

        texts.exit().remove();

    }

    function drawLinePaths(group, entities, filter, classes, labels) {

        var halos = group.selectAll('path')
            .filter(filter)
            .data(entities, iD.Entity.key);

        halos.enter()
            .append('path')
            .style('stroke-width', get(labels, 'font-size'))
            .attr('id', function(d) { return 'labelpath-' + d.id; })
            .attr('class', classes);

        halos.attr('d', get(labels, 'lineString'));

        halos.exit().remove();
    }

    function drawPointLabels(group, entities, filter, classes, labels) {

        var texts = group.selectAll('text.' + classes)
            .filter(filter)
            .data(entities, iD.Entity.key);

        texts.enter()
            .append('text')
            .attr('class', function(d, i) { return classes + ' ' + labels[i].classes + ' ' + d.id; });

        texts.attr('x', get(labels, 'x'))
            .attr('y', get(labels, 'y'))
            .style('text-anchor', get(labels, 'textAnchor'))
            .text(iD.util.displayName)
            .each(function(d, i) { textWidth(iD.util.displayName(d), labels[i].height, this); });

        texts.exit().remove();
        return texts;
    }

    function drawAreaLabels(group, entities, filter, classes, labels) {
        entities = entities.filter(hasText);
        labels = labels.filter(hasText);
        return drawPointLabels(group, entities, filter, classes, labels);

        function hasText(d, i) {
            return labels[i].hasOwnProperty('x') && labels[i].hasOwnProperty('y');
        }
    }

    function drawAreaIcons(group, entities, filter, classes, labels) {

        var icons = group.selectAll('use')
            .filter(filter)
            .data(entities, iD.Entity.key);

        icons.enter()
            .append('use')
            .attr('clip-path', 'url(#clip-square-18)')
            .attr('class', 'icon');

        icons.attr('transform', get(labels, 'transform'))
            .attr('xlink:href', function(d) {
                return '#maki-' + context.presets().match(d, context.graph()).icon + '-18';
            });

        icons.exit().remove();
    }

    function reverse(p) {
        var angle = Math.atan2(p[1][1] - p[0][1], p[1][0] - p[0][0]);
        return !(p[0][0] < p[p.length - 1][0] && angle < Math.PI/2 && angle > - Math.PI/2);
    }

    function lineString(nodes) {
        return 'M' + nodes.join('L');
    }

    function subpath(nodes, from, to) {
        function segmentLength(i) {
            var dx = nodes[i][0] - nodes[i + 1][0];
            var dy = nodes[i][1] - nodes[i + 1][1];
            return Math.sqrt(dx * dx + dy * dy);
        }

        var sofar = 0,
            start, end, i0, i1;
        for (var i = 0; i < nodes.length - 1; i++) {
            var current = segmentLength(i);
            var portion;
            if (!start && sofar + current >= from) {
                portion = (from - sofar) / current;
                start = [
                    nodes[i][0] + portion * (nodes[i + 1][0] - nodes[i][0]),
                    nodes[i][1] + portion * (nodes[i + 1][1] - nodes[i][1])
                ];
                i0 = i + 1;
            }
            if (!end && sofar + current >= to) {
                portion = (to - sofar) / current;
                end = [
                    nodes[i][0] + portion * (nodes[i + 1][0] - nodes[i][0]),
                    nodes[i][1] + portion * (nodes[i + 1][1] - nodes[i][1])
                ];
                i1 = i + 1;
            }
            sofar += current;

        }
        var ret = nodes.slice(i0, i1);
        ret.unshift(start);
        ret.push(end);
        return ret;

    }

    function hideOnMouseover() {
        var layers = d3.select(this)
            .selectAll('.layer-label, .layer-halo');

        layers.selectAll('.proximate')
            .classed('proximate', false);

        var mouse = context.mouse(),
            pad = 50,
            rect = [mouse[0] - pad, mouse[1] - pad, mouse[0] + pad, mouse[1] + pad],
            ids = _.pluck(rtree.search(rect), 'id');

        if (!ids.length) return;
        layers.selectAll('.' + ids.join(', .'))
            .classed('proximate', true);
    }

    var rtree = rbush(),
        rectangles = {};

    function labels(surface, graph, entities, filter, dimensions, fullRedraw) {

        var hidePoints = !surface.select('.node.point').node();

        var labelable = [], i, k, entity;
        for (i = 0; i < label_stack.length; i++) labelable.push([]);

        if (fullRedraw) {
            rtree.clear();
            rectangles = {};
        } else {
            for (i = 0; i < entities.length; i++) {
                rtree.remove(rectangles[entities[i].id]);
            }
        }

        // Split entities into groups specified by label_stack
        for (i = 0; i < entities.length; i++) {
            entity = entities[i];
            var geometry = entity.geometry(graph);

            if (geometry === 'vertex')
                continue;
            if (hidePoints && geometry === 'point')
                continue;

            var preset = geometry === 'area' && context.presets().match(entity, graph),
                icon = preset && !blacklisted(preset) && preset.icon;

            if (!icon && !iD.util.displayName(entity))
                continue;

            for (k = 0; k < label_stack.length; k ++) {
                if (geometry === label_stack[k][0] && entity.tags[label_stack[k][1]]) {
                    labelable[k].push(entity);
                    break;
                }
            }
        }

        var positions = {
            point: [],
            line: [],
            area: []
        };

        var labelled = {
            point: [],
            line: [],
            area: []
        };

        // Try and find a valid label for labellable entities
        for (k = 0; k < labelable.length; k++) {
            var font_size = font_sizes[k];
            for (i = 0; i < labelable[k].length; i ++) {
                entity = labelable[k][i];
                var name = iD.util.displayName(entity),
                    width = name && textWidth(name, font_size),
                    p;
                if (entity.geometry(graph) === 'point') {
                    p = getPointLabel(entity, width, font_size);
                } else if (entity.geometry(graph) === 'line') {
                    p = getLineLabel(entity, width, font_size);
                } else if (entity.geometry(graph) === 'area') {
                    p = getAreaLabel(entity, width, font_size);
                }
                if (p) {
                    p.classes = entity.geometry(graph) + ' tag-' + label_stack[k][1];
                    positions[entity.geometry(graph)].push(p);
                    labelled[entity.geometry(graph)].push(entity);
                }
            }
        }

        function getPointLabel(entity, width, height) {
            var coord = projection(entity.loc),
                m = 5,  // margin
                offset = pointOffsets[0],
                p = {
                    height: height,
                    width: width,
                    x: coord[0] + offset[0],
                    y: coord[1] + offset[1],
                    textAnchor: offset[2]
                };
            var rect = [p.x - m, p.y - m, p.x + width + m, p.y + height + m];
            if (tryInsert(rect, entity.id)) return p;
        }

        function getLineLabel(entity, width, height) {
            var nodes = _.pluck(graph.childNodes(entity), 'loc').map(projection),
                length = iD.geo.pathLength(nodes);
            if (length < width + 20) return;

            for (var i = 0; i < lineOffsets.length; i ++) {
                var offset = lineOffsets[i],
                    middle = offset / 100 * length,
                    start = middle - width/2;
                if (start < 0 || start + width > length) continue;
                var sub = subpath(nodes, start, start + width),
                    rev = reverse(sub),
                    rect = [
                        Math.min(sub[0][0], sub[sub.length - 1][0]) - 10,
                        Math.min(sub[0][1], sub[sub.length - 1][1]) - 10,
                        Math.max(sub[0][0], sub[sub.length - 1][0]) + 20,
                        Math.max(sub[0][1], sub[sub.length - 1][1]) + 30
                    ];
                if (rev) sub = sub.reverse();
                if (tryInsert(rect, entity.id)) return {
                    'font-size': height + 2,
                    lineString: lineString(sub),
                    startOffset: offset + '%'
                };
            }
        }

        function getAreaLabel(entity, width, height) {
            var centroid = path.centroid(entity.asGeoJSON(graph, true)),
                extent = entity.extent(graph),
                entitywidth = projection(extent[1])[0] - projection(extent[0])[0],
                rect;

            if (!centroid || entitywidth < 20) return;

            var iconX = centroid[0] - (iconSize/2),
                iconY = centroid[1] - (iconSize/2),
                textOffset = iconSize + 5;

            var p = {
                transform: 'translate(' + iconX + ',' + iconY + ')'
            };

            if (width && entitywidth >= width + 20) {
                p.x = centroid[0];
                p.y = centroid[1] + textOffset;
                p.textAnchor = 'middle';
                p.height = height;
                rect = [p.x - width/2, p.y, p.x + width/2, p.y + height + textOffset];
            } else {
                rect = [iconX, iconY, iconX + iconSize, iconY + iconSize];
            }

            if (tryInsert(rect, entity.id)) return p;

        }

        function tryInsert(rect, id) {
            // Check that label is visible
            if (rect[0] < 0 || rect[1] < 0 || rect[2] > dimensions[0] ||
                rect[3] > dimensions[1]) return false;
            var v = rtree.search(rect).length === 0;
            if (v) {
                rect.id = id;
                rtree.insert(rect);
                rectangles[id] = rect;
            }
            return v;
        }

        var label = surface.select('.layer-label'),
            halo = surface.select('.layer-halo');

        // points
        drawPointLabels(label, labelled.point, filter, 'pointlabel', positions.point);
        drawPointLabels(halo, labelled.point, filter, 'pointlabel-halo', positions.point);

        // lines
        drawLinePaths(halo, labelled.line, filter, '', positions.line);
        drawLineLabels(label, labelled.line, filter, 'linelabel', positions.line);
        drawLineLabels(halo, labelled.line, filter, 'linelabel-halo', positions.line);

        // areas
        drawAreaLabels(label, labelled.area, filter, 'arealabel', positions.area);
        drawAreaLabels(halo, labelled.area, filter, 'arealabel-halo', positions.area);
        drawAreaIcons(label, labelled.area, filter, 'arealabel-icon', positions.area);
    }

    labels.supersurface = function(supersurface) {
        supersurface
            .on('mousemove.hidelabels', hideOnMouseover)
            .on('mousedown.hidelabels', function () {
                supersurface.on('mousemove.hidelabels', null);
            })
            .on('mouseup.hidelabels', function () {
                supersurface.on('mousemove.hidelabels', hideOnMouseover);
            });
    };

    return labels;
};
<|endoftext|>


<commit_before>'use strict';
/**
 * dynamically wrap lob, mesh, and util functions for javascript
**/
var th = require("./thc.js");

const returntypes = {
  "_lob_json" : "json",
  "_hashname_short" : "string",
  "_lob_get" : "string"
};

const Unwrappers = {
  pointer : (_val) => _val,
  number : (_val) => _val,
  string : th.UTF8ToString,
  json : (_val) => JSON.parse(th.UTF8ToString(_val))
}

const makeVarPointer = (_arg, write, mallextra) => {
  var ptr = th._malloc(_arg.length + mallextra);
  write(_arg, ptr);
  return ptr;
}

const Wrappers = {
  number : (_val) => _val,
  function : (_fun) => th.Runtime.addFunction(_fun),
  string : (_string) => makeVarPointer(_string, th.writeStringToMemory, 1),
  object : (_buf) => (Buffer.isBuffer(_buf)) ?  makeVarPointer(_buf, th.writeArrayToMemory, 0) : _buf === null ? 0 :  new Error("only numbers, strings, functions, and buffers accepted"),
  undefined : () => 0,
  boolean : (b) => b ? 1 : 0
}

const wrapFun = (_fun, returntype) => function() {
  let args = [];
  for(let i = 0; i < arguments.length; i++){
    let _arg = arguments[i];
    args.push( Wrappers[typeof _arg](_arg) );
  }
  return Unwrappers[returntype || "number"]( _fun.apply(null,args) );
}

Object.keys(th).filter(key => key.indexOf("_") == 0).forEach((key) => {
  let fn = key.substr(1);
  th[fn] = wrapFun(th[key], returntypes[key]);
  // globalize all the funthings!
  if(fn.indexOf("_") > 0) global[fn] = th[fn];
})

th._e3x_random(th.Runtime.addFunction(rand));

th.CALLBACK = (fun, types) => function(){
  let args = [];
  for(let i = 0; i < arguments.length; i++){
    args[i] = Unwrappers[types[i] || "number"](arguments[i]);
  }
  return _fun.apply(null,args);
}

th.BUFFER = (ptr, len) => {
  let buf = new Buffer(len);
  for (let i =0; i < len; i++){
    buf[i] = th.getValue(ptr + i)
  }
  return buf;
}

module.exports = th;<commit_msg>remove rng from auto insertion, leave it to mantle<commit_after>'use strict';
/**
 * dynamically wrap lob, mesh, and util functions for javascript
**/
var th = require("./thc.js");

const returntypes = {
  "_lob_json" : "json",
  "_hashname_short" : "string",
  "_lob_get" : "string"
};

const Unwrappers = {
  pointer : (_val) => _val,
  number : (_val) => _val,
  string : th.UTF8ToString,
  json : (_val) => JSON.parse(th.UTF8ToString(_val))
}

const makeVarPointer = (_arg, write, mallextra) => {
  var ptr = th._malloc(_arg.length + mallextra);
  write(_arg, ptr);
  return ptr;
}

const Wrappers = {
  number : (_val) => _val,
  function : (_fun) => th.Runtime.addFunction(_fun),
  string : (_string) => makeVarPointer(_string, th.writeStringToMemory, 1),
  object : (_buf) => (Buffer.isBuffer(_buf)) ?  makeVarPointer(_buf, th.writeArrayToMemory, 0) : _buf === null ? 0 :  new Error("only numbers, strings, functions, and buffers accepted"),
  undefined : () => 0,
  boolean : (b) => b ? 1 : 0
}

const wrapFun = (_fun, returntype) => function() {
  let args = [];
  for(let i = 0; i < arguments.length; i++){
    let _arg = arguments[i];
    args.push( Wrappers[typeof _arg](_arg) );
  }
  return Unwrappers[returntype || "number"]( _fun.apply(null,args) );
}

Object.keys(th).filter(key => key.indexOf("_") == 0).forEach((key) => {
  let fn = key.substr(1);
  th[fn] = wrapFun(th[key], returntypes[key]);
  // globalize all the funthings!
  if(fn.indexOf("_") > 0) global[fn] = th[fn];
})

th.CALLBACK = (fun, types) => function(){
  let args = [];
  for(let i = 0; i < arguments.length; i++){
    args[i] = Unwrappers[types[i] || "number"](arguments[i]);
  }
  return _fun.apply(null,args);
}

th.BUFFER = (ptr, len) => {
  let buf = new Buffer(len);
  for (let i =0; i < len; i++){
    buf[i] = th.getValue(ptr + i)
  }
  return buf;
}

module.exports = th;<|endoftext|>


<commit_before>import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actionCreators from '../../actions/accounts';
import {
  Table,
  TableBody,
  TableFooter,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn,
} from 'material-ui/Table';
import TextField from 'material-ui/TextField';
import Toggle from 'material-ui/Toggle';

import styles from './styles.scss';

function mapStateToProps(state) {
  return {
    data: state.accounts.data,
    token: state.auth.token,
    loaded: state.accounts.loaded,
    isFetching: state.accounts.isFetching,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

@connect(mapStateToProps, mapDispatchToProps)
export default class TransactionsList extends React.Component {
  state = {
    selectedAccount: 0,
    fixedHeader: true,
    fixedFooter: true,
    stripedRows: true,
    showRowHover: false,
    selectable: false,
    multiSelectable: false,
    enableSelectAll: false,
    deselectOnClickaway: false,
    showCheckboxes: false,
    height: '300px',
  };

  componentWillMount() {
    this.setState({selectedAccount: this.props.selectedAccount})
  }

  handleToggle = (event, toggled) => {
    this.setState({
      [event.target.name]: toggled,
    });
  };

  handleChange = (event) => {
    this.setState({height: event.target.value});
  };

  addRow() {
    console.log('addRow called!')
  }

  renderTransactionsList( transactions ) {
    const rows = transactions.map((row) => {
      return (
        <TableRow>
          <TableHeaderColumn className={styles.smallColumn}></TableHeaderColumn>
          <TableHeaderColumn></TableHeaderColumn>
          <TableHeaderColumn className={styles.smallColumn}></TableHeaderColumn>
          <TableHeaderColumn className={styles.smallColumn}></TableHeaderColumn>
        </TableRow>
      )
    })
    return rows
  }

  render() {
    return (

      {!this.props.loaded
        ?
Loading data...

        :

            <TableHeader
              displaySelectAll={this.state.showCheckboxes}
              adjustForCheckbox={this.state.showCheckboxes}
              enableSelectAll={this.state.enableSelectAll}
            >
              <TableRow>
                <TableHeaderColumn className={styles.smallColumn}>Date</TableHeaderColumn>
                <TableHeaderColumn>Label</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}>Debit</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}>Credit</TableHeaderColumn>
              </TableRow>
            </TableHeader>
            <TableBody>
              {this.renderTransactionsList([])}
            </TableBody>
            <TableFooter
              adjustForCheckbox={this.state.showCheckboxes}
            >
              <TableRow>
                <TableRowColumn onTouchTap={this.addRow} colSpan="4" style={{textAlign: 'center'}}>
                  Click here to add a new transaction
                </TableRowColumn>
              </TableRow>
            </TableFooter>

      }

    );
  }
}

TransactionsList.propTypes = {
  fetchAccountsData: React.PropTypes.func,
  loaded: React.PropTypes.bool,
  data: React.PropTypes.any,
  token: React.PropTypes.string,
};
<commit_msg>Make addDraftRow work<commit_after>import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actionCreators from '../../actions/accounts';
import {
  Table,
  TableBody,
  TableFooter,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn,
} from 'material-ui/Table';
import TextField from 'material-ui/TextField';
import Toggle from 'material-ui/Toggle';

import styles from './styles.scss';

function mapStateToProps(state) {
  return {
    data: state.accounts.data,
    token: state.auth.token,
    loaded: state.accounts.loaded,
    isFetching: state.accounts.isFetching,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

@connect(mapStateToProps, mapDispatchToProps)
export default class TransactionsList extends React.Component {
  state = {
    selectedAccount: 0,
    transactionsList: [],
    fixedHeader: true,
    fixedFooter: true,
    stripedRows: true,
    showRowHover: false,
    selectable: false,
    multiSelectable: false,
    enableSelectAll: false,
    deselectOnClickaway: false,
    showCheckboxes: false,
    height: '400px',
  };

  componentWillMount() {
    this.setState({selectedAccount: this.props.selectedAccount})
  }

  handleToggle = (event, toggled) => {
    this.setState({
      [event.target.name]: toggled,
    });
  };

  handleChange = (event) => {
    this.setState({height: event.target.value});
  };

  addDraftRow(row) {
    let draftRow = {
      date: Date.now(),
      label: '',
      debit: 0,
      credit: 0,
      isDraft: true,
      isRecurring: false,
    }
    this.setState((state) => ({
      transactionsList: state.transactionsList.concat([draftRow])
    }))
  }

  renderTransactionsList( transactions ) {
    const rows = transactions.map((row, index) => {
      return (
        <TableRow key={index}>
          <TableHeaderColumn className={styles.smallColumn}>{row.date.toString()}</TableHeaderColumn>
          <TableHeaderColumn>{row.label}</TableHeaderColumn>
          <TableHeaderColumn className={styles.smallColumn}>{row.credit ? row.credit : ''}</TableHeaderColumn>
          <TableHeaderColumn className={styles.smallColumn}>{row.debit ? row.debit : ''}</TableHeaderColumn>
        </TableRow>
      )
    })
    return rows
  }

  render() {
    return (

      {!this.props.loaded
        ?
Loading data...

        :

            <TableHeader
              displaySelectAll={this.state.showCheckboxes}
              adjustForCheckbox={this.state.showCheckboxes}
              enableSelectAll={this.state.enableSelectAll}
            >
              <TableRow>
                <TableHeaderColumn className={styles.smallColumn}>Date</TableHeaderColumn>
                <TableHeaderColumn>Label</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}>Credit</TableHeaderColumn>
                <TableHeaderColumn className={styles.smallColumn}>Debit</TableHeaderColumn>
              </TableRow>
            </TableHeader>
            <TableBody
              displayRowCheckbox={this.state.showCheckboxes}
              deselectOnClickaway={this.state.deselectOnClickaway}
              showRowHover={this.state.showRowHover}
              stripedRows={this.state.stripedRows}
            >
              {this.renderTransactionsList(this.state.transactionsList)}
            </TableBody>
            <TableFooter
              adjustForCheckbox={this.state.showCheckboxes}
            >
              <TableRow>
                <TableRowColumn onTouchTap={this.addDraftRow.bind(this)} colSpan="4" style={{textAlign: 'center'}}>
                  Click here to add a new transaction
                </TableRowColumn>
              </TableRow>
            </TableFooter>

      }

    );
  }
}

TransactionsList.propTypes = {
  fetchAccountsData: React.PropTypes.func,
  loaded: React.PropTypes.bool,
  data: React.PropTypes.any,
  token: React.PropTypes.string,
};
<|endoftext|>


<commit_before>// Load this file immediately after backbone.debug.js

(function() {

  var instanceType = function(object) {
    if (object instanceof Backbone.Model) return 'Model';
    if (object instanceof Backbone.Collection) return 'Collection';
    if (object instanceof Backbone.View) return 'View';
    if (object instanceof Backbone.Router) return 'Router';
    return '';
  };

  var prettyInstanceName = function(object) {
    var name;
    name = object.constructor.name || instanceType(object);
    if (object.cid) {
      name = "" + name + ":" + object.cid;
    }
    return name;
  };

  var prettyElementName = function(elem) {
    if (!elem) {
      console.warn('[BDT Warning] Incorrect view.el value');
      return elem + '';
    }
    return elem.tagName.toLowerCase() + (elem.id && ("#" + elem.id));
  };

  var BDTLogger = {

    data: {
      'event': [],
      'view': [],
      'instance': [],
      'sync': []
    },

    log: function(type, object, details) {
      this.data[type].push({
        t: Date.now(),
        c1: (type === 'event') || (type === 'sync')
            ? prettyInstanceName(object)
            : object,
        c2: type === 'view'
            ? prettyElementName(details)
            : details
      });
    },

    getData: function(type, fromIndex) {
      if (!fromIndex) return this.data[type];
      return this.data[type].slice(fromIndex);
    }

  };

  window.Backbone.debug.logger = BDTLogger;

})();
<commit_msg>check tagName<commit_after>// Load this file immediately after backbone.debug.js

(function() {

  var instanceType = function(object) {
    if (object instanceof Backbone.Model) return 'Model';
    if (object instanceof Backbone.Collection) return 'Collection';
    if (object instanceof Backbone.View) return 'View';
    if (object instanceof Backbone.Router) return 'Router';
    return '';
  };

  var prettyInstanceName = function(object) {
    var name;
    name = object.constructor.name || instanceType(object);
    if (object.cid) {
      name = "" + name + ":" + object.cid;
    }
    return name;
  };

  var prettyElementName = function(elem) {
    if (!elem || !elem.tagName) {
      console.warn('[BDT Warning] Incorrect view.el value');
      return elem + '';
    }
    return elem.tagName.toLowerCase() + (elem.id && ("#" + elem.id));
  };

  var BDTLogger = {

    data: {
      'event': [],
      'view': [],
      'instance': [],
      'sync': []
    },

    log: function(type, object, details) {
      this.data[type].push({
        t: Date.now(),
        c1: (type === 'event') || (type === 'sync')
            ? prettyInstanceName(object)
            : object,
        c2: type === 'view'
            ? prettyElementName(details)
            : details
      });
    },

    getData: function(type, fromIndex) {
      if (!fromIndex) return this.data[type];
      return this.data[type].slice(fromIndex);
    }

  };

  window.Backbone.debug.logger = BDTLogger;

})();
<|endoftext|>


<commit_before>var LocationManager = {
    getCountry: function(callback) {
        jQuery.getJSON('http://freegeoip.net/json/', function(location) {
            callback(location.country_code);
        });
    }
};

function getMsg(key) {
    switch (countryCode) {
        case 'KR':
            return KR[key];
        default:
            return EN[key];
    }
}

// Notify message translations
var KR = {
    added: '추가되었습니다',
    alreadyOnPlaylist: '이미 플레이리스트에 있습니다',
    shared: '이 URL을 공유해보세요! \n',
    loaded: '리스트를 불러왔습니다',
    cleared: '리스트가 삭제되었습니다',
    invalidKey: 'Key를 찾을 수 없습니다',
    invalidUrl: '지원하지 않는 형식의 url 입니다',
    cannotBackNotOnPlaylist: '리스트에서 재생중이 아닙니다',
    cannotBack: '첫번째 음악입니다',
    cannotForthNotOnPlyalist: '리스트에서 재생중이 아닙니다.',
    cannotForth: '마지막 음악입니다',
    inSharedPlaylist: '당신은 공유된 플레이리스트로 접속했습니다.\n'
    + '이 플레이리스트는 당신의 플레이리스트에 영향을 끼치지 않습니다.\n'
    + '플레이리스트를 만드시려면 ' + fullHost + ' 로 접속해주세요',
    notPlayable: 'Soundcloud의 문제로 현재 재생이 불가능한 곡입니다. : ',
    cannotShare: '리스트가 비어있어서 공유할 수 없습니다.'
};

var EN = {
    added: 'Music added',
    alreadyOnPlaylist: 'Already on playlist',
    shared: 'Share this URL to your friends! \n',
    loaded: 'Playlist loaded!',
    cleared: 'Playlist cleared!',
    invalidKey: 'Invalid key!',
    invalidUrl: 'URL not supported!',
    cannotBackNotOnPlaylist: 'Not on playlist!',
    cannotBack: 'First music on playlist',
    cannotForthNotOnPlaylist: 'Not on playlist!',
    cannotForth: 'Last music on playlist',
    inSharedPlaylist: 'You are on shared playlist. \n'
    + 'All changes in this playlist will not affect yours.\n'
    + 'If you want to make your own playlist, access to ' + fullHost,
    notPlayable: 'This track is currently unavailable '
    + 'because of trouble in soundcloud : ',
    cannotShare: 'You cannot share an empty playlist'
};
<commit_msg>removed unused notify messages<commit_after>var LocationManager = {
    getCountry: function(callback) {
        jQuery.getJSON('http://freegeoip.net/json/', function(location) {
            callback(location.country_code);
        });
    }
};

function getMsg(key) {
    switch (countryCode) {
        case 'KR':
            return KR[key];
        default:
            return EN[key];
    }
}

// Notify message translations
var KR = {
    added: '추가되었습니다',
    alreadyOnPlaylist: '이미 플레이리스트에 있습니다',
    shared: '이 URL을 공유해보세요! \n',
    loaded: '리스트를 불러왔습니다',
    cleared: '리스트가 삭제되었습니다',
    invalidUrl: '지원하지 않는 형식의 url 입니다',
    inSharedPlaylist: '당신은 공유된 플레이리스트로 접속했습니다.\n'
    + '이 플레이리스트는 당신의 플레이리스트에 영향을 끼치지 않습니다.\n'
    + '플레이리스트를 만드시려면 ' + fullHost + ' 로 접속해주세요',
    notPlayable: 'Soundcloud의 문제로 현재 재생이 불가능한 곡입니다. : ',
    cannotShare: '리스트가 비어있어서 공유할 수 없습니다.'
};

var EN = {
    added: 'Music added',
    alreadyOnPlaylist: 'Already on playlist',
    shared: 'Share this URL to your friends! \n',
    loaded: 'Playlist loaded!',
    cleared: 'Playlist cleared!',
    invalidUrl: 'URL not supported!',
    inSharedPlaylist: 'You are on shared playlist. \n'
    + 'All changes in this playlist will not affect yours.\n'
    + 'If you want to make your own playlist, access to ' + fullHost,
    notPlayable: 'This track is currently unavailable '
    + 'because of trouble in soundcloud : ',
    cannotShare: 'You cannot share an empty playlist'
};
<|endoftext|>