<commit_before>/*
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Displays species tree based on the combined lineages from all xrefs.
// Based on http://mbostock.github.io/d3/talk/20111018/tree.html

d3SpeciesTree = function(data, upi, selector){

  var levelWidth = [1],
      edgeLength = 150,
      duration = 500,
      depth = [],
      maxLabelLength = 20,
      m = {
        'top': 20,
        'right': 40,
        'bottom': 20,
        'left': 40
      },
      i = 0;

  childCount(0, data);

  var w = (levelWidth.length - 1) * edgeLength + textWidth(depth[depth.length-1]) + m.right,
      h = d3.max(levelWidth) * 20;

  var tree = d3.layout.tree()
      .size([h, w]);

  var diagonal = d3.svg.diagonal()
      .projection(function(d) { return [d.y, d.x]; });

  var vis = d3.select(selector).append("svg:svg")
      .attr("width", w + m.left + m.right)
      .attr("height", h + m.top + m.bottom)
    .append("svg:g")
      .attr("transform", "translate(" + m.top + "," + m.bottom + ")");

  (function(){
    data.x0 = h / 2;
    data.y0 = w;

    function toggleAll(d) {
      if (d.children) {
        d.children.forEach(toggleAll);
        toggle(d);
      }
    }

    // Initialize the display to show the nodes.
    toggle(data.children);
    toggle(data);
    update(data);
    toggle(data);
    update(data);

  })();

  function update(source) {
    // Compute the new tree layout.
    var nodes = tree.nodes(data).reverse();

    // Normalize for fixed-depth.
    nodes.forEach(function(d) { d.y = w - (d.depth * edgeLength); });

    // Update the nodes
    var node = vis.selectAll("g.node")
        .data(nodes, function(d) { return d.id || (d.id = ++i); });

    // Enter any new nodes at the parent's previous position.
    var nodeEnter = node.enter().append("svg:g")
        .attr("class", "node")
        .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
        .on("click", function(d) { toggle(d); update(d); });

    nodeEnter.append("svg:circle")
        .attr("r", 1e-6)
        .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

    nodeEnter.filter(function(d){return d.hasOwnProperty('taxid');})
      .append("a")
        .attr("xlink:href", function (d) { return "/rna/" + upi + "/" + d.taxid; })
      .append("text")
        .attr("x", function(d) { return d.children || d._children ? 10 : -10; })
        .attr("dy", ".35em")
        .attr("class", "species-node")
        .attr("text-anchor", "end")
        .style("fill", "steelblue")
        .text(function(d){return d.name;});

    nodeEnter.filter(function(d){return !d.hasOwnProperty('taxid');}).append("svg:text")
        .attr("x", function(d) { return d.children || d._children ? 10 : -10; })
        .attr("dy", ".35em")
        .attr("text-anchor", function(d) { return d.children || d._children ? "start" : "end"; })
        .text(function(d) { return getNodeName(d); })
        .style("fill-opacity", 1e-6);

    nodeEnter.append("svg:title")
      .text(function(d) { return getHoverText(d) });

    // Transition nodes to their new position.
    var nodeUpdate = node.transition()
        .duration(duration)
        .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

    nodeUpdate.select("circle")
        .attr("r", 4.5)
        .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

    nodeUpdate.select("text")
        .style("fill-opacity", 1);

    // Transition exiting nodes to the parent's new position.
    var nodeExit = node.exit().transition()
        .duration(duration)
        .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
        .remove();

    nodeExit.select("circle")
        .attr("r", 1e-6);

    nodeExit.select("text")
        .style("fill-opacity", 1e-6);

    // Update the links
    var link = vis.selectAll("path.link")
        .data(tree.links(nodes), function(d) { return d.target.id; });

    // Enter any new links at the parent's previous position.
    link.enter().insert("svg:path", "g")
        .attr("class", "link")
        .attr("d", function(d) {
          var o = {x: source.x0, y: source.y0};
          return diagonal({source: o, target: o});
        })
      .transition()
        .duration(duration)
        .attr("d", diagonal);

    // Transition links to their new position.
    link.transition()
        .duration(duration)
        .attr("d", diagonal);

    // Transition exiting nodes to the parent's new position.
    link.exit().transition()
        .duration(duration)
        .attr("d", function(d) {
          var o = {x: source.x, y: source.y};
          return diagonal({source: o, target: o});
        })
        .remove();

    // Stash the old positions for transition.
    nodes.forEach(function(d) {
      d.x0 = d.x;
      d.y0 = d.y;
    });

  }

  function childCount(level, n) {
    if(n.children && n.children.length > 0) {
      if(levelWidth.length <= level + 1) levelWidth.push(0);

      levelWidth[level+1] += n.children.length;

      n.children.forEach(function(d) {
        childCount(level + 1, d);
      });
    } else {
      if (depth[level]) {
        if (n.name.length > depth[level].length) {
          depth[level] = n.name;
        }
      } else {
        depth[level] = n.name;
      }
    }
  }

  // Toggle children.
  function toggle(d) {
    if (d.children) {
      d._children = d.children;
      d.children = null;
    } else {
      d.children = d._children;
      d._children = null;
    }
  }

  function getHoverText(node) {
    var hoverText = '';
    if (node.size) {
      hoverText += [node.size, ' cross-reference', node.size > 1 ? 's' : ''].join('');
    } else if (node.name.length > maxLabelLength) {
      hoverText = node.name;
    }
    return hoverText;
  }

  function getNodeName(node) {
    var nodeName;
    // truncate long taxon names
    if (node.name.length > maxLabelLength) {
      nodeName = node.name.substr(0,maxLabelLength) + '...';
    } else {
      nodeName = node.name;
    }
    return nodeName;
  }

  // measure the width of some text by creating a fake hidden element and
  // getting its width
  function textWidth(text) {
      var fakeEl = $('').hide().appendTo(document.body);
      fakeEl.text(text).css('font-weight', 'bold').css('font-size', '11px');
      return fakeEl.width();
  };

};
<commit_msg>Fix taxonomic tree overflow<commit_after>/*
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Displays species tree based on the combined lineages from all xrefs.
// Based on http://mbostock.github.io/d3/talk/20111018/tree.html

d3SpeciesTree = function(data, upi, selector){

  var levelWidth = [1],
      edgeLength = 150,
      duration = 500,
      depth = [],
      maxLabelLength = 20,
      m = {
        'top': 20,
        'right': 40,
        'bottom': 20,
        'left': 40
      },
      i = 0;

  childCount(0, data);

  var w = (levelWidth.length - 1) * edgeLength + textWidth(depth[depth.length-1]) + m.right,
      h = d3.max(levelWidth) * 20;

  var tree = d3.layout.tree()
      .size([h, w]);

  var diagonal = d3.svg.diagonal()
      .projection(function(d) { return [d.y, d.x]; });

  var vis = d3.select(selector).append("svg:svg")
      .style("width", w + m.left + m.right)
      .attr("width", w + m.left + m.right)
      .attr("height", h + m.top + m.bottom)
    .append("svg:g")
      .attr("transform", "translate(" + m.top + "," + m.bottom + ")");

  (function(){
    data.x0 = h / 2;
    data.y0 = w;

    function toggleAll(d) {
      if (d.children) {
        d.children.forEach(toggleAll);
        toggle(d);
      }
    }

    // Initialize the display to show the nodes.
    toggle(data.children);
    toggle(data);
    update(data);
    toggle(data);
    update(data);

  })();

  function update(source) {
    // Compute the new tree layout.
    var nodes = tree.nodes(data).reverse();

    // Normalize for fixed-depth.
    nodes.forEach(function(d) { d.y = w - (d.depth * edgeLength); });

    // Update the nodes
    var node = vis.selectAll("g.node")
        .data(nodes, function(d) { return d.id || (d.id = ++i); });

    // Enter any new nodes at the parent's previous position.
    var nodeEnter = node.enter().append("svg:g")
        .attr("class", "node")
        .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
        .on("click", function(d) { toggle(d); update(d); });

    nodeEnter.append("svg:circle")
        .attr("r", 1e-6)
        .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

    nodeEnter.filter(function(d){return d.hasOwnProperty('taxid');})
      .append("a")
        .attr("xlink:href", function (d) { return "/rna/" + upi + "/" + d.taxid; })
      .append("text")
        .attr("x", function(d) { return d.children || d._children ? 10 : -10; })
        .attr("dy", ".35em")
        .attr("class", "species-node")
        .attr("text-anchor", "end")
        .style("fill", "steelblue")
        .text(function(d){return d.name;});

    nodeEnter.filter(function(d){return !d.hasOwnProperty('taxid');}).append("svg:text")
        .attr("x", function(d) { return d.children || d._children ? 10 : -10; })
        .attr("dy", ".35em")
        .attr("text-anchor", function(d) { return d.children || d._children ? "start" : "end"; })
        .text(function(d) { return getNodeName(d); })
        .style("fill-opacity", 1e-6);

    nodeEnter.append("svg:title")
      .text(function(d) { return getHoverText(d) });

    // Transition nodes to their new position.
    var nodeUpdate = node.transition()
        .duration(duration)
        .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

    nodeUpdate.select("circle")
        .attr("r", 4.5)
        .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

    nodeUpdate.select("text")
        .style("fill-opacity", 1);

    // Transition exiting nodes to the parent's new position.
    var nodeExit = node.exit().transition()
        .duration(duration)
        .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
        .remove();

    nodeExit.select("circle")
        .attr("r", 1e-6);

    nodeExit.select("text")
        .style("fill-opacity", 1e-6);

    // Update the links
    var link = vis.selectAll("path.link")
        .data(tree.links(nodes), function(d) { return d.target.id; });

    // Enter any new links at the parent's previous position.
    link.enter().insert("svg:path", "g")
        .attr("class", "link")
        .attr("d", function(d) {
          var o = {x: source.x0, y: source.y0};
          return diagonal({source: o, target: o});
        })
      .transition()
        .duration(duration)
        .attr("d", diagonal);

    // Transition links to their new position.
    link.transition()
        .duration(duration)
        .attr("d", diagonal);

    // Transition exiting nodes to the parent's new position.
    link.exit().transition()
        .duration(duration)
        .attr("d", function(d) {
          var o = {x: source.x, y: source.y};
          return diagonal({source: o, target: o});
        })
        .remove();

    // Stash the old positions for transition.
    nodes.forEach(function(d) {
      d.x0 = d.x;
      d.y0 = d.y;
    });

  }

  function childCount(level, n) {
    if(n.children && n.children.length > 0) {
      if(levelWidth.length <= level + 1) levelWidth.push(0);

      levelWidth[level+1] += n.children.length;

      n.children.forEach(function(d) {
        childCount(level + 1, d);
      });
    } else {
      if (depth[level]) {
        if (n.name.length > depth[level].length) {
          depth[level] = n.name;
        }
      } else {
        depth[level] = n.name;
      }
    }
  }

  // Toggle children.
  function toggle(d) {
    if (d.children) {
      d._children = d.children;
      d.children = null;
    } else {
      d.children = d._children;
      d._children = null;
    }
  }

  function getHoverText(node) {
    var hoverText = '';
    if (node.size) {
      hoverText += [node.size, ' cross-reference', node.size > 1 ? 's' : ''].join('');
    } else if (node.name.length > maxLabelLength) {
      hoverText = node.name;
    }
    return hoverText;
  }

  function getNodeName(node) {
    var nodeName;
    // truncate long taxon names
    if (node.name.length > maxLabelLength) {
      nodeName = node.name.substr(0,maxLabelLength) + '...';
    } else {
      nodeName = node.name;
    }
    return nodeName;
  }

  // measure the width of some text by creating a fake hidden element and
  // getting its width
  function textWidth(text) {
      var fakeEl = $('').hide().appendTo(document.body);
      fakeEl.text(text).css('font-weight', 'bold').css('font-size', '11px');
      return fakeEl.width();
  };

};
<|endoftext|>


<commit_before>/**
 * Created by Anirudha on 15/07/17.
 */

exports.sampleFunction = function() {
};

exports.cities = function() {
    return [
        {
            'cityId': 1,
            'cityCode': 'blr',
            'cityName': 'Bangalore',
            'cityPreName': '',
            'cityPostName': 'Karnataka',
            'cityLogo': 'http://i.imgur.com/TzE4rNy.jpg',
            'isActive': true
        },
        {
            'cityId': 2,
            'cityCode': 'ncr',
            'cityName': 'Delhi',
            'cityPreName': 'New',
            'cityPostName': '',
            'cityLogo': 'http://i.imgur.com/bA3g5OH.jpg',
            'isActive': true
        },
        {
            'cityId': 3,
            'cityCode': 'hyd',
            'cityName': 'Hyderabad',
            'cityPreName': '',
            'cityPostName': '',
            'cityLogo': 'http://i.imgur.com/WzuEXXY.jpg',
            'isActive': true
        },
        {
            'cityId': 4,
            'cityCode': 'ahm',
            'cityName': 'Ahmedabad',
            'cityPreName': '',
            'cityPostName': '',
            'cityLogo': 'http://i.imgur.com/YTtVoCf.jpg',
            'isActive': false
        },
        {
            'cityId': 5,
            'cityCode': 'mum',
            'cityName': 'Mumbai',
            'cityPreName': '',
            'cityPostName': '',
            'cityLogo': 'http://i.imgur.com/7rVXgi4.jpg',
            'isActive': true
        }
    ];
};

exports.rowClasses = function(key) {
    var classData = {
        0: 'fadeInLeft',
        1: 'zoomIn',
        2: 'fadeInRight'
    };
    return classData[key];
};

exports.socialAccounts = function(socialKey) {
    var socialAccountValues = {
        'website': {
            'iconClass': 'fa-link',
            'baseUrl': ''
        },
        'facebook': {
            'iconClass': 'fa-facebook',
            'baseUrl': 'https://facebook.com/'
        },
        'twitter': {
            'iconClass': 'fa-twitter',
            'baseUrl': 'https://twitter.com/'
        },
        'linkedin': {
            'iconClass': 'fa-linkedin',
            'baseUrl': 'https://www.linkedin.com/'
        },
        'github': {
            'iconClass': 'fa-github',
            'baseUrl': 'https://github.com/'
        }
    };
    return socialAccountValues[socialKey];
};

exports.teamMembers = function() {
    return [
        {
            'memberId': 1,
            'memberHandle': 'akshay',
            'preName': '',
            'name': 'Akshay',
            'postName': 'Aggarwal',
            'picture': 'http://i.imgur.com/6kFWdvQ.jpg',
            'detail': 'Startup, Technology and community building enthusiast. Fellow at DraperU.',
            'socialHandles': {
                'twitter': 'https://twitter.com/howdy_akshay',
                'facebook': 'https://www.facebook.com/akshay.aggarwal.10',
                'linkedin': 'https://www.linkedin.com/in/akshay-aggarwal'
            },
            'isActive': true
        },
        {
            'memberId': 2,
            'memberHandle': 'anistark',
            'preName': 'Kumar',
            'name': 'Anirudha',
            'postName': '',
            'picture': 'http://i.imgur.com/b7vjK2N.jpg',
            'detail': 'Tech Evangelist, open source contributor and mentor.',
            'socialHandles': {
                'twitter': 'https://twitter.com/kranirudha',
                'github': 'https://github.com/anistark',
                'linkedin': 'https://www.linkedin.com/in/kranirudha'
            },
            'isActive': true
        },
        {
            'memberId': 3,
            'memberHandle': 'karthika',
            'preName': '',
            'name': 'Karthika',
            'postName': 'Sivakumar',
            'picture': 'http://i.imgur.com/MEZR12i.jpg',
            'detail': 'Community Manager at Thoughfactory. Excited about the future of Blockchain.',
            'socialHandles': {
                'facebook': 'https://facebook.com/karthikasiv'
            },
            'isActive': true
        },
        {
            'memberId': 4,
            'memberHandle': 'advaith',
            'preName': '',
            'name': 'Advaith',
            'postName': 'Mohan',
            'picture': 'http://i.imgur.com/qdG7ZQB.jpg',
            'detail': 'CoFounder @Wagr. Dedicated to a better future for humanity.',
            'socialHandles': {
                'twitter': 'https://twitter.com/advaithmohan90',
                'facebook': 'https://facebook.com/advaithm',
                'linkedin': 'https://www.linkedin.com/in/advaith-mohan-90505047'
            },
            'isActive': true
        },
        {
            'memberId': 5,
            'memberHandle': 'manav',
            'preName': '',
            'name': 'Manav',
            'postName': 'Ailawadi',
            'picture': 'http://i.imgur.com/0pQGSpT.jpg',
            'detail': 'Entrepreneur',
            'socialHandles': {
                'facebook': 'https://facebook.com/manav.ailawadi'
            },
            'isActive': true
        },
        {
            'memberId': 6,
            'memberHandle': 'kashyap',
            'preName': '',
            'name': 'Kashyap',
            'postName': 'Kompella',
            'picture': 'http://i.imgur.com/Il3eqP6.jpg',
            'detail': 'Founder at fRndzZy. Fellow at DraperU.',
            'socialHandles': {
                'facebook': 'https://twitter.com/kashyapkomp',
                'linkedin': 'https://www.linkedin.com/in/kashyapk'
            },
            'isActive': true
        }
    ]
};

exports.events = function () {
    return [
        {
            'eventId': 1,
            'eventSlug': 'blr_intro',
            'name': 'Blockchain beyond Bitcoin',
            'detail': '',
            'date': '2017-04-01',
            'cityCode': 'blr',
            'location': 'Thought Factory Social, Diamond District, Tower C, 2nd Floor, 560071, H A L Old Airport Rd, ISRO Colony, Domlur, Bangalore',
            'startTime': '16:00:00',
            'endTime': '18:00:00',
            'partners': ['Thought Factory Social'],
            'sponsors': ['AWS'],
            'hostMemberHandles': ['akshay','anistark','advaith','karthika'],
            'eventLinks': {
                'meetup': 'https://www.meetup.com/blockchainindia/events/238764602'
            }
        },
        {
            'eventId': 2,
            'eventSlug': 'blr_intro_ncr',
            'name': 'Blockchain beyond Bitcoin - Delhi Chapter',
            'detail': '',
            'date': '2017-04-29',
            'cityCode': 'ncr',
            'location': '91 Springboard, E-43/1, Okhla Phase II, New Delhi',
            'startTime': '10:00:00',
            'endTime': '12:00:00',
            'partners': ['91 Springboard'],
            'sponsors': [],
            'hostMemberHandles': ['akshay','manav'],
            'eventLinks': {
                'meetup': 'https://www.meetup.com/blockchainindia/events/239157507'
            }
        },
        {
            'eventId': 3,
            'eventSlug': '',
            'name': '',
            'detail': '',
            'date': '',
            'cityCode': '',
            'location': '',
            'startTime': '',
            'endTime': '',
            'partners': [''],
            'sponsors': [],
            'hostMemberHandles': [],
            'eventLinks': {
                'meetup': '',
                'facebook': ''
            }
        }
    ]
};

exports.partners = function() {
    return [
        {
            'partnerId': 1,
            'partnerSlug': 'tfs',
            'partnerName': 'Thought Factory Social',
            'partnerLogo': 'http://i.imgur.com/yqVKOCJ.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 2,
            'partnerSlug': 'aws',
            'partnerName': 'AWS',
            'partnerLogo': 'http://i.imgur.com/RTd44cg.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 3,
            'partnerSlug': '91springboard',
            'partnerName': '91Springboard',
            'partnerLogo': 'http://i.imgur.com/UjWUgyR.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 4,
            'partnerSlug': 'startupdelhi',
            'partnerName': 'Startup Delhi',
            'partnerLogo': 'http://i.imgur.com/xi4BZ5B.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 5,
            'partnerSlug': 'thub',
            'partnerName': 'THub',
            'partnerLogo': 'http://i.imgur.com/wUDgPKR.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 6,
            'partnerSlug': 'tlabs',
            'partnerName': 'T-Labs',
            'partnerLogo': 'http://i.imgur.com/2tPVxmS.jpg',
            'isActive': false,
            'partnerType': 'general'
        },
        {
            'partnerId': 7,
            'partnerSlug': 'onecoworks',
            'partnerName': 'One Co Works',
            'partnerLogo': 'http://i.imgur.com/n2SnVn4.jpg',
            'isActive': false,
            'partnerType': 'general'
        },
        {
            'partnerId': 8,
            'partnerSlug': 'collabhouse',
            'partnerName': 'Collab House',
            'partnerLogo': 'http://i.imgur.com/PZx5aHx.jpg',
            'isActive': false,
            'partnerType': 'general'
        }
    ];
};

exports.mentors = function() {
    return [
        {
            'mentorId': 1,
            'mentorHandle': '',
            'preName': '',
            'name': '',
            'postName': '',
            'picture': '',
            'detail': '',
            'socialHandles': {
                'twitter': '',
                'linkedin': ''
            },
            'isActive': true
        }
    ]
};

exports.talks = function() {
    return [
        {
            'talkId': 1,
            'talkTitle': 'Dive into Blockchain',
            'speakerName': 'Kumar Anirudha',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'http://anistark.github.io/talks/decentralising-with-ethereum',
            'isActive': true
        },
        {
            'talkId': 2,
            'talkTitle': 'Intial Coin Offering',
            'speakerName': 'Akshay Agarwal',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'https://drive.google.com/file/d/0B4pGqvGd5e8ibXBnd2lvQWVlejQ/view?usp=sharing',
            'isActive': true
        },
        {
            'talkId': 3,
            'talkTitle': 'The Basics Of Ethereum',
            'speakerName': 'Advaith Mohan',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'http://slides.com/blockchainedindia/ethereumbasics/fullscreen#/',
            'isActive': true
        },
        {
            'talkId': 4,
            'talkTitle': 'Decentralising with Ethereum',
            'speakerName': 'Kumar Anirudha',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'http://anistark.github.io/talks/decentralising-with-ethereum',
            'isActive': true
        },
        {
            'talkId': 5,
            'talkTitle': 'Ethereum Smart Contract',
            'speakerName': 'Vinit Agrawal',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'https://drive.google.com/file/d/0B4pGqvGd5e8iMG1sdy1YSU9IdkU/view?usp=sharing',
            'isActive': true
        },
        {
            'talkId': 6,
            'talkTitle': 'Introduction to Blockchain',
            'speakerName': 'Kiran Naik Danavath',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'https://drive.google.com/file/d/0B4pGqvGd5e8iTTZ1VXBXRWdXRms/view?usp=sharing',
            'isActive': true
        },
        {
            'talkId': 7,
            'talkTitle': 'Unravel the Mystery - Blockchain',
            'speakerName': 'Vikas Singh',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'https://drive.google.com/file/d/0B4pGqvGd5e8ic0Z5azN1bnJfWDA/view?usp=sharing',
            'isActive': true
        }
    ]
};
<commit_msg>added david's talk<commit_after>/**
 * Created by Anirudha on 15/07/17.
 */

exports.sampleFunction = function() {
};

exports.cities = function() {
    return [
        {
            'cityId': 1,
            'cityCode': 'blr',
            'cityName': 'Bangalore',
            'cityPreName': '',
            'cityPostName': 'Karnataka',
            'cityLogo': 'http://i.imgur.com/TzE4rNy.jpg',
            'isActive': true
        },
        {
            'cityId': 2,
            'cityCode': 'ncr',
            'cityName': 'Delhi',
            'cityPreName': 'New',
            'cityPostName': '',
            'cityLogo': 'http://i.imgur.com/bA3g5OH.jpg',
            'isActive': true
        },
        {
            'cityId': 3,
            'cityCode': 'hyd',
            'cityName': 'Hyderabad',
            'cityPreName': '',
            'cityPostName': '',
            'cityLogo': 'http://i.imgur.com/WzuEXXY.jpg',
            'isActive': true
        },
        {
            'cityId': 4,
            'cityCode': 'ahm',
            'cityName': 'Ahmedabad',
            'cityPreName': '',
            'cityPostName': '',
            'cityLogo': 'http://i.imgur.com/YTtVoCf.jpg',
            'isActive': false
        },
        {
            'cityId': 5,
            'cityCode': 'mum',
            'cityName': 'Mumbai',
            'cityPreName': '',
            'cityPostName': '',
            'cityLogo': 'http://i.imgur.com/7rVXgi4.jpg',
            'isActive': true
        }
    ];
};

exports.rowClasses = function(key) {
    var classData = {
        0: 'fadeInLeft',
        1: 'zoomIn',
        2: 'fadeInRight'
    };
    return classData[key];
};

exports.socialAccounts = function(socialKey) {
    var socialAccountValues = {
        'website': {
            'iconClass': 'fa-link',
            'baseUrl': ''
        },
        'facebook': {
            'iconClass': 'fa-facebook',
            'baseUrl': 'https://facebook.com/'
        },
        'twitter': {
            'iconClass': 'fa-twitter',
            'baseUrl': 'https://twitter.com/'
        },
        'linkedin': {
            'iconClass': 'fa-linkedin',
            'baseUrl': 'https://www.linkedin.com/'
        },
        'github': {
            'iconClass': 'fa-github',
            'baseUrl': 'https://github.com/'
        }
    };
    return socialAccountValues[socialKey];
};

exports.teamMembers = function() {
    return [
        {
            'memberId': 1,
            'memberHandle': 'akshay',
            'preName': '',
            'name': 'Akshay',
            'postName': 'Aggarwal',
            'picture': 'http://i.imgur.com/6kFWdvQ.jpg',
            'detail': 'Startup, Technology and community building enthusiast. Fellow at DraperU.',
            'socialHandles': {
                'twitter': 'https://twitter.com/howdy_akshay',
                'facebook': 'https://www.facebook.com/akshay.aggarwal.10',
                'linkedin': 'https://www.linkedin.com/in/akshay-aggarwal'
            },
            'isActive': true
        },
        {
            'memberId': 2,
            'memberHandle': 'anistark',
            'preName': 'Kumar',
            'name': 'Anirudha',
            'postName': '',
            'picture': 'http://i.imgur.com/b7vjK2N.jpg',
            'detail': 'Tech Evangelist, open source contributor and mentor.',
            'socialHandles': {
                'twitter': 'https://twitter.com/kranirudha',
                'github': 'https://github.com/anistark',
                'linkedin': 'https://www.linkedin.com/in/kranirudha'
            },
            'isActive': true
        },
        {
            'memberId': 3,
            'memberHandle': 'karthika',
            'preName': '',
            'name': 'Karthika',
            'postName': 'Sivakumar',
            'picture': 'http://i.imgur.com/MEZR12i.jpg',
            'detail': 'Community Manager at Thoughfactory. Excited about the future of Blockchain.',
            'socialHandles': {
                'facebook': 'https://facebook.com/karthikasiv'
            },
            'isActive': true
        },
        {
            'memberId': 4,
            'memberHandle': 'advaith',
            'preName': '',
            'name': 'Advaith',
            'postName': 'Mohan',
            'picture': 'http://i.imgur.com/qdG7ZQB.jpg',
            'detail': 'CoFounder @Wagr. Dedicated to a better future for humanity.',
            'socialHandles': {
                'twitter': 'https://twitter.com/advaithmohan90',
                'facebook': 'https://facebook.com/advaithm',
                'linkedin': 'https://www.linkedin.com/in/advaith-mohan-90505047'
            },
            'isActive': true
        },
        {
            'memberId': 5,
            'memberHandle': 'manav',
            'preName': '',
            'name': 'Manav',
            'postName': 'Ailawadi',
            'picture': 'http://i.imgur.com/0pQGSpT.jpg',
            'detail': 'Entrepreneur',
            'socialHandles': {
                'facebook': 'https://facebook.com/manav.ailawadi'
            },
            'isActive': true
        },
        {
            'memberId': 6,
            'memberHandle': 'kashyap',
            'preName': '',
            'name': 'Kashyap',
            'postName': 'Kompella',
            'picture': 'http://i.imgur.com/Il3eqP6.jpg',
            'detail': 'Founder at fRndzZy. Fellow at DraperU.',
            'socialHandles': {
                'facebook': 'https://twitter.com/kashyapkomp',
                'linkedin': 'https://www.linkedin.com/in/kashyapk'
            },
            'isActive': true
        }
    ]
};

exports.events = function () {
    return [
        {
            'eventId': 1,
            'eventSlug': 'blr_intro',
            'name': 'Blockchain beyond Bitcoin',
            'detail': '',
            'date': '2017-04-01',
            'cityCode': 'blr',
            'location': 'Thought Factory Social, Diamond District, Tower C, 2nd Floor, 560071, H A L Old Airport Rd, ISRO Colony, Domlur, Bangalore',
            'startTime': '16:00:00',
            'endTime': '18:00:00',
            'partners': ['Thought Factory Social'],
            'sponsors': ['AWS'],
            'hostMemberHandles': ['akshay','anistark','advaith','karthika'],
            'eventLinks': {
                'meetup': 'https://www.meetup.com/blockchainindia/events/238764602'
            }
        },
        {
            'eventId': 2,
            'eventSlug': 'blr_intro_ncr',
            'name': 'Blockchain beyond Bitcoin - Delhi Chapter',
            'detail': '',
            'date': '2017-04-29',
            'cityCode': 'ncr',
            'location': '91 Springboard, E-43/1, Okhla Phase II, New Delhi',
            'startTime': '10:00:00',
            'endTime': '12:00:00',
            'partners': ['91 Springboard'],
            'sponsors': [],
            'hostMemberHandles': ['akshay','manav'],
            'eventLinks': {
                'meetup': 'https://www.meetup.com/blockchainindia/events/239157507'
            }
        },
        {
            'eventId': 3,
            'eventSlug': '',
            'name': '',
            'detail': '',
            'date': '',
            'cityCode': '',
            'location': '',
            'startTime': '',
            'endTime': '',
            'partners': [''],
            'sponsors': [],
            'hostMemberHandles': [],
            'eventLinks': {
                'meetup': '',
                'facebook': ''
            }
        }
    ]
};

exports.partners = function() {
    return [
        {
            'partnerId': 1,
            'partnerSlug': 'tfs',
            'partnerName': 'Thought Factory Social',
            'partnerLogo': 'http://i.imgur.com/yqVKOCJ.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 2,
            'partnerSlug': 'aws',
            'partnerName': 'AWS',
            'partnerLogo': 'http://i.imgur.com/RTd44cg.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 3,
            'partnerSlug': '91springboard',
            'partnerName': '91Springboard',
            'partnerLogo': 'http://i.imgur.com/UjWUgyR.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 4,
            'partnerSlug': 'startupdelhi',
            'partnerName': 'Startup Delhi',
            'partnerLogo': 'http://i.imgur.com/xi4BZ5B.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 5,
            'partnerSlug': 'thub',
            'partnerName': 'THub',
            'partnerLogo': 'http://i.imgur.com/wUDgPKR.jpg',
            'isActive': true,
            'partnerType': 'general'
        },
        {
            'partnerId': 6,
            'partnerSlug': 'tlabs',
            'partnerName': 'T-Labs',
            'partnerLogo': 'http://i.imgur.com/2tPVxmS.jpg',
            'isActive': false,
            'partnerType': 'general'
        },
        {
            'partnerId': 7,
            'partnerSlug': 'onecoworks',
            'partnerName': 'One Co Works',
            'partnerLogo': 'http://i.imgur.com/n2SnVn4.jpg',
            'isActive': false,
            'partnerType': 'general'
        },
        {
            'partnerId': 8,
            'partnerSlug': 'collabhouse',
            'partnerName': 'Collab House',
            'partnerLogo': 'http://i.imgur.com/PZx5aHx.jpg',
            'isActive': false,
            'partnerType': 'general'
        }
    ];
};

exports.mentors = function() {
    return [
        {
            'mentorId': 1,
            'mentorHandle': '',
            'preName': '',
            'name': '',
            'postName': '',
            'picture': '',
            'detail': '',
            'socialHandles': {
                'twitter': '',
                'linkedin': ''
            },
            'isActive': true
        }
    ]
};

exports.talks = function() {
    return [
        {
            'talkId': 1,
            'talkTitle': 'Dive into Blockchain',
            'speakerName': 'Kumar Anirudha',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'http://anistark.github.io/talks/decentralising-with-ethereum',
            'isActive': true
        },
        {
            'talkId': 2,
            'talkTitle': 'Intial Coin Offering',
            'speakerName': 'Akshay Agarwal',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'https://drive.google.com/file/d/0B4pGqvGd5e8ibXBnd2lvQWVlejQ/view?usp=sharing',
            'isActive': true
        },
        {
            'talkId': 3,
            'talkTitle': 'The Basics Of Ethereum',
            'speakerName': 'Advaith Mohan',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'http://slides.com/blockchainedindia/ethereumbasics/fullscreen#/',
            'isActive': true
        },
        {
            'talkId': 4,
            'talkTitle': 'Decentralising with Ethereum',
            'speakerName': 'Kumar Anirudha',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'http://anistark.github.io/talks/decentralising-with-ethereum',
            'isActive': true
        },
        {
            'talkId': 5,
            'talkTitle': 'Ethereum Smart Contract',
            'speakerName': 'Vinit Agrawal',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'https://drive.google.com/file/d/0B4pGqvGd5e8iMG1sdy1YSU9IdkU/view?usp=sharing',
            'isActive': true
        },
        {
            'talkId': 6,
            'talkTitle': 'Introduction to Blockchain',
            'speakerName': 'Kiran Naik Danavath',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'https://drive.google.com/file/d/0B4pGqvGd5e8iTTZ1VXBXRWdXRms/view?usp=sharing',
            'isActive': true
        },
        {
            'talkId': 7,
            'talkTitle': 'Unravel the Mystery - Blockchain',
            'speakerName': 'Vikas Singh',
            'talkImg': 'http://i.imgur.com/kQx8HjP.png',
            'talkUrl': 'https://drive.google.com/file/d/0B4pGqvGd5e8ic0Z5azN1bnJfWDA/view?usp=sharing',
            'isActive': true
        },
        {
            'talkId': 8,
            'talkTitle': 'The Stellar Consensus Protocol',
            'speakerName': 'David Mazières',
            'talkImg': 'https://i.imgur.com/0shxy8s.png',
            'talkUrl': 'https://drive.google.com/file/d/0B4pGqvGd5e8ibk51SXBIVXUwcDQ/view?usp=sharing',
            'isActive': true
        }
    ]
};
<|endoftext|>


<commit_before>var db = require('./modelAdapters');
var util = require('../core/utilities');

//exports.createMessage({message: 'Excellant, it works!', x: 535, y: 325, z: 325, userToken: 'live'});
exports.createMessage = function(userData) {
  return db.insert('messages', {
    messageString: userData.message,
    image: util.saveImage(userData.image)
    }).then(function(messageSuccess) {
      return db.insert('marks', {
        x: userData.x,
        y: userData.y,
        z: userData.z,
        userToken: userData.userToken,
        messageId: messageSuccess.insertId
    }).then(function(markSuccess) {
      return {markSuccess: markSuccess, messageSuccess: messageSuccess};
    });
  });
};

//exports.createComment({messageId: 1, message: 'works'});
exports.createComment = function(userData) {
  return db.insert('comments',{
    messageId: userData.messageId,
    commentString: userData.message
  });
}

//exports.createUser('grgrdg');
exports.createUser = function(token) {
  return db.insert('users', {token: token});
};

//exports.createVote(3, 'grgrdg');
exports.createVote = function(messageId, token) {
  return db.insert('votes', {userToken: token, messageId: messageId});
};

//exports.retrieveMarks({x: 535, y: 325, z: 325}).then(callback(success));
exports.retrieveMarks = db.retrieveMarks;

//exports.retrieveScore(3).then(callback(success));
exports.retrieveScore = function(messageId, objectToFill) {
  return new Promise(function(resolve, reject) {
    db.where('messages', ['id', messageId])
      .then(function(success) {
        resolve(success[0].score);
      },
      function(err) {
        reject(err);
      });
  });
};

//exports.updateScore(3, 9001);
exports.updateScore = function(messageId, amount) {
  return db.update('messages', ['score', amount, 'id', messageId]);
};

//exports.retrieveVotes(10).then(function(success){console.log(success)});
exports.retrieveVotes = function(messageId) {
  return db.retrieveCount('votes', ['messageId', messageId]);
};

//exports.retrieveComments(10).then(function(success){console.log(success)});
exports.retrieveComments = function(messageId) {
  return db.where('comments', ['messageId', messageId]);
};

//delete(string tableName, [string key, string value]);
exports.deleteRow = db.deleteRow;

//deleteUser(string userToken)
exports.deleteUser = function(userToken) {
  return db.deleteRow('users', ['token', userToken]);
};

//deleteMessage(string messageId)
exports.deleteMessage = function(messageId) {
  return db.deleteRow('messages', ['id', messageId]);
}

//deleteMark(string markId)
exports.deleteMark = function(markId) {
  return db.deleteRow('marks', ['id', markId]);
}
<commit_msg>Implement deleteVote method in models<commit_after>var db = require('./modelAdapters');
var util = require('../core/utilities');

//exports.createMessage({message: 'Excellant, it works!', x: 535, y: 325, z: 325, userToken: 'live'});
exports.createMessage = function(userData) {
  return db.insert('messages', {
    messageString: userData.message,
    image: util.saveImage(userData.image)
    }).then(function(messageSuccess) {
      return db.insert('marks', {
        x: userData.x,
        y: userData.y,
        z: userData.z,
        userToken: userData.userToken,
        messageId: messageSuccess.insertId
    }).then(function(markSuccess) {
      return {markSuccess: markSuccess, messageSuccess: messageSuccess};
    });
  });
};

//exports.createComment({messageId: 1, message: 'works'});
exports.createComment = function(userData) {
  return db.insert('comments',{
    messageId: userData.messageId,
    commentString: userData.message
  });
}

//exports.createUser('grgrdg');
exports.createUser = function(token) {
  return db.insert('users', {token: token});
};

//exports.createVote(3, 'grgrdg');
exports.createVote = function(messageId, token) {
  return db.insert('votes', {userToken: token, messageId: messageId});
};

//exports.retrieveMarks({x: 535, y: 325, z: 325}).then(callback(success));
exports.retrieveMarks = db.retrieveMarks;

//exports.retrieveScore(3).then(callback(success));
exports.retrieveScore = function(messageId, objectToFill) {
  return new Promise(function(resolve, reject) {
    db.where('messages', ['id', messageId])
      .then(function(success) {
        resolve(success[0].score);
      },
      function(err) {
        reject(err);
      });
  });
};

//exports.updateScore(3, 9001);
exports.updateScore = function(messageId, amount) {
  return db.update('messages', ['score', amount, 'id', messageId]);
};

//exports.retrieveVotes(10).then(function(success){console.log(success)});
exports.retrieveVotes = function(messageId) {
  return db.retrieveCount('votes', ['messageId', messageId]);
};

//exports.retrieveComments(10).then(function(success){console.log(success)});
exports.retrieveComments = function(messageId) {
  return db.where('comments', ['messageId', messageId]);
};

//delete(string tableName, [string key, string value]);
exports.deleteRow = db.deleteRow;

//deleteUser(string userToken)
exports.deleteUser = function(userToken) {
  return db.deleteRow('users', ['token', userToken]);
};

//deleteMessage(string messageId)
exports.deleteMessage = function(messageId) {
  return db.deleteRow('messages', ['id', messageId]);
};

//deleteMark(string markId)
exports.deleteMark = function(markId) {
  return db.deleteRow('marks', ['id', markId]);
};

//deleteVote(string voteId)
exports.deleteVote = function(voteId) {
  return db.deleteRow('votes', ['id', voteId]);
};
<|endoftext|>


<commit_before>const { blue } = require("chalk");
const logger = require("morgan");
const webpack = require("webpack");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");
const devConfig = require("../../webpack.config.dev");

/**
 * inject debug settings to express app.
 */
module.exports.inject = (app, options = {}) =>
{
    console.log(blue("Current Environment: development"));

    // set logger.
    app.use(logger("dev"));

    // set webpack.
    const compiler = webpack(devConfig);
    const instance = webpackDevMiddleware(
        compiler,
        {
            stats:
            {
                chunks: false,
                colors: true
            },
            publicPath: devConfig.output.publicPath
        }
    );
    instance.waitUntilValid(() =>
    {
        // assets map setup.
        app.locals.map = require(options.assetsPath);
    });

    app.use(instance);
    app.use(webpackHotMiddleware(compiler));
};
<commit_msg>format<commit_after>const { blue } = require("chalk");
const logger = require("morgan");
const webpack = require("webpack");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");

const devConfig = require("../../webpack.config.dev");

/**
 * inject debug settings to express app.
 */
module.exports.inject = (app, options = {}) =>
{
    console.log(blue("Current environment: development\n"));

    // set logger.
    app.use(logger("dev"));

    // set webpack.
    const compiler = webpack(devConfig);
    const instance = webpackDevMiddleware(
        compiler,
        {
            stats:
                {
                    chunks: false,
                    colors: true
                },
            publicPath: devConfig.output.publicPath
        }
    );
    instance.waitUntilValid(() =>
    {
        // assets map setup.
        app.locals.map = require(options.assetsPath);
    });

    app.use(instance);
    app.use(webpackHotMiddleware(compiler));
};
<|endoftext|>


<commit_before>/*
 *   Copyright 2015
 */

/**
 * Changes the locale of the cube
 */
var ChangeLocale = Backbone.View.extend({

    initialize: function (args) {
        this.workspace = args.workspace;

        // Create a unique ID for use as the CSS selector
        this.id = _.uniqueId("changeLocale_");
        $(this.el).attr({ id: this.id });

        // Bind table rendering to query result event
        _.bindAll(this, "render", "show", "handleClick", "fetch_datasources");

        this.datasources = new Connections({}, { dialog: this });

        // Add change locale button to saiku toolbar
        this.add_button();
        this.workspace.toolbar.changeLocale = this.show;

        // Listen to adjust event and rerender
        this.workspace.bind('workspace:adjust', this.render);

        // Create locale screen
        this.localeOptionsScreen = $("
  " +
            "
" +
            "
         <button id='en_US' > English </button>
 " +
            "
   	    <button id='nl_BE' > Dutch </button>
 " +
            "
   	    <button id='fr_FR' > French </button>
" +
            "
" +
            "
 " +
            "
 Choose your language
")
        ;

        // attach event handler
        this.localeOptionsScreen.find('span').click(this.handleClick);

        //function for menu
        $("#nav ul ").css({display: "none"}); // Opera Fix
        $("#nav li").hover(function () {
            $(this).find('ul:first').css({visibility: "visible", display: "none"}).show(400);
        }, function () {
            $(this).find('ul:first').css({visibility: "hidden"});
        });

        // Append chart to workspace
        $(this.workspace.el).find('.workspace_results')
            .prepend($(this.el).hide())
            .prepend(this.localeOptionsScreen.hide());

    },

    add_button: function () {
        var $chart_button =
            $('')
                .css({  'background-image': "url('js/saiku/plugins/ChangeLocale/images/change_locale.png')",
                    'background-repeat': 'no-repeat',
                    'background-position': '7px 7px'
                });

        var $chart_li = $('

').append($chart_button);
        $(this.workspace.toolbar.el).find("ul").append($chart_li);
    },

    show: function (event, ui) {
        $(this.workspace.table.el).toggle();
        $(this.el).toggle();
        $(this.localeOptionsScreen).toggle();
        $(event.target).toggleClass('on');

        if ($(event.target).hasClass('on')) {
            this.render();
        } else {
            this.workspace.table.render({ data: this.workspace.query.result.lastresult() });
        }
    },

    fetch_datasources: function () {
        return true;
    },

    handleClick: function (event) {
        // Keep a reference to the main plugin object.
        var this_p = this;

        // get selected locale
        var newLocale = $(event.target).attr('id');

        // get current selected connection name (without URL data)
        selectedCube = $(".cubes option:selected").val();
        selectedConnectionName = selectedCube.substring(0, selectedCube.indexOf("/"));

        // Get all connections from back-end
        getUrl = Settings.REST_URL + "admin" + "/datasources";
        $.get(getUrl, function (data) {
            allConnections = data;
            // match
            selectedConnection = _.find(allConnections, function (connection) {
                return connection.connectionname == selectedConnectionName
            });

            selectedDataSource = new DataSource(selectedConnection);

            // change locale
            if (selectedConnection.advanced == null) {
                alert("Change the URL connection string to advanced");
            } else {
                referenceText = "locale=";
                start = selectedConnection.advanced.toLowerCase().indexOf(referenceText);
                start = start + referenceText.length;
                if (start == -1) {
                    alert("no locale defined in connection string of data source")
                }
                else {
                    end = selectedConnection.advanced.indexOf(";", start);
                }
                oldLocale = selectedConnection.advanced.substring(start, end);
                selectedDataSource.attributes.advanced = selectedConnection.advanced.replace(oldLocale, newLocale);
//                alert("selected connection : " + selectedConnection.advanced);
            }

            // post update
            selectedDataSource.save({}, {
                data: JSON.stringify(selectedConnection.attributes),
                contentType: "application/json",
                success: function () {
                    $(this_p.el).find('#feedback').html("");
                },
                error: function (data, xhr) {
                    $(this_p.el).find('#feedback').html("Save failed!
(" + xhr.responseText + ")");
                }
            });
            // refresh datasources
            // see onenote
        });
        return false;
    },

    render: function (chartOptions) {

    }
});

var DataSource = Backbone.Model.extend({
    url: "admin/datasources",
    refresh: function () {
        $.ajax({
            type: 'GET',
            url: Settings.REST_URL + "admin" + "/datasources/" + this.get("connectionname") + "/refresh"
        });
    }
});

/**
 * Start Plugin
 */
Saiku.events.bind('session:new', function (session) {

    function new_workspace(args) {
        // Add stats element
        if (typeof args.workspace.changeLocale == "undefined") {
            args.workspace.changeLocale = new ChangeLocale({ workspace: args.workspace });
        }
    };

    function clear_workspace(args) {
        if (typeof args.workspace.changeLocale != "undefined") {
            $(args.workspace.changeLocale.localeOptionsScreen).hide();
            $(args.workspace.changeLocale.el).parents().find('.workspace_results table').show();
            $(args.workspace.changeLocale.el).hide();
        }
    };

    // Attach stats to existing tabs
    for (var i = 0; i < Saiku.tabs._tabs.length; i++) {
        var tab = Saiku.tabs._tabs[i];
        new_workspace({
            workspace: tab.content
        });
    }
    ;

    // Attach stats to future tabs
    Saiku.session.bind("workspace:new", new_workspace);
    Saiku.session.bind("workspace:clear", clear_workspace);
});
<commit_msg>bugfix and refactoring changelocale plugin<commit_after>/*
 *   Copyright 2015
 */

/**
 * Changes the locale of the cube
 */
var ChangeLocale = Backbone.View.extend({

    initialize: function (args) {
        this.workspace = args.workspace;

        // Create a unique ID for use as the CSS selector
        this.id = _.uniqueId("changeLocale_");
        $(this.el).attr({ id: this.id });

        // Bind table rendering to query result event
        _.bindAll(this, "render", "show", "handleClick", "fetch_datasources");

        this.datasources = new Connections({}, { dialog: this });

        // Add change locale button to saiku toolbar
        this.add_button();
        this.workspace.toolbar.changeLocale = this.show;

        // Listen to adjust event and rerender
        this.workspace.bind('workspace:adjust', this.render);

        // Create locale screen
        this.localeOptionsScreen = $("
  " +
            "
" +
            "
         <button id='en_US' > English </button>
 " +
            "
   	    <button id='nl_BE' > Dutch </button>
 " +
            "
   	    <button id='fr_FR' > French </button>
" +
            "
" +
            "
 " +
            "
 Choose your language
")
        ;

        // attach event handler
        this.localeOptionsScreen.find('button').click(this.handleClick);

        //function for menu
        $("#nav ul ").css({display: "none"}); // Opera Fix
        $("#nav li").hover(function () {
            $(this).find('ul:first').css({visibility: "visible", display: "none"}).show(400);
        }, function () {
            $(this).find('ul:first').css({visibility: "hidden"});
        });

        // Append chart to workspace
        $(this.workspace.el).find('.workspace_results')
            .prepend($(this.el).hide())
            .prepend(this.localeOptionsScreen.hide());

    },

    add_button: function () {
        var $chart_button =
            $('')
                .css({  'background-image': "url('js/saiku/plugins/ChangeLocale/images/change_locale.png')",
                    'background-repeat': 'no-repeat',
                    'background-position': '7px 7px'
                });

        var $chart_li = $('

').append($chart_button);
        $(this.workspace.toolbar.el).find("ul").append($chart_li);
    },

    show: function (event, ui) {
        $(this.workspace.table.el).toggle();
        $(this.el).toggle();
        $(this.localeOptionsScreen).toggle();
        $(event.target).toggleClass('on');

        if ($(event.target).hasClass('on')) {
            this.render();
        } else {
            this.workspace.table.render({ data: this.workspace.query.result.lastresult() });
        }
    },

    fetch_datasources: function () {
        return true;
    },

    handleClick: function (event) {
        // Keep a reference to the main plugin object.
        var this_p = this;

        // get selected locale
        var newLocale = $(event.target).attr('id');

        // get current selected connection name (without URL data)
        selectedCube = $(".cubes option:selected").val();
        selectedConnectionName = selectedCube.substring(0, selectedCube.indexOf("/"));

        // Get all connections from back-end
        getUrl = Settings.REST_URL + "admin" + "/datasources";
        $.get(getUrl, function (data) {
            allConnections = data;
            // match
            selectedConnection = _.find(allConnections, function (connection) {
                return connection.connectionname == selectedConnectionName
            });

            selectedDataSource = new DataSource(selectedConnection);

            // change locale
            if (selectedConnection.advanced == null) {
                alert("Change the URL connection string to advanced");
            } else {
                referenceText = "locale=";
                start = selectedConnection.advanced.toLowerCase().indexOf(referenceText);
                start = start + referenceText.length;
                if (start == -1) {
                    alert("no locale defined in connection string of data source")
                }
                else {
                    end = selectedConnection.advanced.indexOf(";", start);
                    oldLocale = selectedConnection.advanced.substring(start, end);
                    selectedDataSource.set({"advanced": selectedConnection.advanced.replace(oldLocale, newLocale)});
                    // post update
                    this_p.saveDataSource(selectedDataSource);
                    // refresh datasources
                    Saiku.session.sessionworkspace.refresh()
                }
            }
        });
        return false;
    },

    saveDataSource: function (selectedDataSource) {
        selectedDataSource.save({}, {
                data: JSON.stringify(selectedDataSource.attributes),
                contentType: "application/json",
                success: function (model, respose, options) {
                    console.log("The model has been updated to the server");
                },
                error: function (model, xhr, options) {
                    console.log("Something went wrong while updating the model: " + xhr.responseText);
                }
            }
        );
    },

    render: function (chartOptions) {

    }
});

var DataSource = Backbone.Model.extend({
//    url: "admin/datasources",
    urlRoot: "admin/datasources",
    refresh: function () {
        $.ajax({
            type: 'GET',
            url: Settings.REST_URL + "admin" + "/datasources/" + this.get("connectionname") + "/refresh"
        });
    }
});

/**
 * Start Plugin
 */
Saiku.events.bind('session:new', function (session) {

    function new_workspace(args) {
        // Add stats element
        if (typeof args.workspace.changeLocale == "undefined") {
            args.workspace.changeLocale = new ChangeLocale({ workspace: args.workspace });
        }
    };

    function clear_workspace(args) {
        if (typeof args.workspace.changeLocale != "undefined") {
            $(args.workspace.changeLocale.localeOptionsScreen).hide();
            $(args.workspace.changeLocale.el).parents().find('.workspace_results table').show();
            $(args.workspace.changeLocale.el).hide();
        }
    };

    // Attach stats to existing tabs
    for (var i = 0; i < Saiku.tabs._tabs.length; i++) {
        var tab = Saiku.tabs._tabs[i];
        new_workspace({
            workspace: tab.content
        });
    }
    ;

    // Attach stats to future tabs
    Saiku.session.bind("workspace:new", new_workspace);
    Saiku.session.bind("workspace:clear", clear_workspace);
});
<|endoftext|>


<commit_before>import slugify from 'slugify';
import { trimToMaxLength } from './stringUtil';
import { notEmptyString } from './formValidators';
import { downloadViaFormPost } from './apiUtil';
import { downloadSvg } from '../components/util/svg';

export const DEFAULT_SOURCES = '';

export const DEFAULT_COLLECTION = 9139487;

export const DEFAULT_COLLECTION_OBJECT_ARRAY = [{ id: DEFAULT_COLLECTION, tags_id: DEFAULT_COLLECTION, label: 'U.S. Top News' }];

export const PICK_COLLECTION = 0;
export const PICK_SOURCE = 1;
export const PICK_COUNTRY = 2;
export const PICK_ADVANCED = 3;

export function generateQueryParamObject(query, skipEncoding) {
  return {
    label: skipEncoding ? query.label : encodeURIComponent(query.label),
    q: skipEncoding ? query.q : encodeURIComponent(query.q),
    color: skipEncoding ? query.color : encodeURIComponent(query.color),
    startDate: query.startDate,
    endDate: query.endDate,
    sources: query.sources && query.sources.length > 0 ? query.sources.map(s => (s.id ? s.id : s)) : [], // id field or the id itself
    collections: query.collections && query.collections.length > 0 ? query.collections.map(s => (s.id ? s.id : s)) : [],
  };
}

export function generateQueryParamString(queries) {
  const queriesForUrl = queries.map(generateQueryParamObject);
  return JSON.stringify(queriesForUrl);
}

export function decodeQueryParamString(queryString) {
  const queriesForUrl = JSON.parse(queryString).map(query => ({
    label: notEmptyString(query.label) ? decodeURIComponent(query.label) : '',
    q: notEmptyString(query.q) ? decodeURIComponent(query.q) : '*',
    color: notEmptyString(query.color) ? decodeURIComponent(query.color) : '',
    startDate: query.startDate,
    endDate: query.endDate,
    sources: query.sources, // de-aggregate media bucket into sources and collections
    collections: query.collections,
  }));
  return queriesForUrl;
}

function queryPropertyHasChanged(queries, nextQueries, propName) {
  const currentProps = queries.map(q => q[propName]).reduce((allProps, prop) => allProps + prop);
  const nextProps = nextQueries.map(q => q[propName]).reduce((allProps, prop) => allProps + prop);
  const propHasChanged = currentProps !== nextProps;
  return propHasChanged;
}

// call this from componentShouldUpdate to figure out if it should or not
export function queryChangedEnoughToUpdate(queries, nextQueries, results, nextResults) {
  // only re-render if results, any labels, or any colors have changed
  if (results.length) { // may have reset results so avoid test if results is empty
    const labelsHaveChanged = queryPropertyHasChanged(queries.slice(0, results.length), nextQueries.slice(0, results.length), 'label');
    const colorsHaveChanged = queryPropertyHasChanged(queries.slice(0, results.length), nextQueries.slice(0, results.length), 'color');
    return (
      ((labelsHaveChanged || colorsHaveChanged))
       || (results !== nextResults.results)
    );
  }
  return false; // if both results and queries are empty, don't update
}

// TODO: implement this logic from Dashboard
const MAX_QUERY_LABEL_LENGTH = 60;
export const autoMagicQueryLabel = query => decodeURIComponent(trimToMaxLength(query.q, MAX_QUERY_LABEL_LENGTH));

// This handles samples or user-generated queries for you.  To handle quotes and utf and such, we do this
// via a form submission (after trying lots of other options).
export function postToDownloadUrl(url, query, otherData) {
  // figure out if it is sample or user-created query
  let data = { index: query.index };
  if (parseInt(query.searchId, 10) >= 0) {
    data.sampleId = query.searchId;
  } else {
    data.q = JSON.stringify(generateQueryParamObject(query, true)); // don't encode the params because we're not putting them on the url
  }
  if (otherData) {
    data = { ...data, ...otherData };
  }
  downloadViaFormPost(url, data);
}

export const slugifiedQueryLabel = queryLabel => slugify(trimToMaxLength(queryLabel, 30));

export function downloadExplorerSvg(queryLabel, type, domIdOrElement) {
  const filename = `${slugifiedQueryLabel(queryLabel)}-${type}`;
  downloadSvg(filename, domIdOrElement);
}
<commit_msg>#929 get color encoded for all queries<commit_after>import slugify from 'slugify';
import { trimToMaxLength } from './stringUtil';
import { notEmptyString } from './formValidators';
import { downloadViaFormPost } from './apiUtil';
import { downloadSvg } from '../components/util/svg';

export const DEFAULT_SOURCES = '';

export const DEFAULT_COLLECTION = 9139487;

export const DEFAULT_COLLECTION_OBJECT_ARRAY = [{ id: DEFAULT_COLLECTION, tags_id: DEFAULT_COLLECTION, label: 'U.S. Top News' }];

export const PICK_COLLECTION = 0;
export const PICK_SOURCE = 1;
export const PICK_COUNTRY = 2;
export const PICK_ADVANCED = 3;

export function generateQueryParamObject(query) {
  const skipPerQuery = this;
  return {
    label: skipPerQuery ? query.label : encodeURIComponent(query.label),
    q: skipPerQuery ? query.q : encodeURIComponent(query.q),
    color: skipPerQuery ? query.color : encodeURIComponent(query.color),
    startDate: query.startDate,
    endDate: query.endDate,
    sources: query.sources && query.sources.length > 0 ? query.sources.map(s => (s.id ? s.id : s)) : [], // id field or the id itself
    collections: query.collections && query.collections.length > 0 ? query.collections.map(s => (s.id ? s.id : s)) : [],
  };
}

export function generateQueryParamString(queries) {
  const queriesForUrl = queries.map(generateQueryParamObject, false);
  return JSON.stringify(queriesForUrl);
}

export function decodeQueryParamString(queryString) {
  const queriesForUrl = JSON.parse(queryString).map(query => ({
    label: notEmptyString(query.label) ? decodeURIComponent(query.label) : '',
    q: notEmptyString(query.q) ? decodeURIComponent(query.q) : '*',
    color: notEmptyString(query.color) ? decodeURIComponent(query.color) : '',
    startDate: query.startDate,
    endDate: query.endDate,
    sources: query.sources, // de-aggregate media bucket into sources and collections
    collections: query.collections,
  }));
  return queriesForUrl;
}

function queryPropertyHasChanged(queries, nextQueries, propName) {
  const currentProps = queries.map(q => q[propName]).reduce((allProps, prop) => allProps + prop);
  const nextProps = nextQueries.map(q => q[propName]).reduce((allProps, prop) => allProps + prop);
  const propHasChanged = currentProps !== nextProps;
  return propHasChanged;
}

// call this from componentShouldUpdate to figure out if it should or not
export function queryChangedEnoughToUpdate(queries, nextQueries, results, nextResults) {
  // only re-render if results, any labels, or any colors have changed
  if (results.length) { // may have reset results so avoid test if results is empty
    const labelsHaveChanged = queryPropertyHasChanged(queries.slice(0, results.length), nextQueries.slice(0, results.length), 'label');
    const colorsHaveChanged = queryPropertyHasChanged(queries.slice(0, results.length), nextQueries.slice(0, results.length), 'color');
    return (
      ((labelsHaveChanged || colorsHaveChanged))
       || (results !== nextResults.results)
    );
  }
  return false; // if both results and queries are empty, don't update
}

// TODO: implement this logic from Dashboard
const MAX_QUERY_LABEL_LENGTH = 60;
export const autoMagicQueryLabel = query => decodeURIComponent(trimToMaxLength(query.q, MAX_QUERY_LABEL_LENGTH));

// This handles samples or user-generated queries for you.  To handle quotes and utf and such, we do this
// via a form submission (after trying lots of other options).
export function postToDownloadUrl(url, query, otherData) {
  // figure out if it is sample or user-created query
  let data = { index: query.index };
  if (parseInt(query.searchId, 10) >= 0) {
    data.sampleId = query.searchId;
  } else {
    data.q = JSON.stringify(generateQueryParamObject(query, true)); // don't encode the params because we're not putting them on the url
  }
  if (otherData) {
    data = { ...data, ...otherData };
  }
  downloadViaFormPost(url, data);
}

export const slugifiedQueryLabel = queryLabel => slugify(trimToMaxLength(queryLabel, 30));

export function downloadExplorerSvg(queryLabel, type, domIdOrElement) {
  const filename = `${slugifiedQueryLabel(queryLabel)}-${type}`;
  downloadSvg(filename, domIdOrElement);
}
<|endoftext|>


<commit_before>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 11/24/12
 * Time: 10:13 PM
 * To change this template use File | Settings | File Templates.
 */

define([
    'modules/view',
    'element/application/application.element',
    'element/header.element',
    'element/footer.element',
    'element/application/application.element.content',
    'element/application/application.element.debug'
], function defineApplicationView(BaseView, AppHTML, Header, Footer, AppContent, DebuggerElement) {

    /**
     * View
     * @constructor
     * @class AppView
     * @extends BaseView
     */
    var AppView = function AppView() {
    };

    return AppView.extend('AppView', {

        /**
         * Render Application
         * @member AppView
         */
        renderApplication: function renderApplication() {

            /**
             * Define $application
             * @type {AppElement}
             */
            this.elements.$app = new AppHTML(this, {
                $container: this.getConfigHTML().container,
                id: this.createUUID()
            });

            this.header(Header, this.elements.$app);

            this.workspaces();

            this.footer(Footer, this.elements.$app);
        },

        /**
         * Render Workspaces container
         * @member AppView
         */
        workspaces: function workspaces() {

            /**
             * Define $workspaces
             * @type {AppContent}
             */
            this.elements.$workspaces = new AppContent(this, {
                $container: this.elements.$app.$,
                style: 'workspaces'
            });
        },

        /**
         * Render Debugger window
         * @member AppView
         */
        debug: function debug() {

            /**
             * Define $debugger
             * @type {DebuggerElement}
             */
            this.elements.$debugger = new DebuggerElement(this, {
                $container: this.elements.$app.$,
                style: 'debugger',
                opacity: 0.6,
                events: {
                    click: 'activateDebugger'
                }
            });
        },

        /**
         * Start rendering
         * @member AppView
         * @param {boolean} silent
         */
        render: function render(silent) {

            this.scope.observer.publish(
                this.scope.eventmanager.eventList.successRendered,
                silent
            );
        }

    }, BaseView.prototype)
});<commit_msg>fix comment<commit_after>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 11/24/12
 * Time: 10:13 PM
 * To change this template use File | Settings | File Templates.
 */

define([
    'modules/view',
    'element/application/application.element',
    'element/header.element',
    'element/footer.element',
    'element/application/application.element.content',
    'element/application/application.element.debug'
], function defineApplicationView(BaseView, AppHTML, Header, Footer, AppContent, DebuggerElement) {

    /**
     * View
     * @constructor
     * @class AppView
     * @extends BaseView
     */
    var AppView = function AppView() {
    };

    return AppView.extend('AppView', {

        /**
         * Render Application
         * @member AppView
         */
        renderApplication: function renderApplication() {

            /**
             * Define $application
             * @type {AppElement}
             */
            this.elements.$app = new AppHTML(this, {
                $container: this.getConfigHTML().container,
                id: this.createUUID()
            });

            this.header(Header, this.elements.$app);

            this.workspaces();

            this.footer(Footer, this.elements.$app);
        },

        /**
         * Render Workspaces container
         * @member AppView
         */
        workspaces: function workspaces() {

            /**
             * Define $workspaces
             * @type {AppContent}
             */
            this.elements.$workspaces = new AppContent(this, {
                $container: this.elements.$app.$,
                style: 'workspaces'
            });
        },

        /**
         * Render Debugger window
         * @member AppView
         */
        debug: function debug() {

            /**
             * Define $debugger
             * @type {DebuggerElement}
             */
            this.elements.$debugger = new DebuggerElement(this, {
                $container: this.elements.$app.$,
                style: 'debugger',
                opacity: 0.6,
                events: {
                    click: 'activateDebugger'
                }
            });
        },

        /**
         * Start rendering
         * @member AppView
         * @param {boolean} [silent]
         */
        render: function render(silent) {

            this.scope.observer.publish(
                this.scope.eventmanager.eventList.successRendered,
                silent
            );
        }

    }, BaseView.prototype)
});<|endoftext|>


<commit_before><commit_msg>Update parcialdimensionar - TESTE.js<commit_after><|endoftext|>


<commit_before>/**
	enyo.Node is a control that creates structured trees based off Enyo's child component heirachy format.

		{kind: "Node", icon: "images/folder-open.png", content: "Tree", expandable: true, expanded: true, components: [
			{icon: "images/file.png", content: "Alpha"},
			{icon: "images/folder-open.png", content: "Bravo", expandable: true, expanded: false, components: [
				{icon: "images/file.png", content: "Bravo-Alpha"},
				{icon: "images/file.png", content: "Bravo-Bravo"},
				{icon: "images/file.png", content: "Bravo-Charlie"}
			]},
		]}

	The default kind of components within a Node, are themselves enyo.Node, so only the top level Node of the tree needs to be explicitly defined as such.

	When an expandable tree node expands an onExpand event is sent, and when one is tapped it will send a nodeTap event.

	Optionally, there is a node property called onlyIconExpands (false by default) that, when true, tapping the icon is the only way to open expandable Nodes; tapping the content label would still fire the nodeTap event, but wouldn't expand it.
*/

enyo.kind({
	name: "enyo.Node",
	published: {
		//* @public
		//* whether or not the Node is expandable and has children branches
		expandable: false,
		//* open/closed state of this current Node
		expanded: false,
		//* image path to be used for the icon for this Node
		icon: "",
		//* Optional flag that will have the icon trigger expanding of a Node, and not the Node contents too
		onlyIconExpands: false,
		//* @protected
		//level: 0,
		selected: false
	},
	style: "padding: 0 0 0 16px;",
	content: "Node",
	defaultKind: "Node",
	classes: "enyo-node",
	components: [
		{name: "icon", kind: "Image", showing: false},
		{kind: "Control", name: "caption", Xtag: "span", style: "display: inline-block; padding: 4px;", allowHtml: true},
		{kind: "Control", name: "extra", tag: 'span', allowHtml: true}
	],
	childClient: [
		{kind: "Control", name: "box", classes: "enyo-node-box", Xstyle: "border: 1px solid orange;", components: [
			{kind: "Control", name: "client", classes: "enyo-node-client", Xstyle: "border: 1px solid lightblue;"}
		]}
	],
	events: {
		onNodeTap: "nodeTap",
		onNodeDblClick: "nodeDblClick",
		onExpand: "nodeExpand",
		onDestroyed: "nodeDestroyed"
	},
	handlers: {
		ondblclick: "dblclick"
	},
	//
	//* @protected
	create: function() {
		this.inherited(arguments);
		//this.expandedChanged();
		//this.levelChanged();
		this.selectedChanged();
		this.iconChanged();
	},
	destroy: function() {
		this.doDestroyed();
		this.inherited(arguments);
	},
	initComponents: function() {
		// TODO: optimize to create the childClient on demand
		//this.hasChildren = this.components;
		if (this.expandable) {
			this.kindComponents = this.kindComponents.concat(this.childClient);
		}
		this.inherited(arguments);
	},
	//
	contentChanged: function() {
		//this.$.caption.setContent((this.expandable ? (this.expanded ? "-" : "+") : "") + this.content);
		this.$.caption.setContent(this.content);
	},
	iconChanged: function() {
		this.$.icon.setSrc(this.icon);
		this.$.icon.setShowing(Boolean(this.icon));
	},
	selectedChanged: function() {
		this.addRemoveClass("enyo-selected", this.selected);
	},
	rendered: function() {
		this.inherited(arguments);
		if (this.expandable && !this.expanded) {
			this.quickCollapse();
		}
	},
	//
	addNodes: function(inNodes) {
		this.destroyClientControls();
		for (var i=0, n; n=inNodes[i]; i++) {
			this.createComponent(n);
		}
		this.$.client.render();
	},
	addTextNodes: function(inNodes) {
		this.destroyClientControls();
		for (var i=0, n; n=inNodes[i]; i++) {
			this.createComponent({content: n});
		}
		this.$.client.render();
	},
	//
	tap: function(inSender, inEvent) {
		if(!this.onlyIconExpands) {
			this.toggleExpanded();
			this.doNodeTap();
		} else {
			if((inEvent.target==this.$.icon.hasNode())) {
				this.toggleExpanded();
			} else {
				this.doNodeTap();
			}
		}
		return true;
	},
	dblclick: function(inSender, inEvent) {
		this.doNodeDblClick();
		return true;
	},
	//
	toggleExpanded: function() {
		this.setExpanded(!this.expanded);
	},
	quickCollapse: function() {
		this.removeClass("enyo-animate");
		this.$.box.applyStyle("height", "0");
		var h = this.$.client.getBounds().height;
		this.$.client.setBounds({top: -h});
	},
	_expand: function() {
		this.addClass("enyo-animate");
		var h = this.$.client.getBounds().height;
		this.$.box.setBounds({height: h});
		this.$.client.setBounds({top: 0});
		setTimeout(enyo.bind(this, function() {
			// things may have happened in the interim, make sure
			// we only fix height if we are still expanded
			if (this.expanded) {
				this.removeClass("enyo-animate");
				this.$.box.applyStyle("height", "auto");
			}
		}), 225);
	},
	_collapse: function() {
		// disable transitions
		this.removeClass("enyo-animate");
		// fix the height of our box (rather than 'auto'), this
		// gives webkit something to lerp from
		var h = this.$.client.getBounds().height;
		this.$.box.setBounds({height: h});
		// yield the thead so DOM can make those changes (without transitions)
		setTimeout(enyo.bind(this, function() {
			// enable transitions
			this.addClass("enyo-animate");
			// shrink our box to 0
			this.$.box.applyStyle("height", "0");
			// slide the contents up
			this.$.client.setBounds({top: -h});
		}), 25);
	},
	expandedChanged: function(inOldExpanded) {
		if (!this.expandable) {
			this.expanded = false;
		} else {
			var event = {expanded: this.expanded};
			this.doExpand(event);
			if (!event.wait) {
				this.effectExpanded();
			}
		}
	},
	effectExpanded: function() {
		if (this.$.client) {
			if (!this.expanded) {
				this._collapse();
			} else {
				this._expand();
			}
		}
		//this.contentChanged();
	}/*,
	//
	//
	levelChanged: function() {
		this.applyStyle("padding-left", 16 + "px");
	},
	toggleChildren: function() {
		if (this.$.list) {
			this.$.list.setShowing(this.expanded);
		}
	},
	renderNodes: function(inNodes) {
		var list = this.createComponent({name: "list", container: this});
		for (var i=0, n; n=inNodes[i]; i++) {
			n.setLevel(this.level + 1);
			n.setContainer(list);
			n.render();
		}
		list.render();
	},
	//* @public
	addNodes: function(inNodes) {
		this.renderNodes(inNodes);
		this.toggleChildren();
	},
	removeNodes: function() {
		if (this.$.list) {
			this.$.list.destroy();
		}
	},
	hasVisibleChildren: function() {
		return this.expanded && this.$.list && this.$.list.controls.length > 0;
	},
	fetchParent: function() {
		return this.level > 0 && this.container.container;
	},
	fetchChildren: function() {
		return this.$.list && this.$.list.controls;
	},
	fetchFirstChild: function() {
		return this.$.list && this.$.list.controls[0];
	},
	fetchLastChild: function() {
		return this.$.list && this.$.list.controls[this.$.list.controls.length-1];
	},
	fetchPrevSibling: function() {
		var i = this.container.controls.indexOf(this);
		return this.level > 0 && this.container.controls[i-1];
	},
	fetchNextSibling: function() {
		var i = this.container.controls.indexOf(this);
		return this.level > 0 && this.container.controls[i+1];
	},
	getVisibleBounds: function() {
		return this.$.client.getBounds();
	}
	*/
});<commit_msg>ENYO-590 Documentation for lib/layout/tree/source for Node.js<commit_after>/**
	enyo.Node is a control that creates structured trees based off Enyo's child component heirachy format.

		{kind: "Node", icon: "images/folder-open.png", content: "Tree", expandable: true, expanded: true, components: [
			{icon: "images/file.png", content: "Alpha"},
			{icon: "images/folder-open.png", content: "Bravo", expandable: true, expanded: false, components: [
				{icon: "images/file.png", content: "Bravo-Alpha"},
				{icon: "images/file.png", content: "Bravo-Bravo"},
				{icon: "images/file.png", content: "Bravo-Charlie"}
			]},
		]}

	The default kind of components within a Node, are themselves enyo.Node, so only the top level Node of the tree needs to be explicitly defined as such.

	When an expandable tree node expands an onExpand event is sent, and when one is tapped it will send a nodeTap event.

	Optionally, there is a node property called onlyIconExpands (false by default) that, when true, tapping the icon is the only way to open expandable Nodes; tapping the content label would still fire the nodeTap event, but wouldn't expand it.
*/

enyo.kind({
	name: "enyo.Node",
	published: {
		//* @public
		//* whether or not the Node is expandable and has children branches
		expandable: false,
		//* open/closed state of this current Node
		expanded: false,
		//* image path to be used for the icon for this Node
		icon: "",
		//* Optional flag that will have the icon trigger expanding of a Node, and not the Node contents too
		onlyIconExpands: false,
		//* @protected
		//* Adds or removes the enyo-selected css class
		selected: false
	},
	style: "padding: 0 0 0 16px;",
	content: "Node",
	defaultKind: "Node",
	classes: "enyo-node",
	components: [
		{name: "icon", kind: "Image", showing: false},
		{kind: "Control", name: "caption", Xtag: "span", style: "display: inline-block; padding: 4px;", allowHtml: true},
		{kind: "Control", name: "extra", tag: 'span', allowHtml: true}
	],
	childClient: [
		{kind: "Control", name: "box", classes: "enyo-node-box", Xstyle: "border: 1px solid orange;", components: [
			{kind: "Control", name: "client", classes: "enyo-node-client", Xstyle: "border: 1px solid lightblue;"}
		]}
	],
	handlers: {
		ondblclick: "dblclick"
	},
	events: {
		//* @public
		//* Fired when the Node is tapped
		onNodeTap: "nodeTap",
		//* Fired when the Node is double-clicked
		onNodeDblClick: "nodeDblClick",
		//* Fired when the Node is expanded or contracted, indicated by the 'expanded' property in the event data
		onExpand: "nodeExpand",
		//* Fired when the Node is destroyed
		onDestroyed: "nodeDestroyed"
	},
	//
	//* @protected
	create: function() {
		this.inherited(arguments);
		//this.expandedChanged();
		//this.levelChanged();
		this.selectedChanged();
		this.iconChanged();
	},
	destroy: function() {
		this.doDestroyed();
		this.inherited(arguments);
	},
	initComponents: function() {
		// TODO: optimize to create the childClient on demand
		//this.hasChildren = this.components;
		if (this.expandable) {
			this.kindComponents = this.kindComponents.concat(this.childClient);
		}
		this.inherited(arguments);
	},
	//
	contentChanged: function() {
		//this.$.caption.setContent((this.expandable ? (this.expanded ? "-" : "+") : "") + this.content);
		this.$.caption.setContent(this.content);
	},
	iconChanged: function() {
		this.$.icon.setSrc(this.icon);
		this.$.icon.setShowing(Boolean(this.icon));
	},
	selectedChanged: function() {
		this.addRemoveClass("enyo-selected", this.selected);
	},
	rendered: function() {
		this.inherited(arguments);
		if (this.expandable && !this.expanded) {
			this.quickCollapse();
		}
	},
	//
	addNodes: function(inNodes) {
		this.destroyClientControls();
		for (var i=0, n; n=inNodes[i]; i++) {
			this.createComponent(n);
		}
		this.$.client.render();
	},
	addTextNodes: function(inNodes) {
		this.destroyClientControls();
		for (var i=0, n; n=inNodes[i]; i++) {
			this.createComponent({content: n});
		}
		this.$.client.render();
	},
	//
	tap: function(inSender, inEvent) {
		if(!this.onlyIconExpands) {
			this.toggleExpanded();
			this.doNodeTap();
		} else {
			if((inEvent.target==this.$.icon.hasNode())) {
				this.toggleExpanded();
			} else {
				this.doNodeTap();
			}
		}
		return true;
	},
	dblclick: function(inSender, inEvent) {
		this.doNodeDblClick();
		return true;
	},
	//
	toggleExpanded: function() {
		this.setExpanded(!this.expanded);
	},
	quickCollapse: function() {
		this.removeClass("enyo-animate");
		this.$.box.applyStyle("height", "0");
		var h = this.$.client.getBounds().height;
		this.$.client.setBounds({top: -h});
	},
	_expand: function() {
		this.addClass("enyo-animate");
		var h = this.$.client.getBounds().height;
		this.$.box.setBounds({height: h});
		this.$.client.setBounds({top: 0});
		setTimeout(enyo.bind(this, function() {
			// things may have happened in the interim, make sure
			// we only fix height if we are still expanded
			if (this.expanded) {
				this.removeClass("enyo-animate");
				this.$.box.applyStyle("height", "auto");
			}
		}), 225);
	},
	_collapse: function() {
		// disable transitions
		this.removeClass("enyo-animate");
		// fix the height of our box (rather than 'auto'), this
		// gives webkit something to lerp from
		var h = this.$.client.getBounds().height;
		this.$.box.setBounds({height: h});
		// yield the thead so DOM can make those changes (without transitions)
		setTimeout(enyo.bind(this, function() {
			// enable transitions
			this.addClass("enyo-animate");
			// shrink our box to 0
			this.$.box.applyStyle("height", "0");
			// slide the contents up
			this.$.client.setBounds({top: -h});
		}), 25);
	},
	expandedChanged: function(inOldExpanded) {
		if (!this.expandable) {
			this.expanded = false;
		} else {
			var event = {expanded: this.expanded};
			this.doExpand(event);
			if (!event.wait) {
				this.effectExpanded();
			}
		}
	},
	effectExpanded: function() {
		if (this.$.client) {
			if (!this.expanded) {
				this._collapse();
			} else {
				this._expand();
			}
		}
		//this.contentChanged();
	}/*,
	//
	//
	levelChanged: function() {
		this.applyStyle("padding-left", 16 + "px");
	},
	toggleChildren: function() {
		if (this.$.list) {
			this.$.list.setShowing(this.expanded);
		}
	},
	renderNodes: function(inNodes) {
		var list = this.createComponent({name: "list", container: this});
		for (var i=0, n; n=inNodes[i]; i++) {
			n.setLevel(this.level + 1);
			n.setContainer(list);
			n.render();
		}
		list.render();
	},
	//* @public
	addNodes: function(inNodes) {
		this.renderNodes(inNodes);
		this.toggleChildren();
	},
	removeNodes: function() {
		if (this.$.list) {
			this.$.list.destroy();
		}
	},
	hasVisibleChildren: function() {
		return this.expanded && this.$.list && this.$.list.controls.length > 0;
	},
	fetchParent: function() {
		return this.level > 0 && this.container.container;
	},
	fetchChildren: function() {
		return this.$.list && this.$.list.controls;
	},
	fetchFirstChild: function() {
		return this.$.list && this.$.list.controls[0];
	},
	fetchLastChild: function() {
		return this.$.list && this.$.list.controls[this.$.list.controls.length-1];
	},
	fetchPrevSibling: function() {
		var i = this.container.controls.indexOf(this);
		return this.level > 0 && this.container.controls[i-1];
	},
	fetchNextSibling: function() {
		var i = this.container.controls.indexOf(this);
		return this.level > 0 && this.container.controls[i+1];
	},
	getVisibleBounds: function() {
		return this.$.client.getBounds();
	}
	*/
});<|endoftext|>


<commit_before>//var queue = new PowerQueue();
var hn = Meteor.require('hacker-news-api');

var readHn = function () {
  "use strict";
  console.log('Reading last hour, 12 hours, 24 hours, and week of Hacker News');
  var now = Date.now() / 1000;
  var querylist = [];

  // past hour
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60) + ',created_at_i<' +
  now);

  // past 12 hours
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 12) + ',created_at_i<' +
  now);

  // past 24 hours
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 24) + ',created_at_i<' +
  now);

  // past week
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 24 * 7) + ',created_at_i<' +
  now);

  // past month
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 24 * 30) + ',created_at_i<' +
  now);

  // past year
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 24 * 365) + ',created_at_i<' +
  now);

  // past ever
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  0 + ',created_at_i<' +
  now);

  _.forEach(querylist, function (query) {
    hn.call(query, Meteor.bindEnvironment(
      function (error, data) {
        if (error) {
          throw error;
        }
        _(data.hits).forEach(function (item) {
          /*jshint camelcase: false */
          var obj = {
            oldId: parseInt(item.objectID, 10),
            oldPoints: parseInt(item.points, 10),
            createdAt: new Date(item.created_at),
            site: 'hn',
            author: item.author,
            title: item.title,
            url: item.url,
            oldComments: parseInt(item.num_comments, 10),
          };

          Posts.upsert({
            oldId: obj.oldId
          },{
            $set: obj
          });

        });
      }, function (error) {
        throw error;
      })
    );
  });
};

// read last 24 hours of hn
readHn();

// reread hn every half hour
Meteor.setInterval(readHn, 1000 * 60 * 30);
<commit_msg>Reread HN every minute<commit_after>//var queue = new PowerQueue();
var hn = Meteor.require('hacker-news-api');

var readHn = function () {
  "use strict";
  console.log('Reading last hour, 12 hours, 24 hours, and week of Hacker News');
  var now = Date.now() / 1000;
  var querylist = [];

  // past hour
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60) + ',created_at_i<' +
  now);

  // past 12 hours
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 12) + ',created_at_i<' +
  now);

  // past 24 hours
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 24) + ',created_at_i<' +
  now);

  // past week
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 24 * 7) + ',created_at_i<' +
  now);

  // past month
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 24 * 30) + ',created_at_i<' +
  now);

  // past year
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  (now - 60 * 60 * 24 * 365) + ',created_at_i<' +
  now);

  // past ever
  querylist.push('search?tags=story&numericFilters=created_at_i>' +
  0 + ',created_at_i<' +
  now);

  _.forEach(querylist, function (query) {
    hn.call(query, Meteor.bindEnvironment(
      function (error, data) {
        if (error) {
          throw error;
        }
        _(data.hits).forEach(function (item) {
          /*jshint camelcase: false */
          var obj = {
            oldId: parseInt(item.objectID, 10),
            oldPoints: parseInt(item.points, 10),
            createdAt: new Date(item.created_at),
            site: 'hn',
            author: item.author,
            title: item.title,
            url: item.url,
            oldComments: parseInt(item.num_comments, 10),
          };

          Posts.upsert({
            oldId: obj.oldId
          },{
            $set: obj
          });

        });
      }, function (error) {
        throw error;
      })
    );
  });
};

// reread hn
readHn();

// reread hn every minute
Meteor.setInterval(readHn, 1000 * 60);
<|endoftext|>


<commit_before>/*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Copyright (c) 2014 Mozilla Corporation
*/

if (Meteor.isClient) {

    //select an incident for editing
    Template.preferences.events({
        "click .something": function(e, t) {
        },
        'input #preferences': _.debounce(function(e, t) {
            savePreferences(e, t);
        }, 500),

    });

    Template.preferences.rendered = function() {
        // Deps.autorun(function () {
        //     Meteor.subscribe("preferences", Meteor.user().profile.email);
        // });

        savePreferences = function(e, template) {
            var preferencesobj = {
                name: template.find("#name").value,
                email: template.find("#email").value,
                theme: template.find("#theme").value
            }

            preferences.update(template.data._id,
                { $set: preferencesobj },
                {},
                function(error, nobj) {
                    if (!error && nobj === 1) {
                        $('#saveMessage').text('Changes Saved');
                    } else {
                        $('#saveMessage').text('Changes Not Saved');
                        console.log(error, template);
                    }
                }
            );

            //clear the info message after a bit
            Meteor.setTimeout(function() {
                $('#saveMessage').text('');
            }, 3000);
        }
    };

}
<commit_msg>auto-set a theme when picked<commit_after>/*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Copyright (c) 2014 Mozilla Corporation
*/

if ( Meteor.isClient ) {

    //select an incident for editing
    Template.preferences.events( {
        "change #theme": function( e, t ) {
            savePreferences( e, t );
            Meteor.setTimeout( function() {
                location.reload( true );
            }, 1000 );
        },
        'input #preferences': _.debounce( function( e, t ) {
            savePreferences( e, t );
        }, 500 ),

    } );

    Template.preferences.rendered = function() {
        // Deps.autorun(function () {
        //     Meteor.subscribe("preferences", Meteor.user().profile.email);
        // });

        savePreferences = function( e, template ) {
            var preferencesobj = {
                name: template.find( "#name" ).value,
                email: template.find( "#email" ).value,
                theme: template.find( "#theme" ).value
            }

            preferences.update( template.data._id,
                { $set: preferencesobj },
                {},
                function( error, nobj ) {
                    if ( !error && nobj === 1 ) {
                        $( '#saveMessage' ).text( 'Changes Saved' );
                    } else {
                        $( '#saveMessage' ).text( 'Changes Not Saved' );
                        console.log( error, template );
                    }
                }
            );

            //clear the info message after a bit
            Meteor.setTimeout( function() {
                $( '#saveMessage' ).text( '' );
            }, 3000 );
        }
    };

}
<|endoftext|>