<commit_before>import { hooks } from '../utils/hooks';
import hasOwnProp from '../utils/has-own-prop';
import getParsingFlags from '../create/parsing-flags';

// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = hooks.momentProperties = [];

export function copyConfig(to, from) {
    var i, prop, val;

    if (typeof from._isAMomentObject !== 'undefined') {
        to._isAMomentObject = from._isAMomentObject;
    }
    if (typeof from._i !== 'undefined') {
        to._i = from._i;
    }
    if (typeof from._f !== 'undefined') {
        to._f = from._f;
    }
    if (typeof from._l !== 'undefined') {
        to._l = from._l;
    }
    if (typeof from._strict !== 'undefined') {
        to._strict = from._strict;
    }
    if (typeof from._tzm !== 'undefined') {
        to._tzm = from._tzm;
    }
    if (typeof from._isUTC !== 'undefined') {
        to._isUTC = from._isUTC;
    }
    if (typeof from._offset !== 'undefined') {
        to._offset = from._offset;
    }
    if (typeof from._pf !== 'undefined') {
        to._pf = getParsingFlags(from);
    }
    if (typeof from._locale !== 'undefined') {
        to._locale = from._locale;
    }

    if (momentProperties.length > 0) {
        for (i in momentProperties) {
            prop = momentProperties[i];
            val = from[prop];
            if (typeof val !== 'undefined') {
                to[prop] = val;
            }
        }
    }

    return to;
}

var updateInProgress = false;

// Moment prototype object
export function Moment(config) {
    copyConfig(this, config);
    this._d = new Date(+config._d);
    // Prevent infinite loop in case updateOffset creates new moment
    // objects.
    if (updateInProgress === false) {
        updateInProgress = true;
        hooks.updateOffset(this);
        updateInProgress = false;
    }
}

export function isMoment (obj) {
    return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
}
<commit_msg>perf: use faster form of copying dates, across the board improvement<commit_after>import { hooks } from '../utils/hooks';
import hasOwnProp from '../utils/has-own-prop';
import getParsingFlags from '../create/parsing-flags';

// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = hooks.momentProperties = [];

export function copyConfig(to, from) {
    var i, prop, val;

    if (typeof from._isAMomentObject !== 'undefined') {
        to._isAMomentObject = from._isAMomentObject;
    }
    if (typeof from._i !== 'undefined') {
        to._i = from._i;
    }
    if (typeof from._f !== 'undefined') {
        to._f = from._f;
    }
    if (typeof from._l !== 'undefined') {
        to._l = from._l;
    }
    if (typeof from._strict !== 'undefined') {
        to._strict = from._strict;
    }
    if (typeof from._tzm !== 'undefined') {
        to._tzm = from._tzm;
    }
    if (typeof from._isUTC !== 'undefined') {
        to._isUTC = from._isUTC;
    }
    if (typeof from._offset !== 'undefined') {
        to._offset = from._offset;
    }
    if (typeof from._pf !== 'undefined') {
        to._pf = getParsingFlags(from);
    }
    if (typeof from._locale !== 'undefined') {
        to._locale = from._locale;
    }

    if (momentProperties.length > 0) {
        for (i in momentProperties) {
            prop = momentProperties[i];
            val = from[prop];
            if (typeof val !== 'undefined') {
                to[prop] = val;
            }
        }
    }

    return to;
}

var updateInProgress = false;

// Moment prototype object
export function Moment(config) {
    copyConfig(this, config);
    this._d = new Date(config._d.getTime());
    // Prevent infinite loop in case updateOffset creates new moment
    // objects.
    if (updateInProgress === false) {
        updateInProgress = true;
        hooks.updateOffset(this);
        updateInProgress = false;
    }
}

export function isMoment (obj) {
    return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
}
<|endoftext|>


<commit_before>/* global $ */

$(document).ready(function () {
  $('.carousel').slick({
    infinite: true,
    dots: true,
    autoplay: false,
    autoplaySpeed: 3000
  })
})
<commit_msg>Autoplay carousel<commit_after>/* global $ */

$(document).ready(function () {
  $('.carousel').slick({
    infinite: true,
    dots: true,
    autoplay: true,
    autoplaySpeed: 3000
  })
})
<|endoftext|>


<commit_before>/**
 * Created by reinv on 15-6-2017.
 */

/* global $ */

$.get('/api/v1/graphs', sets => {
  // Populate void:Dataset part
  sets['@graph']
    .filter(set => set['@type'].find(type => type === 'void:Dataset'))
    .forEach(dataset => $('#dataset-showcases')
      .append(`

Zonder titel

  ${dataset['@id'].split('/').slice(-1)}

`
    ));

  // Populate void:Linkset part
  sets['@graph']
    .filter(set => set['@type'].find(type => type === 'void:Linkset'))
    .forEach(dataset => $('#linkset-showcases')
      .append(`

Zonder titel

${dataset['@id'].split('/').slice(-1)}
`
    ));

  // Populate miscellaneous
  sets['@graph']
    .filter(set => !set['@type'].find(type => type === 'void:Linkset' || type === 'void:Dataset'))
    .forEach(dataset => $('#overig-showcases')
      .append(`

Zonder titel

${dataset['@id'].split('/').slice(-1)}
`
    ));
});
<commit_msg>Hopefully fix styling<commit_after>/**
 * Created by reinv on 15-6-2017.
 */

/* global $ */

$.get('/api/v1/graphs', sets => {
  // Populate void:Dataset part
  sets['@graph']
    .filter(set => set['@type'].find(type => type === 'void:Dataset'))
    .forEach(dataset => {
      let uri = dataset['@id'];
      if (uri[-1] === '/') uri = uri.slice(0, -1);
      $('#dataset-showcases')
        .append(`

Zonder titel

  ${uri.split('/').slice(-1)}

`
        );
    });

  // Populate void:Linkset part
  sets['@graph']
    .filter(set => set['@type'].find(type => type === 'void:Linkset'))
    .forEach(dataset => $('#linkset-showcases')
      .append(`

Zonder titel

${dataset['@id'].split('/').slice(-1)}
`
    ));

  // Populate miscellaneous
  sets['@graph']
    .filter(set => !set['@type'].find(type => type === 'void:Linkset' || type === 'void:Dataset'))
    .forEach(dataset => $('#overig-showcases')
      .append(`

Zonder titel

${dataset['@id'].split('/').slice(-1)}
`
    ));
});
<|endoftext|>


<commit_before>/**
 * onlylemi
 *
 * @author: only乐秘
 * @time: 2016-02-24 2:54
 */

$(document).ready(function() {

    /* set https */
    if (location.hostname == "onlylemi.github.io") {
        var a = location.href;
        var b = a.substring(5);
        a = a.substring(0, 5);
        if (a == "http:") {
            location.href = "https:" + b;
        }
    }

    /* nprogress */
    $('body').show();
    NProgress.start();
    setTimeout(function() {
        NProgress.done();
    }, 300);

    setTimeout(function() {
        $(".wrapper-masthead").css({
    	'border-top': '4px solid #262b3b'
    });
    }, 600);

    /* sidebar-right */
    $(".js-scroll-top").click(function() {
        $("html,body").animate({ scrollTop: $("#wrapper-masthead").offset().top }, 1000)
    });
    $(".js-scroll-comment").click(function() {
        $("html,body").animate({ scrollTop: $("#comments").offset().top }, 1000)
    });
    $(".js-scroll-down").click(function() {
        $("html,body").animate({ scrollTop: $("#wrapper-footer").offset().top }, 1000)
    });

    /* contents */
    $('#toc').toc({
        title: '',
        minimumHeaders: 0,
        listType: 'ul',
        isEncode: false
    });

    /* post-contents */
    var show_contents = false;
    $(".contents-btn").click(function() {
        if (show_contents) {
            $(".post-contents").css({
                'visibility': 'hidden'
            });
        } else {
            $(".post-contents").css({
                'visibility': 'visible'
            });
        }
        show_contents = !show_contents;
    });

    $(".contents-close").click(function() {
        $(".post-contents").css({
            'visibility': 'hidden'
        });
        show_contents = !show_contents;
    });

    /* 滚动监听 */

    /* search */
    var time1 = 0;
    var show = false;
    var names = new Array(); //文章名字等
    var urls = new Array(); //文章地址
    $(document).keyup(function(e) {
        var time2 = new Date().getTime();
        if (e.keyCode == 17) {
            var gap = time2 - time1;
            time1 = time2;
            if (gap < 500) {
                if (show) {
                    $('.search-dialog').modal('hide')
                    show = false;
                } else {
                    $('.search-dialog').modal('show')
                    show = true;
                    $("#search-content").val("");
                    window.setTimeout("$('#search-content').focus();", 500);
                }
                time1 = 0;
            }
        } else if (e.keyCode == 27) {
            $('.search-dialog').modal('hide')
            show = false;
            time1 = 0;
        }
    });

    $("#search-content").keyup(function(e) {
        var time2 = new Date().getTime();
        if (window.event.keyCode == 17) {
            var gap = time2 - time1;
            time1 = time2;
            if (gap < 500) {
                if (show) {
                    $('.search-dialog').modal('hide');
                    show = false;
                } else {
                    $('.search-dialog').modal('show')
                    $("#search-content").val("");
                    window.setTimeout("$('#search-content').focus();", 500);
                    show = true;
                }
                time1 = 0;
            }
        }
    });

    $('#search-dialog').on('hidden.bs.modal', function(e) {
        show = false;
    })

    $(".search-btn").click(function() {
        $("#search-content").val("");
        /*$('#search-content').focus();*/
        window.setTimeout("$('#search-content').focus();", 500);
    });

    $.getJSON("/search.json").done(function(data) {
        if (data.code == 0) {
            for (var index in data.data) {
                var item = data.data[index];
                names.push(item.title);
                urls.push(item.url);
            }

            $("#search-content").typeahead({
                source: names,

                afterSelect: function(item) {
                    $('.search-dialog').modal('hide')
                    show = false;
                    window.location.href = (urls[names.indexOf(item)]);
                    return item;
                }
            });
        }
    });

});
<commit_msg>Update onlylemi.js<commit_after>/**
 * onlylemi
 *
 * @author: only乐秘
 * @time: 2016-02-24 2:54
 */

$(document).ready(function() {

    /* set https */
    if (location.hostname == "onlylemi.github.io") {
        var a = location.href;
        var b = a.substring(5);
        a = a.substring(0, 5);
        if (a == "http:") {
            location.href = "https:" + b;
        }
    }

    /* nprogress */
    $('body').show();
    NProgress.start();
    setTimeout(function() {
        NProgress.done();
    }, 300);

    setTimeout(function() {
        $(".wrapper-masthead").css({
    	'border-top': '4px solid #262b3b'
    });
    }, 600);

    /* sidebar-right */
    $(".js-scroll-top").click(function() {
        $("html,body").animate({ scrollTop: $("#wrapper-masthead").offset().top }, 1000)
    });
    $(".js-scroll-comment").click(function() {
        $("html,body").animate({ scrollTop: $("#comments").offset().top }, 1000)
    });
    $(".js-scroll-down").click(function() {
        $("html,body").animate({ scrollTop: $("#wrapper-footer").offset().top }, 1000)
    });

    /* contents */
    $('#toc').toc({
        title: '',
        minimumHeaders: 0,
        listType: 'ul',
        isEncode: false
    });

    /* post-contents */
    var show_contents = false;
    $(".contents-btn").click(function() {
        if (show_contents) {
            $(".post-contents").css({
                'visibility': 'hidden'
            });
        } else {
            $(".post-contents").css({
                'visibility': 'visible'
            });
        }
        show_contents = !show_contents;
    });

    $(".contents-close").click(function() {
        $(".post-contents").css({
            'visibility': 'hidden'
        });
        show_contents = !show_contents;
    });

    /* 滚动监听 */

    /* search */
    var time1 = 0;
    var show = false;
    var names = new Array(); //文章名字等
    var urls = new Array(); //文章地址
    $(document).keyup(function(e) {
        var time2 = new Date().getTime();
        if (e.keyCode == 17) {
            var gap = time2 - time1;
            time1 = time2;
            if (gap < 500) {
                if (show) {
                    $('.search-dialog').modal('hide')
                    show = false;
                } else {
                    $('.search-dialog').modal('show')
                    show = true;
                    $("#search-content").val("");
                    window.setTimeout("$('#search-content').focus();", 500);
                }
                time1 = 0;
            }
        } else if (e.keyCode == 27) {
            $('.search-dialog').modal('hide')
            show = false;
            time1 = 0;
        }
    });

    $("#search-content").keyup(function(e) {
        var time2 = new Date().getTime();
        if (window.event.keyCode == 17) {
            var gap = time2 - time1;
            time1 = time2;
            if (gap < 500) {
                if (show) {
                    $('.search-dialog').modal('hide');
                    show = false;
                } else {
                    $('.search-dialog').modal('show')
                    $("#search-content").val("");
                    window.setTimeout("$('#search-content').focus();", 500);
                    show = true;
                }
                time1 = 0;
            }
        }
    });

    $('#search-dialog').on('hidden.bs.modal', function(e) {
        show = false;
    })

    $(".search-btn").click(function() {
        $("#search-content").val("");
        /*$('#search-content').focus();*/
        window.setTimeout("$('#search-content').focus();", 500);
    });

    $.getJSON("../search.json").done(function(data) {
        if (data.code == 0) {
            for (var index in data.data) {
                var item = data.data[index];
                names.push(item.title);
                urls.push(item.url);
            }

            $("#search-content").typeahead({
                source: names,

                afterSelect: function(item) {
                    $('.search-dialog').modal('hide')
                    show = false;
                    window.location.href = (urls[names.indexOf(item)]);
                    return item;
                }
            });
        }
    });

});
<|endoftext|>


<commit_before>/*
	Dynamically generate projects from JSON for Parallelism by HTML5 UP
	Christian Frisson
	MIT licensed
*/

function initProjects(thumbHeight) {
    d3.json("projects.json", function(error, data) {
        if (error) console.log(error)
            //var people = data.people;
        var article = d3.select("#reel")
            .selectAll("item thumb")
            .data(data.projects)
            .enter()
            .append(function(d) {
                return document.createElement("article");
            })
            .attr("data-width", function(d) {
                return (d.thumb.width * thumbHeight / d.thumb.height);
            })
            .attr("class", "item thumb")
        article.append(function(d) {
            var h2 = document.createElement("h2");
            var innerHTML = d.title;
            innerHTML += " (";
            if (d.eventName !== undefined) {
                innerHTML += d.eventName;
            }
            if (d.eventName !== undefined && d.eventYear !== undefined) {
                innerHTML += " ";
            }
            if (d.eventYear !== undefined) {
                innerHTML += d.eventYear;
            }
            innerHTML += ")";
            h2.innerHTML = innerHTML;
            return h2;
        });
        article.append(function(d) {
                var a = document.createElement("a");
                a.className = "image";
                if (d.video !== undefined) {
                    if (d.video.host === "vimeo"){
                        a.href = "http://vimeo.com/" + d.video.id;
                        a.setAttribute("data-poptrox", "vimeo,800x480");
                    }
                    else if (d.video.host === "youtube"){
                        a.href = "http://youtu.be/" + d.video.id;
                        a.setAttribute("data-poptrox", "youtube,800x480");
                    }
                } else if (d.image !== undefined) {
                    a.href = "images/fulls/" + d.image.stem;
                } else {
                    a.href = "images/fulls/" + d.thumb.stem;
                }
                return a;
            })
            .append(function(d) {
                var img = document.createElement("img");
                if (d.thumb.stem !== undefined)
                    img.src = "images/thumbs/" + d.thumb.stem;
                // Pass caption to poptrox
                d.caption = "";

                /*d.caption += " ";
                d.caption +="project: ";*/

                d.caption += d.title;

                if (d.publications === undefined) {
                    d.caption += " (";
                    if (d.eventName !== undefined) {
                        d.caption += d.eventName;
                    }
                    if (d.eventName !== undefined && d.eventYear !== undefined) {
                        d.caption += " ";
                    }
                    if (d.eventYear !== undefined) {
                        d.caption += d.eventYear;
                    }
                    d.caption += ")";
                    d.caption += "
"
                    if (d.subtitle !== undefined) {
                        d.caption += "
" + d.subtitle + "
";
                    }
                } else {
                    if (d.subtitle !== undefined) {
                        d.caption += ": " + d.subtitle;
                    }
                    d.caption += "
"
                }

                var thesis = false;
                if (d.publications !== undefined) {
                    d.caption += "
"
                    d.caption += " ";
                    d.caption += "dissemination: ";
                    d.publications.forEach(function(publication, i) {
                        if (i > 0) {
                            d.caption += " and "
                        }
                        //if (publication.conference !== undefined) {

                        if (publication.type === "phdthesis") {
                            thesis = true;
                            d.caption += "PhD thesis";
                        } else if (publication.type !== undefined) {
                            d.caption += publication.type + " ";
                        }

                        if (publication.presentation !== undefined) {
                            d.caption += publication.presentation
                            if (publication.presentation === "oral") d.caption += " presentation"
                            d.caption += " "
                        }
                        if (publication.conference !== undefined) {
                            d.caption += "at ";
                            if (publication.conference.split("ACM").length === 1) {
                                d.caption += "the ";
                            }
                            d.caption += publication.conference;
                            if (publication.series !== undefined && publication.series !== publication.conference) {
                                d.caption += " ("
                                d.caption += publication.series;
                                //d.caption += ")"
                            }
                            if (publication.year !== undefined && publication.year.toString().length === 4) {
                                //d.caption += " " + publication.year;
                                d.caption += "'";
                                d.caption += publication.year.toString().charAt(2);
                                d.caption += publication.year.toString().charAt(3);
                            }
                            if (publication.series !== undefined && publication.series !== publication.conference) {
                                d.caption += ")"
                            }

                            if (publication.acmDLAuthorizeId !== undefined) {

                                d.caption += ' '
                                d.caption += '';
                            }
                        } else if (publication.university !== undefined) {
                            d.caption += " at ";
                            d.caption += publication.university;
                            if (publication.year !== undefined) {
                                d.caption += " (" + publication.year + ")";
                            }
                        }
                        /*if(publication.location !== undefined){
                            if(publication.location.city !== undefined){
                                d.caption += ", " + publication.location.city;
                            }
                            if(publication.location.country !== undefined){
                                d.caption += ", " + publication.location.country;
                            }
                        }*/

                        //}
                    });
                    d.caption += "
";
                }

                /*if (d.dataset !== undefined) {
                    d.caption += "
"
                    d.caption += " ";
                    d.caption += "dataset: " + d.dataset + "
";
                }*/

                if (d.people !== undefined) {
                    d.caption += "
";
                    d.caption += " ";
                    d.caption += (thesis ? "jury: " : "in collaboration with: ");
                    for (var n = 0; n < d.people.length; n++) {
                        if (d.people[n][0] !== "Christian" && d.people[n][1] !== "Frisson") {
                            /*var author= people.find(
							function(e){
								if(d.people[n][0] == e.given && d.people[n][1] == e.family){
									return e;
								}
							});
						if(author !== undefined){
	                        d.caption += author.given;
	                        d.caption += " ";
	                        d.caption += author.family;
	                        if(n<d.people.length-1){
	                            d.caption += ", ";
	                        }
						}*/
                            if (d.people[n][0] !== undefined && d.people[n][1] !== undefined) {
                                d.caption += d.people[n][0];
                                d.caption += " ";
                                d.caption += d.people[n][1];
                                if (n < d.people.length - 1) {
                                    d.caption += ", ";
                                }
                            }

                        }
                    }
                    d.caption += "
";
                }

                if (d.contribs !== undefined) {
                    //d.caption += "
contributions: " + d.contribs + "
";
                    d.caption += "
"

                    d.caption += " my contributions: ";

                    //d.caption += "
"
                    d.contribs.forEach(function(contrib, i) {
                        if (i > 0) d.caption += ",";
                        if (i === d.contribs.length - 1) d.caption += "

"
                            //d.caption += "
";
                        d.caption += " ";

                        if (contrib.type === "development") {
                            d.caption += "";

                            if (d.code !== undefined && d.code.host === "github") {
                                var url = "https://github.com/" + d.code.account + "/"
                                if (d.code.repo !== undefined) url += d.code.repo;
                                d.caption += " ";
                                d.caption += "Github"
                                d.caption += "";
                            }
                        } else {
                            d.caption += " ";
                        }
                        d.caption += " ";
                        //d.caption += "(";
                        d.caption += contrib.desc;
                        //d.caption += ")";
                        //d.caption += "
";
                    });
                    d.caption += "
"
                    d.caption += "
";
                }
                d.caption += "
"
                return img;
            })
    });
};<commit_msg>Update ACM DL logo<commit_after>/*
	Dynamically generate projects from JSON for Parallelism by HTML5 UP
	Christian Frisson
	MIT licensed
*/

function initProjects(thumbHeight) {
    d3.json("projects.json", function(error, data) {
        if (error) console.log(error)
            //var people = data.people;
        var article = d3.select("#reel")
            .selectAll("item thumb")
            .data(data.projects)
            .enter()
            .append(function(d) {
                return document.createElement("article");
            })
            .attr("data-width", function(d) {
                return (d.thumb.width * thumbHeight / d.thumb.height);
            })
            .attr("class", "item thumb")
        article.append(function(d) {
            var h2 = document.createElement("h2");
            var innerHTML = d.title;
            innerHTML += " (";
            if (d.eventName !== undefined) {
                innerHTML += d.eventName;
            }
            if (d.eventName !== undefined && d.eventYear !== undefined) {
                innerHTML += " ";
            }
            if (d.eventYear !== undefined) {
                innerHTML += d.eventYear;
            }
            innerHTML += ")";
            h2.innerHTML = innerHTML;
            return h2;
        });
        article.append(function(d) {
                var a = document.createElement("a");
                a.className = "image";
                if (d.video !== undefined) {
                    if (d.video.host === "vimeo"){
                        a.href = "http://vimeo.com/" + d.video.id;
                        a.setAttribute("data-poptrox", "vimeo,800x480");
                    }
                    else if (d.video.host === "youtube"){
                        a.href = "http://youtu.be/" + d.video.id;
                        a.setAttribute("data-poptrox", "youtube,800x480");
                    }
                } else if (d.image !== undefined) {
                    a.href = "images/fulls/" + d.image.stem;
                } else {
                    a.href = "images/fulls/" + d.thumb.stem;
                }
                return a;
            })
            .append(function(d) {
                var img = document.createElement("img");
                if (d.thumb.stem !== undefined)
                    img.src = "images/thumbs/" + d.thumb.stem;
                // Pass caption to poptrox
                d.caption = "";

                /*d.caption += " ";
                d.caption +="project: ";*/

                d.caption += d.title;

                if (d.publications === undefined) {
                    d.caption += " (";
                    if (d.eventName !== undefined) {
                        d.caption += d.eventName;
                    }
                    if (d.eventName !== undefined && d.eventYear !== undefined) {
                        d.caption += " ";
                    }
                    if (d.eventYear !== undefined) {
                        d.caption += d.eventYear;
                    }
                    d.caption += ")";
                    d.caption += "
"
                    if (d.subtitle !== undefined) {
                        d.caption += "
" + d.subtitle + "
";
                    }
                } else {
                    if (d.subtitle !== undefined) {
                        d.caption += ": " + d.subtitle;
                    }
                    d.caption += "
"
                }

                var thesis = false;
                if (d.publications !== undefined) {
                    d.caption += "
"
                    d.caption += " ";
                    d.caption += "dissemination: ";
                    d.publications.forEach(function(publication, i) {
                        if (i > 0) {
                            d.caption += " and "
                        }
                        //if (publication.conference !== undefined) {

                        if (publication.type === "phdthesis") {
                            thesis = true;
                            d.caption += "PhD thesis";
                        } else if (publication.type !== undefined) {
                            d.caption += publication.type + " ";
                        }

                        if (publication.presentation !== undefined) {
                            d.caption += publication.presentation
                            if (publication.presentation === "oral") d.caption += " presentation"
                            d.caption += " "
                        }
                        if (publication.conference !== undefined) {
                            d.caption += "at ";
                            if (publication.conference.split("ACM").length === 1) {
                                d.caption += "the ";
                            }
                            d.caption += publication.conference;
                            if (publication.series !== undefined && publication.series !== publication.conference) {
                                d.caption += " ("
                                d.caption += publication.series;
                                //d.caption += ")"
                            }
                            if (publication.year !== undefined && publication.year.toString().length === 4) {
                                //d.caption += " " + publication.year;
                                d.caption += "'";
                                d.caption += publication.year.toString().charAt(2);
                                d.caption += publication.year.toString().charAt(3);
                            }
                            if (publication.series !== undefined && publication.series !== publication.conference) {
                                d.caption += ")"
                            }

                            if (publication.acmDLAuthorizeId !== undefined) {

                                d.caption += ' '
                                d.caption += '';
                            }
                        } else if (publication.university !== undefined) {
                            d.caption += " at ";
                            d.caption += publication.university;
                            if (publication.year !== undefined) {
                                d.caption += " (" + publication.year + ")";
                            }
                        }
                        /*if(publication.location !== undefined){
                            if(publication.location.city !== undefined){
                                d.caption += ", " + publication.location.city;
                            }
                            if(publication.location.country !== undefined){
                                d.caption += ", " + publication.location.country;
                            }
                        }*/

                        //}
                    });
                    d.caption += "
";
                }

                /*if (d.dataset !== undefined) {
                    d.caption += "
"
                    d.caption += " ";
                    d.caption += "dataset: " + d.dataset + "
";
                }*/

                if (d.people !== undefined) {
                    d.caption += "
";
                    d.caption += " ";
                    d.caption += (thesis ? "jury: " : "in collaboration with: ");
                    for (var n = 0; n < d.people.length; n++) {
                        if (d.people[n][0] !== "Christian" && d.people[n][1] !== "Frisson") {
                            /*var author= people.find(
							function(e){
								if(d.people[n][0] == e.given && d.people[n][1] == e.family){
									return e;
								}
							});
						if(author !== undefined){
	                        d.caption += author.given;
	                        d.caption += " ";
	                        d.caption += author.family;
	                        if(n<d.people.length-1){
	                            d.caption += ", ";
	                        }
						}*/
                            if (d.people[n][0] !== undefined && d.people[n][1] !== undefined) {
                                d.caption += d.people[n][0];
                                d.caption += " ";
                                d.caption += d.people[n][1];
                                if (n < d.people.length - 1) {
                                    d.caption += ", ";
                                }
                            }

                        }
                    }
                    d.caption += "
";
                }

                if (d.contribs !== undefined) {
                    //d.caption += "
contributions: " + d.contribs + "
";
                    d.caption += "
"

                    d.caption += " my contributions: ";

                    //d.caption += "
"
                    d.contribs.forEach(function(contrib, i) {
                        if (i > 0) d.caption += ",";
                        if (i === d.contribs.length - 1) d.caption += "

"
                            //d.caption += "
";
                        d.caption += " ";

                        if (contrib.type === "development") {
                            d.caption += "";

                            if (d.code !== undefined && d.code.host === "github") {
                                var url = "https://github.com/" + d.code.account + "/"
                                if (d.code.repo !== undefined) url += d.code.repo;
                                d.caption += " ";
                                d.caption += "Github"
                                d.caption += "";
                            }
                        } else {
                            d.caption += " ";
                        }
                        d.caption += " ";
                        //d.caption += "(";
                        d.caption += contrib.desc;
                        //d.caption += ")";
                        //d.caption += "
";
                    });
                    d.caption += "
"
                    d.caption += "
";
                }
                d.caption += "
"
                return img;
            })
    });
};<|endoftext|>


<commit_before>angular.module('sikre.services', [])

  .factory('sikreAPIservice', function ($http) {
    //var mainAPIUrl = 'https://api.sikr.io/v1/';
    var sikreAPI = {};

    sikreAPI.getGroups = function () {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'groups/'
      });
    };

    sikreAPI.getGroup = function (groupId) {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'groups/' + groupId
      });
    };

    sikreAPI.saveGroup = function (data) {
      return $http({
        method: "POST",
        url: mainAPIUrl + 'groups/'
      });
    };

    sikreAPI.getItems = function () {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'items/'
      })
    };

    sikreAPI.getItem = function (itemId) {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'items/' + itemId
      })
    };

    sikreAPI.saveItem = function (data) {
      return $http({
        method: "POST",
        url: mainAPIUrl + 'items/',
        data: data
      });
    };

    sikreAPI.getServices = function () {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'services/'
      })
    };

    sikreAPI.getService = function (serviceId) {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'services/' + serviceId
      })
    };

    sikreAPI.saveService = function (data) {
      return $http({
        method: "POST",
        url: mainAPIUrl + 'services/',
        data: data
      });
    };

    return sikreAPI;
  });
<commit_msg>Fix tyopo<commit_after>angular.module('sikre.services', [])

  .factory('sikreAPIservice', function ($http) {
    //var mainAPIUrl = 'https://api.sikr.io/v1/';
    var sikreAPI = {};

    sikreAPI.getGroups = function () {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'groups/'
      });
    };

    sikreAPI.getGroup = function (groupId) {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'groups/' + groupId
      });
    };

    sikreAPI.saveGroup = function (data) {
      return $http({
        method: "POST",
        url: mainAPIUrl + 'groups/'
      });
    };

    sikreAPI.getItems = function () {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'items/'
      });
    };

    sikreAPI.getItem = function (itemId) {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'items/' + itemId
      });
    };

    sikreAPI.saveItem = function (data) {
      return $http({
        method: "POST",
        url: mainAPIUrl + 'items/',
        data: data
      });
    };

    sikreAPI.getServices = function () {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'services/'
      });
    };

    sikreAPI.getService = function (serviceId) {
      return $http({
        method: "GET",
        url: mainAPIUrl + 'services/' + serviceId
      });
    };

    sikreAPI.saveService = function (data) {
      return $http({
        method: "POST",
        url: mainAPIUrl + 'services/',
        data: data
      });
    };

    return sikreAPI;
  });
<|endoftext|>


<commit_before>/** @module */

import Vue from 'vue';
import _ from 'lodash';
import { def } from './common';
import batchedAdd from '../batchedAdd';

let nextBufferId = 0;

/** The IRC buffer instance */
export default class BufferState {
    constructor(name, networkid, state, messageDict) {
        // Enumerable properties that become reactive under Vue
        this.id = nextBufferId++;
        this.networkid = networkid;
        this.name = name;
        this.topics = [];
        this.key = '';
        this.joined = false;
        this.enabled = true;
        this.created_at = null;
        this.users = Object.create(null);
        this.modes = Object.create(null);
        this.flags = {
            unread: 0,
            alert_on: 'default',
            has_opened: false,
            channel_badkey: false,
            chathistory_available: true,
            requested_modes: false,
            requested_banlist: false,
            is_requesting_chathistory: false,
        };
        this.settings = { };
        this.last_read = 0;
        this.active_timeout = null;
        this.message_count = 0;
        this.current_input = '';
        this.input_history = [];
        this.input_history_pos = 0;
        this.show_input = true;

        Vue.observable(this);

        // Some non-enumerable properties (vues $watch won't cover these properties)
        def(this, 'state', state, false);
        def(this, 'messageDict', messageDict, false);

        let messagesObj = {
            networkid: this.networkid,
            buffer: this.name,
            messages: [],
        };
        this.messageDict.push(messagesObj);
        def(this, 'messagesObj', messagesObj, false);

        def(this, 'addMessageBatch', createMessageBatch(this), false);
        def(this, 'addUserBatch', createUserBatch(this), false);

        // poll who to update away status if away-notify is not enabled
        if (this.isChannel()) {
            maybeStartWhoLoop(this);
        }
    }

    get topic() {
        return this.topics.length === 0 ?
            '' :
            this.topics[this.topics.length - 1];
    }

    set topic(newVal) {
        this.topics.push(newVal);
    }

    getNetwork() {
        return this.state.getNetwork(this.networkid);
    }

    getMessages() {
        let bufMessages = _.find(this.messageDict, {
            networkid: this.networkid,
            buffer: this.name,
        });

        return bufMessages ?
            bufMessages.messages :
            [];
    }

    isServer() {
        return this.name === '*';
    }

    isChannel() {
        let chanPrefixes = ['#', '&'];
        let ircNetwork = this.getNetwork().ircClient.network;
        if (ircNetwork && ircNetwork.options.CHANTYPES) {
            chanPrefixes = ircNetwork.options.CHANTYPES;
        }

        return chanPrefixes.indexOf(this.name[0]) > -1;
    }

    isQuery() {
        let chanPrefixes = ['#', '&'];
        let ircNetwork = this.getNetwork().ircClient.network;
        if (ircNetwork && ircNetwork.options.CHANTYPES) {
            chanPrefixes = ircNetwork.options.CHANTYPES;
        }

        return chanPrefixes.indexOf(this.name[0]) === -1 &&
            !this.isSpecial() &&
            !this.isServer();
    }

    isSpecial() {
        // Special buffer names (Usually controller queries, like *status or *raw).
        // Server buffer '*' is not included in this classification.
        let name = this.name;
        return name[0] === '*' && name.length > 1;
    }

    isUserAnOp(nick) {
        let user = this.state.getUser(this.networkid, nick);
        if (!user) {
            return false;
        }

        let userBufferInfo = user.buffers[this.id];
        if (!userBufferInfo) {
            return false;
        }

        let modes = userBufferInfo.modes;
        let opModes = ['Y', 'y', 'q', 'a', 'o', 'h'];
        let hasOp = _.find(modes, mode => opModes.indexOf(mode.toLowerCase()) > -1);

        return !!hasOp;
    }

    /**
     * Get a users prefix symbol on a buffer from its modes
     * @param {Object} user The user object
     */
    userModePrefix(user) {
        // The user may not be on the buffer
        if (!user.buffers[this.id]) {
            return '';
        }

        let modes = user.buffers[this.id].modes;
        if (modes.length === 0) {
            return '';
        }

        let network = this.getNetwork();
        let netPrefixes = network.ircClient.network.options.PREFIX;
        // Find the first (highest) netPrefix in the users buffer modes
        let prefix = _.find(netPrefixes, p => modes.indexOf(p.mode) > -1);

        return prefix ?
            prefix.symbol :
            '';
    }

    /**
     * Get a users mode on a buffer
     * @param user {Object} The user object
     */
    userMode(user) {
        // The user may not be on the buffer
        if (!user.buffers[this.id]) {
            return '';
        }

        let modes = user.buffers[this.id].modes;
        if (modes.length === 0) {
            return '';
        }

        let network = this.getNetwork();
        let netPrefixes = network.ircClient.network.options.PREFIX;
        // Find the first (highest) netPrefix in the users buffer modes
        let prefix = _.find(netPrefixes, p => modes.indexOf(p.mode) > -1);

        return prefix ?
            prefix.mode :
            '';
    }

    setting(name, val) {
        if (typeof val !== 'undefined') {
            this.state.$set(this.settings, name, val);
            return val;
        }

        // Check the buffer specific settings before reverting to global settings
        let result = typeof this.settings[name] !== 'undefined' ?
            this.settings[name] :
            this.state.setting('buffers.' + name);

        return result;
    }

    rename(newName) {
        let network = this.getNetwork();
        let oldName = this.name;
        let setActive = this.state.getActiveBuffer() === this;

        this.name = newName;
        if (setActive) {
            this.state.setActiveBuffer(network.id, newName);
        }

        // update the buffer name on our messages
        let bufferMessages = _.find(this.messageDict, { networkid: network.id, buffer: oldName });
        bufferMessages.buffer = newName;
    }

    flag(name, val) {
        if (typeof val !== 'undefined') {
            this.state.$set(this.flags, name, val);
            return val;
        }

        return this.flags[name];
    }

    requestScrollback(_direction) {
        let direction = _direction || 'backward';
        let time = '';
        let chathistoryFuncName = 'before';

        // Going backwards takes the earliest message we already have and requests messages
        // before it. Going forward takes the last message we have and requests messages after
        // it.

        if (direction === 'backward') {
            let lastMessage = this.getMessages().reduce((earliest, current) => {
                let ignoreTypes = ['traffic', 'topic', 'connection', 'presence'];
                let validType = ignoreTypes.indexOf(earliest.type) === -1;
                if (validType && earliest.time && earliest.time < current.time) {
                    return earliest;
                }
                return current;
            }, this.getMessages()[0]);

            chathistoryFuncName = 'before';
            time = lastMessage ?
                new Date(lastMessage.time) :
                new Date();
        } else if (direction === 'forward') {
            let firstMessage = this.getMessages().reduce((latest, current) => {
                let ignoreTypes = ['traffic', 'topic', 'connection', 'presence'];
                let validType = ignoreTypes.indexOf(latest.type) === -1;
                if (validType && latest.time && latest.time > current.time) {
                    return latest;
                }
                return current;
            }, this.getMessages()[0]);

            chathistoryFuncName = 'after';
            time = firstMessage ?
                new Date(firstMessage.time) :
                new Date();
        } else {
            throw new Error('Invalid direction for requestScrollback(): ' + _direction);
        }

        let ircClient = this.getNetwork().ircClient;
        this.flags.is_requesting_chathistory = true;
        ircClient.chathistory[chathistoryFuncName](this.name, time).then((event) => {
            if (!event || event.commands.length === 0) {
                this.flags.chathistory_available = false;
            } else {
                this.flags.chathistory_available = true;
            }
        }).finally(() => {
            this.flags.is_requesting_chathistory = false;
        });
    }

    requestLatestScrollback() {
        let ircClient = this.getNetwork().ircClient;
        this.flags.is_requesting_chathistory = true;
        ircClient.chathistory.before(this.name, '*').finally(() => {
            this.flags.is_requesting_chathistory = false;
        });
    }

    markAsRead(delayed) {
        if (this.active_timeout) {
            clearTimeout(this.active_timeout);
            this.active_timeout = null;
        }
        if (delayed) {
            this.active_timeout = setTimeout(
                this.markAsRead.bind(this),
                10000,
                false
            );
        } else {
            this.last_read = Date.now();
            this.flag('highlight', false);

            // If running under a bouncer, set it on the server-side too
            let network = this.getNetwork();
            let allowedUpdate = !network ? false : this.isChannel() || this.isQuery();
            if (allowedUpdate && network.connection.bncname) {
                network.ircClient.bnc.bufferSeen(
                    network.connection.bncname,
                    this.name,
                    new Date(),
                );
            }
        }
    }

    incrementFlag(flagName) {
        this.flags[flagName] = (this.flags[flagName] || 0) + 1;
    }

    addUser(user) {
        this.addUserBatch(user);
    }

    removeUser(nick) {
        let userObj = this.state.getUser(this.networkid, nick);

        // A user could be queued to be added, so make sure it's not there as it
        // would just be added again. Eg. user joins/parts during a flood
        _.pull(this.addUserBatch.queue(), userObj);

        this.state.$delete(this.users, nick.toLowerCase());

        if (userObj) {
            delete userObj.buffers[this.id];
        }
    }

    clearUsers() {
        // Users could be queued to be added, so make sure to clear them as they
        // would just be added again. Eg. user joins/parts during a flood
        this.addUserBatch && this.addUserBatch.queue().splice(0);

        _.each(this.users, (userObj, nick) => {
            delete userObj.buffers[this.id];
        });

        this.state.$set(this, 'users', {});
    }

    addMessage(message) {
        this.addMessageBatch(message);
    }

    say(message, opts = {}) {
        let network = this.getNetwork();
        let newMessage = {
            time: Date.now(),
            nick: network.nick,
            message: message,
            type: opts.type || 'privmsg',
        };

        this.state.addMessage(this, newMessage);

        let fnNames = {
            privmsg: 'say',
            action: 'action',
            notice: 'notice',
        };
        let fnName = fnNames[opts.type] || 'say';
        network.ircClient[fnName](this.name, message);
    }

    join() {
        if (!this.isChannel()) {
            return;
        }

        let network = this.getNetwork();
        network.ircClient.join(this.name, this.key || '');
    }

    part(reason) {
        if (!this.isChannel()) {
            return;
        }

        let network = this.getNetwork();
        network.ircClient.part(this.name, reason || '');
    }

    scrollToMessage(id) {
        this.state.$emit('messagelist.scrollto', { id: id });
    }
}

/**
 * Batch up floods of addUsers for a huge performance gain.
 * Generally happens when reconnecting to a BNC
 */
function createUserBatch(bufferState) {
    let addSingleUser = (u) => {
        bufferState.state.$set(bufferState.users, u.nick.toLowerCase(), u);
    };
    let addMultipleUsers = (users) => {
        let o = _.clone(bufferState.users);
        users.forEach((u) => {
            o[u.nick.toLowerCase()] = u;
        });
        bufferState.users = o;
    };

    return batchedAdd(addSingleUser, addMultipleUsers);
}

/**
 * batch up floods of new messages for a huge performance gain
 */
function createMessageBatch(bufferState) {
    let addSingleMessage = (newMessage) => {
        bufferState.messagesObj.messages.push(newMessage);
        trimMessages();
        bufferState.message_count++;
    };
    let addMultipleMessages = (newMessages) => {
        bufferState.messagesObj.messages = bufferState.messagesObj.messages.concat(newMessages);
        trimMessages();
        bufferState.message_count++;
    };
    let trimMessages = () => {
        let scrollbackSize = bufferState.setting('scrollback_size');
        let length = bufferState.messagesObj.messages.length;

        if (bufferState.messagesObj.messages.length > scrollbackSize) {
            bufferState.messagesObj.messages.splice(0, length - scrollbackSize);
        }
    };

    return batchedAdd(addSingleMessage, addMultipleMessages);
}

// Update our user list status every 30seconds to get each users current away status
function maybeStartWhoLoop(bufferState) {
    let network = bufferState.state.getNetwork(bufferState.networkid);

    if (network.state === 'connected') {
        // network is connected start the loop if its needed
        nextLoop();
    } else {
        // Network is not coonnected. Wait until it is
        let on001 = (command, event, eventNetwork) => {
            if (eventNetwork === network) {
                bufferState.state.$off('irc.raw.001', on001);
                nextLoop();
            }
        };
        bufferState.state.$on('irc.raw.001', on001);
    }

    function nextLoop() {
        setTimeout(updateWhoStatusLoop, 30000);
    }

    function updateWhoStatusLoop() {
        network = bufferState.state.getNetwork(bufferState.networkid);

        // Make sure the network still exists
        if (!network) {
            return;
        }

        // Make sure the buffer still exists
        if (!network.bufferByName(bufferState.name)) {
            return;
        }

        let whoLoop = bufferState.setting('who_loop');
        let isJoined = bufferState.joined;
        let hasAwayNotify = network.ircClient.network.cap.isEnabled('away-notify');
        let networkConnected = network.state === 'connected';

        if (whoLoop && networkConnected && isJoined && !hasAwayNotify) {
            network.ircClient.who(bufferState.name, () => {
                nextLoop();
            });
        } else {
            nextLoop();
        }
    }
}
<commit_msg>Updated ti use the flag() helper.<commit_after>/** @module */

import Vue from 'vue';
import _ from 'lodash';
import { def } from './common';
import batchedAdd from '../batchedAdd';

let nextBufferId = 0;

/** The IRC buffer instance */
export default class BufferState {
    constructor(name, networkid, state, messageDict) {
        // Enumerable properties that become reactive under Vue
        this.id = nextBufferId++;
        this.networkid = networkid;
        this.name = name;
        this.topics = [];
        this.key = '';
        this.joined = false;
        this.enabled = true;
        this.created_at = null;
        this.users = Object.create(null);
        this.modes = Object.create(null);
        this.flags = {
            unread: 0,
            alert_on: 'default',
            has_opened: false,
            channel_badkey: false,
            chathistory_available: true,
            requested_modes: false,
            requested_banlist: false,
            is_requesting_chathistory: false,
        };
        this.settings = { };
        this.last_read = 0;
        this.active_timeout = null;
        this.message_count = 0;
        this.current_input = '';
        this.input_history = [];
        this.input_history_pos = 0;
        this.show_input = true;

        Vue.observable(this);

        // Some non-enumerable properties (vues $watch won't cover these properties)
        def(this, 'state', state, false);
        def(this, 'messageDict', messageDict, false);

        let messagesObj = {
            networkid: this.networkid,
            buffer: this.name,
            messages: [],
        };
        this.messageDict.push(messagesObj);
        def(this, 'messagesObj', messagesObj, false);

        def(this, 'addMessageBatch', createMessageBatch(this), false);
        def(this, 'addUserBatch', createUserBatch(this), false);

        // poll who to update away status if away-notify is not enabled
        if (this.isChannel()) {
            maybeStartWhoLoop(this);
        }
    }

    get topic() {
        return this.topics.length === 0 ?
            '' :
            this.topics[this.topics.length - 1];
    }

    set topic(newVal) {
        this.topics.push(newVal);
    }

    getNetwork() {
        return this.state.getNetwork(this.networkid);
    }

    getMessages() {
        let bufMessages = _.find(this.messageDict, {
            networkid: this.networkid,
            buffer: this.name,
        });

        return bufMessages ?
            bufMessages.messages :
            [];
    }

    isServer() {
        return this.name === '*';
    }

    isChannel() {
        let chanPrefixes = ['#', '&'];
        let ircNetwork = this.getNetwork().ircClient.network;
        if (ircNetwork && ircNetwork.options.CHANTYPES) {
            chanPrefixes = ircNetwork.options.CHANTYPES;
        }

        return chanPrefixes.indexOf(this.name[0]) > -1;
    }

    isQuery() {
        let chanPrefixes = ['#', '&'];
        let ircNetwork = this.getNetwork().ircClient.network;
        if (ircNetwork && ircNetwork.options.CHANTYPES) {
            chanPrefixes = ircNetwork.options.CHANTYPES;
        }

        return chanPrefixes.indexOf(this.name[0]) === -1 &&
            !this.isSpecial() &&
            !this.isServer();
    }

    isSpecial() {
        // Special buffer names (Usually controller queries, like *status or *raw).
        // Server buffer '*' is not included in this classification.
        let name = this.name;
        return name[0] === '*' && name.length > 1;
    }

    isUserAnOp(nick) {
        let user = this.state.getUser(this.networkid, nick);
        if (!user) {
            return false;
        }

        let userBufferInfo = user.buffers[this.id];
        if (!userBufferInfo) {
            return false;
        }

        let modes = userBufferInfo.modes;
        let opModes = ['Y', 'y', 'q', 'a', 'o', 'h'];
        let hasOp = _.find(modes, mode => opModes.indexOf(mode.toLowerCase()) > -1);

        return !!hasOp;
    }

    /**
     * Get a users prefix symbol on a buffer from its modes
     * @param {Object} user The user object
     */
    userModePrefix(user) {
        // The user may not be on the buffer
        if (!user.buffers[this.id]) {
            return '';
        }

        let modes = user.buffers[this.id].modes;
        if (modes.length === 0) {
            return '';
        }

        let network = this.getNetwork();
        let netPrefixes = network.ircClient.network.options.PREFIX;
        // Find the first (highest) netPrefix in the users buffer modes
        let prefix = _.find(netPrefixes, p => modes.indexOf(p.mode) > -1);

        return prefix ?
            prefix.symbol :
            '';
    }

    /**
     * Get a users mode on a buffer
     * @param user {Object} The user object
     */
    userMode(user) {
        // The user may not be on the buffer
        if (!user.buffers[this.id]) {
            return '';
        }

        let modes = user.buffers[this.id].modes;
        if (modes.length === 0) {
            return '';
        }

        let network = this.getNetwork();
        let netPrefixes = network.ircClient.network.options.PREFIX;
        // Find the first (highest) netPrefix in the users buffer modes
        let prefix = _.find(netPrefixes, p => modes.indexOf(p.mode) > -1);

        return prefix ?
            prefix.mode :
            '';
    }

    setting(name, val) {
        if (typeof val !== 'undefined') {
            this.state.$set(this.settings, name, val);
            return val;
        }

        // Check the buffer specific settings before reverting to global settings
        let result = typeof this.settings[name] !== 'undefined' ?
            this.settings[name] :
            this.state.setting('buffers.' + name);

        return result;
    }

    rename(newName) {
        let network = this.getNetwork();
        let oldName = this.name;
        let setActive = this.state.getActiveBuffer() === this;

        this.name = newName;
        if (setActive) {
            this.state.setActiveBuffer(network.id, newName);
        }

        // update the buffer name on our messages
        let bufferMessages = _.find(this.messageDict, { networkid: network.id, buffer: oldName });
        bufferMessages.buffer = newName;
    }

    flag(name, val) {
        if (typeof val !== 'undefined') {
            this.state.$set(this.flags, name, val);
            return val;
        }

        return this.flags[name];
    }

    requestScrollback(_direction) {
        let direction = _direction || 'backward';
        let time = '';
        let chathistoryFuncName = 'before';

        // Going backwards takes the earliest message we already have and requests messages
        // before it. Going forward takes the last message we have and requests messages after
        // it.

        if (direction === 'backward') {
            let lastMessage = this.getMessages().reduce((earliest, current) => {
                let ignoreTypes = ['traffic', 'topic', 'connection', 'presence'];
                let validType = ignoreTypes.indexOf(earliest.type) === -1;
                if (validType && earliest.time && earliest.time < current.time) {
                    return earliest;
                }
                return current;
            }, this.getMessages()[0]);

            chathistoryFuncName = 'before';
            time = lastMessage ?
                new Date(lastMessage.time) :
                new Date();
        } else if (direction === 'forward') {
            let firstMessage = this.getMessages().reduce((latest, current) => {
                let ignoreTypes = ['traffic', 'topic', 'connection', 'presence'];
                let validType = ignoreTypes.indexOf(latest.type) === -1;
                if (validType && latest.time && latest.time > current.time) {
                    return latest;
                }
                return current;
            }, this.getMessages()[0]);

            chathistoryFuncName = 'after';
            time = firstMessage ?
                new Date(firstMessage.time) :
                new Date();
        } else {
            throw new Error('Invalid direction for requestScrollback(): ' + _direction);
        }

        let ircClient = this.getNetwork().ircClient;
        this.flag('is_requesting_chathistory', true);
        ircClient.chathistory[chathistoryFuncName](this.name, time).then((event) => {
            if (!event || event.commands.length === 0) {
                this.flag('chathistory_available', false);
            } else {
                this.flag('chathistory_available', true);
            }
        }).finally(() => {
            this.flag('is_requesting_chathistory', false);
        });
    }

    requestLatestScrollback() {
        let ircClient = this.getNetwork().ircClient;
        this.flag('is_requesting_chathistory', true);
        ircClient.chathistory.before(this.name, '*').finally(() => {
            this.flag('is_requesting_chathistory', false);
        });
    }

    markAsRead(delayed) {
        if (this.active_timeout) {
            clearTimeout(this.active_timeout);
            this.active_timeout = null;
        }
        if (delayed) {
            this.active_timeout = setTimeout(
                this.markAsRead.bind(this),
                10000,
                false
            );
        } else {
            this.last_read = Date.now();
            this.flag('highlight', false);

            // If running under a bouncer, set it on the server-side too
            let network = this.getNetwork();
            let allowedUpdate = !network ? false : this.isChannel() || this.isQuery();
            if (allowedUpdate && network.connection.bncname) {
                network.ircClient.bnc.bufferSeen(
                    network.connection.bncname,
                    this.name,
                    new Date(),
                );
            }
        }
    }

    incrementFlag(flagName) {
        this.flags[flagName] = (this.flags[flagName] || 0) + 1;
    }

    addUser(user) {
        this.addUserBatch(user);
    }

    removeUser(nick) {
        let userObj = this.state.getUser(this.networkid, nick);

        // A user could be queued to be added, so make sure it's not there as it
        // would just be added again. Eg. user joins/parts during a flood
        _.pull(this.addUserBatch.queue(), userObj);

        this.state.$delete(this.users, nick.toLowerCase());

        if (userObj) {
            delete userObj.buffers[this.id];
        }
    }

    clearUsers() {
        // Users could be queued to be added, so make sure to clear them as they
        // would just be added again. Eg. user joins/parts during a flood
        this.addUserBatch && this.addUserBatch.queue().splice(0);

        _.each(this.users, (userObj, nick) => {
            delete userObj.buffers[this.id];
        });

        this.state.$set(this, 'users', {});
    }

    addMessage(message) {
        this.addMessageBatch(message);
    }

    say(message, opts = {}) {
        let network = this.getNetwork();
        let newMessage = {
            time: Date.now(),
            nick: network.nick,
            message: message,
            type: opts.type || 'privmsg',
        };

        this.state.addMessage(this, newMessage);

        let fnNames = {
            privmsg: 'say',
            action: 'action',
            notice: 'notice',
        };
        let fnName = fnNames[opts.type] || 'say';
        network.ircClient[fnName](this.name, message);
    }

    join() {
        if (!this.isChannel()) {
            return;
        }

        let network = this.getNetwork();
        network.ircClient.join(this.name, this.key || '');
    }

    part(reason) {
        if (!this.isChannel()) {
            return;
        }

        let network = this.getNetwork();
        network.ircClient.part(this.name, reason || '');
    }

    scrollToMessage(id) {
        this.state.$emit('messagelist.scrollto', { id: id });
    }
}

/**
 * Batch up floods of addUsers for a huge performance gain.
 * Generally happens when reconnecting to a BNC
 */
function createUserBatch(bufferState) {
    let addSingleUser = (u) => {
        bufferState.state.$set(bufferState.users, u.nick.toLowerCase(), u);
    };
    let addMultipleUsers = (users) => {
        let o = _.clone(bufferState.users);
        users.forEach((u) => {
            o[u.nick.toLowerCase()] = u;
        });
        bufferState.users = o;
    };

    return batchedAdd(addSingleUser, addMultipleUsers);
}

/**
 * batch up floods of new messages for a huge performance gain
 */
function createMessageBatch(bufferState) {
    let addSingleMessage = (newMessage) => {
        bufferState.messagesObj.messages.push(newMessage);
        trimMessages();
        bufferState.message_count++;
    };
    let addMultipleMessages = (newMessages) => {
        bufferState.messagesObj.messages = bufferState.messagesObj.messages.concat(newMessages);
        trimMessages();
        bufferState.message_count++;
    };
    let trimMessages = () => {
        let scrollbackSize = bufferState.setting('scrollback_size');
        let length = bufferState.messagesObj.messages.length;

        if (bufferState.messagesObj.messages.length > scrollbackSize) {
            bufferState.messagesObj.messages.splice(0, length - scrollbackSize);
        }
    };

    return batchedAdd(addSingleMessage, addMultipleMessages);
}

// Update our user list status every 30seconds to get each users current away status
function maybeStartWhoLoop(bufferState) {
    let network = bufferState.state.getNetwork(bufferState.networkid);

    if (network.state === 'connected') {
        // network is connected start the loop if its needed
        nextLoop();
    } else {
        // Network is not coonnected. Wait until it is
        let on001 = (command, event, eventNetwork) => {
            if (eventNetwork === network) {
                bufferState.state.$off('irc.raw.001', on001);
                nextLoop();
            }
        };
        bufferState.state.$on('irc.raw.001', on001);
    }

    function nextLoop() {
        setTimeout(updateWhoStatusLoop, 30000);
    }

    function updateWhoStatusLoop() {
        network = bufferState.state.getNetwork(bufferState.networkid);

        // Make sure the network still exists
        if (!network) {
            return;
        }

        // Make sure the buffer still exists
        if (!network.bufferByName(bufferState.name)) {
            return;
        }

        let whoLoop = bufferState.setting('who_loop');
        let isJoined = bufferState.joined;
        let hasAwayNotify = network.ircClient.network.cap.isEnabled('away-notify');
        let networkConnected = network.state === 'connected';

        if (whoLoop && networkConnected && isJoined && !hasAwayNotify) {
            network.ircClient.who(bufferState.name, () => {
                nextLoop();
            });
        } else {
            nextLoop();
        }
    }
}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------

const assertType = require('folktale/helpers/assert-type');
const assertFunction = require('folktale/helpers/assert-function');
const { data, derivations } = require('folktale/core/adt');
const provideAliases = require('folktale/helpers/provide-fantasy-land-aliases');
const warnDeprecation = require('folktale/helpers/warn-deprecation');
const adtMethods = require('folktale/helpers/define-adt-methods');
const extend = require('folktale/helpers/extend');

const { equality, debugRepresentation, serialization } = derivations;

/*~ stability: unstable */
const Maybe = data('folktale:Data.Maybe', {
  /*~
   * type: |
   *   forall a: () => Maybe a
   */
  Nothing() {
  },

  /*~
   * type: |
   *   forall a: (a) => Maybe a
   */
  Just(value) {
    return { value };
  }
}).derive(equality, debugRepresentation, serialization);

const { Nothing, Just } = Maybe;
const assertMaybe = assertType(Maybe);

extend(Just.prototype, {
  /*~
   * isRequired: true
   * type: |
   *   forall a: get (Maybe a) => a
   */
  get value() {
    throw new TypeError('`value` can’t be accessed in an abstract instance of Maybe.Just');
  }
});

/*~~belongsTo: Maybe */
adtMethods(Maybe, {
  /*~
   * type: |
   *   forall a, b: (Maybe a).((a) => b) => Maybe b
   */
  map: {
    /*~*/
    Nothing: function map(transformation) {
      assertFunction('Maybe.Nothing#map', transformation);
      return this;
    },

    /*~*/
    Just: function map(transformation) {
      assertFunction('Maybe.Just#map', transformation);
      return Just(transformation(this.value));
    }
  },

  /*~
   * type: |
   *   forall a, b: (Maybe (a) => b).(Maybe a) => Maybe b
   */
  apply: {
    /*~*/
    Nothing: function apply(aMaybe) {
      assertMaybe('Maybe.Nothing#apply', aMaybe);
      return this;
    },

    /*~*/
    Just: function apply(aMaybe) {
      assertMaybe('Maybe.Just#apply', aMaybe);
      return aMaybe.map(this.value);
    }
  },

  /*~
   * type: |
   *   forall a, b: (Maybe a).((a) => Maybe b) => Maybe b
   */
  chain: {
    /*~*/
    Nothing: function chain(transformation) {
      assertFunction('Maybe.Nothing#chain', transformation);
      return this;
    },

    /*~*/
    Just: function chain(transformation) {
      assertFunction('Maybe.Just#chain', transformation);
      return transformation(this.value);
    }
  },

  /*~
   * type: |
   *   forall a: (Maybe a).() => a :: (throws TypeError)
   */
  unsafeGet: {
    /*~*/
    Nothing: function unsafeGet() {
      throw new TypeError(`Can't extract the value of a Nothing.

    Since Nothing holds no values, it's not possible to extract one from them.
    You might consider switching from Maybe#get to Maybe#getOrElse, or some other method
    that is not partial.
      `);
    },

    /*~*/
    Just: function unsafeGet() {
      return this.value;
    }
  },

  /*~
   * type: |
   *   forall a: (Maybe a).(a) => a
   */
  getOrElse: {
    /*~*/
    Nothing: function getOrElse(_default) {
      return _default;
    },

    /*~*/
    Just: function getOrElse(_default) {
      return this.value;
    }
  },

  /*~
   * type: |
   *   forall a: (Maybe a).((a) => Maybe a) => Maybe a
   */
  orElse: {
    /*~*/
    Nothing: function orElse(handler) {
      assertFunction('Maybe.Nothing#orElse', handler);
      return handler(this.value);
    },

    /*~*/
    Just: function orElse(handler) {
      assertFunction('Maybe.Nothing#orElse', handler);
      return this;
    }
  },

  /*~
   * deprecated:
   *   since: 2.0.0
   *   replacedBy: .matchWith(pattern)
   *
   * type: |
   *   forall a, b:
   *     (Maybe a).({
   *       Nothing: () => b,
   *       Just: (a) => b
   *     }) => b
   */
  cata: {
    /*~*/
    Nothing: function cata(pattern) {
      warnDeprecation('`.cata(pattern)` is deprecated. Use `.matchWith(pattern)` instead.');
      return pattern.Nothing();
    },

    /*~*/
    Just: function cata(pattern) {
      warnDeprecation('`.cata(pattern)` is deprecated. Use `.matchWith(pattern)` instead.');
      return pattern.Just(this.value);
    }
  }
});

Object.assign(Maybe, {
  /*~
   * type: |
   *   forall a: (a) => Maybe a
   */
  of(value) {
    return Just(value);
  },

  /*~
   * deprecated:
   *   since: 2.0.0
   *   replacedBy: .unsafeGet()
   * type: |
   *   forall a: (Maybe a).() => a :: (throws TypeError)
   */
  'get'() {
    warnDeprecation('`.get()` is deprecated, and has been renamed to `.unsafeGet()`.');
    return this.unsafeGet();
  },

  /*~
   * type: |
   *   forall a, b: (Maybe a).(b) => Result b a
   */
  toResult(fallbackValue) {
    return require('folktale/data/conversions/maybe-to-result')(this, fallbackValue);
  },

  /*~
   * type: |
   *   forall a, b: (Maybe a).(b) => Result b a
   */
  toValidation(fallbackValue) {
    return require('folktale/data/conversions/maybe-to-validation')(this, fallbackValue);
  }
});

provideAliases(Just.prototype);
provideAliases(Nothing.prototype);
provideAliases(Maybe);

module.exports = Maybe;
<commit_msg>(new maybe) Adds .fold to Maybe<commit_after>//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------

const assertType = require('folktale/helpers/assert-type');
const assertFunction = require('folktale/helpers/assert-function');
const { data, derivations } = require('folktale/core/adt');
const provideAliases = require('folktale/helpers/provide-fantasy-land-aliases');
const warnDeprecation = require('folktale/helpers/warn-deprecation');
const adtMethods = require('folktale/helpers/define-adt-methods');
const extend = require('folktale/helpers/extend');

const { equality, debugRepresentation, serialization } = derivations;

/*~ stability: unstable */
const Maybe = data('folktale:Data.Maybe', {
  /*~
   * type: |
   *   forall a: () => Maybe a
   */
  Nothing() {
  },

  /*~
   * type: |
   *   forall a: (a) => Maybe a
   */
  Just(value) {
    return { value };
  }
}).derive(equality, debugRepresentation, serialization);

const { Nothing, Just } = Maybe;
const assertMaybe = assertType(Maybe);

extend(Just.prototype, {
  /*~
   * isRequired: true
   * type: |
   *   forall a: get (Maybe a) => a
   */
  get value() {
    throw new TypeError('`value` can’t be accessed in an abstract instance of Maybe.Just');
  }
});

/*~~belongsTo: Maybe */
adtMethods(Maybe, {
  /*~
   * type: |
   *   forall a, b: (Maybe a).((a) => b) => Maybe b
   */
  map: {
    /*~*/
    Nothing: function map(transformation) {
      assertFunction('Maybe.Nothing#map', transformation);
      return this;
    },

    /*~*/
    Just: function map(transformation) {
      assertFunction('Maybe.Just#map', transformation);
      return Just(transformation(this.value));
    }
  },

  /*~
   * type: |
   *   forall a, b: (Maybe (a) => b).(Maybe a) => Maybe b
   */
  apply: {
    /*~*/
    Nothing: function apply(aMaybe) {
      assertMaybe('Maybe.Nothing#apply', aMaybe);
      return this;
    },

    /*~*/
    Just: function apply(aMaybe) {
      assertMaybe('Maybe.Just#apply', aMaybe);
      return aMaybe.map(this.value);
    }
  },

  /*~
   * type: |
   *   forall a, b: (Maybe a).((a) => Maybe b) => Maybe b
   */
  chain: {
    /*~*/
    Nothing: function chain(transformation) {
      assertFunction('Maybe.Nothing#chain', transformation);
      return this;
    },

    /*~*/
    Just: function chain(transformation) {
      assertFunction('Maybe.Just#chain', transformation);
      return transformation(this.value);
    }
  },

  /*~
   * type: |
   *   forall a: (Maybe a).() => a :: (throws TypeError)
   */
  unsafeGet: {
    /*~*/
    Nothing: function unsafeGet() {
      throw new TypeError(`Can't extract the value of a Nothing.

    Since Nothing holds no values, it's not possible to extract one from them.
    You might consider switching from Maybe#get to Maybe#getOrElse, or some other method
    that is not partial.
      `);
    },

    /*~*/
    Just: function unsafeGet() {
      return this.value;
    }
  },

  /*~
   * type: |
   *   forall a: (Maybe a).(a) => a
   */
  getOrElse: {
    /*~*/
    Nothing: function getOrElse(_default) {
      return _default;
    },

    /*~*/
    Just: function getOrElse(_default) {
      return this.value;
    }
  },

  /*~
   * type: |
   *   forall a: (Maybe a).((a) => Maybe a) => Maybe a
   */
  orElse: {
    /*~*/
    Nothing: function orElse(handler) {
      assertFunction('Maybe.Nothing#orElse', handler);
      return handler(this.value);
    },

    /*~*/
    Just: function orElse(handler) {
      assertFunction('Maybe.Nothing#orElse', handler);
      return this;
    }
  },

  /*~
   * deprecated:
   *   since: 2.0.0
   *   replacedBy: .matchWith(pattern)
   *
   * type: |
   *   forall a, b:
   *     (Maybe a).({
   *       Nothing: () => b,
   *       Just: (a) => b
   *     }) => b
   */
  cata: {
    /*~*/
    Nothing: function cata(pattern) {
      warnDeprecation('`.cata(pattern)` is deprecated. Use `.matchWith(pattern)` instead.');
      return pattern.Nothing();
    },

    /*~*/
    Just: function cata(pattern) {
      warnDeprecation('`.cata(pattern)` is deprecated. Use `.matchWith(pattern)` instead.');
      return pattern.Just(this.value);
    }
  },

  /*~
   * type: |
   *   forall a, b: (Maybe a).(() => b, (a) => b) => b
   */
  fold: {
    /*~*/
    Nothing: function(transformNothing, transformJust) {
      assertFunction('Maybe.Nothing#fold', transformNothing);
      assertFunction('Maybe.Nothing#fold', transformJust);
      return transformNothing();
    },

    /*~*/
    Just: function(transformNothing, transformJust) {
      assertFunction('Maybe.Just#fold', transformNothing);
      assertFunction('Maybe.Just#fold', transformJust);
      return transformJust(this.value);
    }
  }
});

Object.assign(Maybe, {
  /*~
   * type: |
   *   forall a: (a) => Maybe a
   */
  of(value) {
    return Just(value);
  },

  /*~
   * deprecated:
   *   since: 2.0.0
   *   replacedBy: .unsafeGet()
   * type: |
   *   forall a: (Maybe a).() => a :: (throws TypeError)
   */
  'get'() {
    warnDeprecation('`.get()` is deprecated, and has been renamed to `.unsafeGet()`.');
    return this.unsafeGet();
  },

  /*~
   * type: |
   *   forall a, b: (Maybe a).(b) => Result b a
   */
  toResult(fallbackValue) {
    return require('folktale/data/conversions/maybe-to-result')(this, fallbackValue);
  },

  /*~
   * type: |
   *   forall a, b: (Maybe a).(b) => Result b a
   */
  toValidation(fallbackValue) {
    return require('folktale/data/conversions/maybe-to-validation')(this, fallbackValue);
  }
});

provideAliases(Just.prototype);
provideAliases(Nothing.prototype);
provideAliases(Maybe);

module.exports = Maybe;
<|endoftext|>


<commit_before>export default {
  name: "AuthAccount",
  ogit: "ogit/Auth/Account",
  required: {
    name: "ogit/name",
    status: "ogit/status",
  },
  optional: {
    roles: {
      src: "/roles",
      type: "list",
    },
  },
};
<commit_msg>HD-344: fix formatting<commit_after>export default {
    name: "AuthAccount",
    ogit: "ogit/Auth/Account",
    required: {
        name: "ogit/name",
        status: "ogit/status"
    },
    optional: {
        roles: {
            src: "/roles",
            type: "list"
        }
    }
};
<|endoftext|>


<commit_before>import * as most from 'most'
import stream from 'jsonmvc-helper-stream'

import getValue from './../fns/getValue'
import bubbleTo from './../fns/bubbleTo'
import parsePatch from './../fns/parsePatch'
import {
  numberRegExpStr,
  textRegExpStr,
  objRegExpStr,
  arrayRegExpStr,
  htmlAttrRegExpStr,
  pathOptRegExpStr
} from './../fns/parsePatch'

const numberRegExp = new RegExp('^' + numberRegExpStr + '$', 'g')
const objRegExp = new RegExp('^' + objRegExpStr, 'g')
const arrayRegExp = new RegExp('^' + arrayRegExpStr, 'g')
const textRegExp = new RegExp('^' + textRegExpStr + '$', 'g')
const htmlAttrRegExp = new RegExp('^' + htmlAttrRegExpStr + '$', 'g')
const pathRegExp = new RegExp('^' + pathOptRegExpStr + '$', 'g')

const controller = {
  args: {
    events: '/config/ui/events'
  },
  fn: stream
    .filter(x => !!document && !!document.body)
    .chain(x => {
      let events = x.events
      let streams = Object.keys(events).map(x => {
        let e = events[x]
        let stream = most.fromEvent(x, document.body)

        if (e.debounce) {
          stream = stream.debounce(e.debounce)
        }

        return stream
      })

      return most.mergeArray(streams)
    })
    .map(e => {
      return {
        el: bubbleTo('[data-patch]', e),
        e: e
      }
    })
    .filter(x => !!x.el)
    .map((x, lib) => {
      if (x.el.hasAttribute('href')) {
        x.e.preventDefault()
      }

      let el = x.el

      let str = el.getAttribute('data-patch')

      let patches = parsePatch(str)

      // Parse and convert the value
      patches = patches.map(x => {
        if (!x.value) {
          return x
        }

        let firstChar = x.value[0]

        let match = {
          obj: x.value.match(objRegExp) !== null,
          array: x.value.match(arrayRegExp) !== null,
          htmlAttr: x.value.match(htmlAttrRegExp) !== null,
          path: x.value.match(pathRegExp) !== null,
          text: x.value.match(textRegExp) !== null,
          number: x.value.match(numberRegExp) !== null
        }

        if (match.obj || match.array) {
          try {
            x.value = JSON.parse(x.value)
          } catch (e) {
            console.error('Tried to JSON.parse ', x.value, ' from the patch ', x, ' and got ', e)
            throw e
          }
        } else if (match.htmlAttr) {
          let prop = x.value.replace(/^attr\./, '')
          x.value = getValue(el, prop)
        } else if (match.path) {
          x.value = lib.get(x.value)
        } else if (match.text) {
          x.value = x.value.substr(1, x.value.length - 2)
        } else if (match.number) {
          x.value = parseFloat(x.value)
        } else {
          throw new Error('Patch value not recognized "' + x.value + '". It should start and end with {..}, [..], \'..\', "..", or be a number')
        }

        return x
      })

      return patches
    })

// @TODO: Timestamp events by their exact time relative to the /time/ms time
// in order to avoid having two events at the same timestamp but in reality they
// were a smaller distance than the increment chosen for the /time/ms
//
// A better decision is to use performance.now() so that the time recording of events
// reflects the moment since the application started running which is much more
// appropiate than using timestamps. The only caveat though is to store the start
// timestamp.

}

export default controller
<commit_msg>Fix jsonmvc-module-ui patch parse throwing errors.<commit_after>import * as most from 'most'
import stream from 'jsonmvc-helper-stream'

import getValue from './../fns/getValue'
import bubbleTo from './../fns/bubbleTo'
import parsePatch from './../fns/parsePatch'
import {
  numberRegExpStr,
  textRegExpStr,
  objRegExpStr,
  arrayRegExpStr,
  htmlAttrRegExpStr,
  pathOptRegExpStr
} from './../fns/parsePatch'

const numberRegExp = new RegExp('^' + numberRegExpStr + '$', 'g')
const objRegExp = new RegExp('^' + objRegExpStr, 'g')
const arrayRegExp = new RegExp('^' + arrayRegExpStr, 'g')
const textRegExp = new RegExp('^' + textRegExpStr + '$', 'g')
const htmlAttrRegExp = new RegExp('^' + htmlAttrRegExpStr + '$', 'g')
const pathRegExp = new RegExp('^' + pathOptRegExpStr + '$', 'g')

const controller = {
  args: {
    events: '/config/ui/events'
  },
  fn: stream
    .filter(x => !!document && !!document.body)
    .chain(x => {
      let events = x.events
      let streams = Object.keys(events).map(x => {
        let e = events[x]
        let stream = most.fromEvent(x, document.body)

        if (e.debounce) {
          stream = stream.debounce(e.debounce)
        }

        return stream
      })

      return most.mergeArray(streams)
    })
    .map(e => {
      return {
        el: bubbleTo('[data-patch]', e),
        e: e
      }
    })
    .filter(x => !!x.el)
    .map((x, lib) => {
      if (x.el.hasAttribute('href')) {
        x.e.preventDefault()
      }

      let el = x.el

      let str = el.getAttribute('data-patch')

      let patches
      try {
        patches = parsePatch(str)
      } catch (e) {
        console.error('Patch parse error', e)
        return []
      }

      // Parse and convert the value
      patches = patches.map(x => {
        if (!x.value) {
          return x
        }

        let firstChar = x.value[0]

        let match = {
          obj: x.value.match(objRegExp) !== null,
          array: x.value.match(arrayRegExp) !== null,
          htmlAttr: x.value.match(htmlAttrRegExp) !== null,
          path: x.value.match(pathRegExp) !== null,
          text: x.value.match(textRegExp) !== null,
          number: x.value.match(numberRegExp) !== null
        }

        if (match.obj || match.array) {
          try {
            x.value = JSON.parse(x.value)
          } catch (e) {
            console.error('Tried to JSON.parse ', x.value, ' from the patch ', x, ' and got ', e)
            throw e
          }
        } else if (match.htmlAttr) {
          let prop = x.value.replace(/^attr\./, '')
          x.value = getValue(el, prop)
        } else if (match.path) {
          x.value = lib.get(x.value)
        } else if (match.text) {
          x.value = x.value.substr(1, x.value.length - 2)
        } else if (match.number) {
          x.value = parseFloat(x.value)
        } else {
          console.error('Patch value not recognized "' + x.value + '". It should start and end with {..}, [..], \'..\', "..", or be a number')
        }

        return x
      })

      return patches
    })
    .filter(x => x && x.length > 0)

// @TODO: Timestamp events by their exact time relative to the /time/ms time
// in order to avoid having two events at the same timestamp but in reality they
// were a smaller distance than the increment chosen for the /time/ms
//
// A better decision is to use performance.now() so that the time recording of events
// reflects the moment since the application started running which is much more
// appropiate than using timestamps. The only caveat though is to store the start
// timestamp.

}

export default controller
<|endoftext|>


<commit_before>var AlphaReportService = require('./alpha_report');

var ConfirmedReport = module.exports = function(models, io, log) {
	var me = this;

	me.logger = log;
	me.models = models;
	me.io = io;
};

ConfirmedReport.prototype.listFlattened = function(params, listFlatCallback) {
	var me = this;

	me.list(params, function(err, reports) {
		//FIXME handle err;
		//handle none;
		async.each(reports, function(report, callback) {
			me.flattenConfirmedReport(report, function(err, updatedReport) {
				if(!err) {
					report = updatedReport;
				}
				callback(err);
			})
		}, function(err) {
			listFlatCallback(err, reports);
		});
	});
};

ConfirmedReport.prototype.list = function(params, listCallback) {
	var me = this;

	me.models.confirmedReport.find(params, function(err, confirmedReports) {
		if(err) {
			var errMsg = "Error in retrieving list of confirmed reports";
			me.logger.error("confirmeedReport: " + errMsg, err);
		}

		listCallback(err, confirmedReports);
	});
};

ConfirmedReport.prototype.getFlattened = function(id, callback) {
	var me = this;

	me.get(id, function(err, report) {
		//FIXME handle err
		me.flattenConfirmedReport(report, callback);
	})
};

ConfirmedReport.prototype.get = function(id, getCallback) {
	var me = this;

	me.models.confirmedReport.findById(id, function(err, confirmedReport) {
		if(err) {
			var errMsg = "Error in retrieving confirmed report";
			me.logger.error("confirmeedReport: " + errMsg, err);
		}

		getCallback(err, confirmedReport);
	});
};

ConfirmedReport.prototype.flattenConfirmedReport = function(report, callback) {
	var me = this;

	var fieldsToFlatten = ['alpha_report_id', 'target_event_id', 'profile_id', 'assertions']

	async.each(fieldsToFlatten, function(field, fieldCallback) {
		if(field === 'assertions' && report.assertions.length > 0) {
			var flattenedAssertions = [];
			async.each(report.assertions, function(assertion, assertionCallback) {
				me.flattenField(report, assertion, function(err, flattenedField) {
					if(err) {
						assertionCallback(err)
					} else {
						flattenedAssertions.put(flattenField);
						assertionCallback();
					}
				});
			}, function(err) {
				report.assertions = flattenedAssertions;
				fieldCallback(err);
			});
		} else {
			if(typeof(report[field]) !== 'undefined' && report[field] != null) {
				me.flattenField(report, field, function(err, flattenedField) {
					if(err) {
						fieldCallback(err)
					} else {
						report[field] = flattenField;
						fieldCallback();
					}
				});
			}
		}
	},function(err) {
		callback(err, report)
	}
};

ConfirmedReport.prototype.flattenField = function(report, field, callback) {
	if(field === 'alpha_report_id') {
		var alphaReportService = new AlphaReportService(me.models, me.io, me.logger);

		alphaReportService.get(report.alpha_report_id, callback);
	} else if(field === 'target_event_id') {
		//need service;
		//temp callback to allow for running;
		callback(err, report.target_event_id);
	} else if(field == 'profile_id') {
		//need to update service
		//temp callback to allow for running;
		callback(err, report.profile_id);
	}
};

ConfirmedReport.prototype.create = function(data, createCallback) {
	var me = this;

	//validateConfirmedReport(data, function(valid) {
	//	if (valid.valid) {
	//		logger.info("Valid AlphaReport");
			var newConfirmedReport = new me.models.confirmedReport(data);
			newConfirmedReport.save(function(err){
				if(err){
					me.logger.error('Error saving confirmedReport ', err);
				}
				createCallback(err,/* valid,*/ newConfirmedReport);
			});
	//	}
	//	else {
	//		saveCallback(undefined, valid, data);
	//	}
	//});
};

ConfirmedReport.prototype.update = function(id, data, updateCallback) {
	var me = this;

	me.get(id, function(err, confirmedReport) {
		if(err) {
			me.logger.error("Error getting confirmed report for updating;", err);
			updateCallback(err, null);
		} else if(typeof(confirmedReport) === 'undefined' || !confirmedReport) {
			me.logger.error("Could not find a confirmed report for updating with id " + id, err);
			updateCallback(err, null);
		} else {
			async.each(Object.keys(data), function(key, eachCallback) {
				confirmedReport[key] = data[key];
				eachCallback();
			}, function(err) {
				//validate
				confirmedReport.save(function(err) {
					updateCallback(err, confirmedReport);
				});
			});
		}
	});
};

ConfirmedReport.prototype.delete = function(paramsObject, deleteCallback) {
	var me = this;

	me.models.confirmedReport.remove(paramsObject, deleteCallback);
};<commit_msg>Adding retrieval of profile object for flat get and list<commit_after>var async = require('async');

var AlphaReportService = require('./alpha_report');
var ProfileService = require('./profile');

var ConfirmedReport = module.exports = function(models, io, log) {
	var me = this;

	me.logger = log;
	me.models = models;
	me.io = io;
};

ConfirmedReport.prototype.listFlattened = function(params, listFlatCallback) {
	var me = this;

	me.list(params, function(err, reports) {
		//FIXME handle err;
		//handle none;
		async.each(reports, function(report, callback) {
			me.flattenConfirmedReport(report, function(err, updatedReport) {
				if(!err) {
					report = updatedReport;
				}
				callback(err);
			});
		}, function(err) {
			listFlatCallback(err, reports);
		});
	});
};

ConfirmedReport.prototype.list = function(params, listCallback) {
	var me = this;

	me.models.confirmedReport.find(params, function(err, confirmedReports) {
		if(err) {
			var errMsg = "Error in retrieving list of confirmed reports";
			me.logger.error("confirmeedReport: " + errMsg, err);
		}

		listCallback(err, confirmedReports);
	});
};

ConfirmedReport.prototype.getFlattened = function(id, callback) {
	var me = this;

	me.get(id, function(err, report) {
		//FIXME handle err
		me.flattenConfirmedReport(report, callback);
	});
};

ConfirmedReport.prototype.get = function(id, getCallback) {
	var me = this;

	me.models.confirmedReport.findById(id, function(err, confirmedReport) {
		if(err) {
			var errMsg = "Error in retrieving confirmed report";
			me.logger.error("confirmeedReport: " + errMsg, err);
		}

		getCallback(err, confirmedReport);
	});
};

ConfirmedReport.prototype.flattenConfirmedReport = function(report, callback) {
	var me = this;

	var fieldsToFlatten = ['alpha_report_id', 'target_event_id', 'profile_id', 'assertions'];

	async.each(fieldsToFlatten, function(field, fieldCallback) {
		if(field === 'assertions' && report.assertions.length > 0) {
			var flattenedAssertions = [];
			async.each(report.assertions, function(assertion, assertionCallback) {
				me.flattenField(report, assertion, function(err, flattenedField) {
					if(err) {
						assertionCallback(err);
					} else {
						flattenedAssertions.put(flattenedField);
						assertionCallback();
					}
				});
			}, function(err) {
				report.assertions = flattenedAssertions;
				fieldCallback(err);
			});
		} else {
			if(typeof(report[field]) !== 'undefined' && report[field] !== null) {
				me.flattenField(report, field, function(err, flattenedField) {
					if(err) {
						fieldCallback(err);
					} else {
						report[field] = flattenedField;
						fieldCallback();
					}
				});
			}
		}
	},function(err) {
		callback(err, report);
	});
};

ConfirmedReport.prototype.flattenField = function(report, field, callback) {
	var me = this;

	if(field === 'alpha_report_id') {
		var alphaReportService = new AlphaReportService(me.models, me.io, me.logger);

		alphaReportService.get(report.alpha_report_id, callback);
	} else if(field === 'target_event_id') {
		//need service;
		//temp callback to allow for running;
		callback(null, report.target_event_id);
	} else if(field === 'profile_id') {
		var profileService = new ProfileService(me.models, me.io, me.logger);
		profileService.get(report.profile_id, callback);
	}
};

ConfirmedReport.prototype.create = function(data, createCallback) {
	var me = this;

	//validateConfirmedReport(data, function(valid) {
	//	if (valid.valid) {
	//		logger.info("Valid AlphaReport");
			var newConfirmedReport = new me.models.confirmedReport(data);
			newConfirmedReport.save(function(err){
				if(err){
					me.logger.error('Error saving confirmedReport ', err);
				}
				createCallback(err,/* valid,*/ newConfirmedReport);
			});
	//	}
	//	else {
	//		saveCallback(undefined, valid, data);
	//	}
	//});
};

ConfirmedReport.prototype.update = function(id, data, updateCallback) {
	var me = this;

	me.get(id, function(err, confirmedReport) {
		if(err) {
			me.logger.error("Error getting confirmed report for updating;", err);
			updateCallback(err, null);
		} else if(typeof(confirmedReport) === 'undefined' || !confirmedReport) {
			me.logger.error("Could not find a confirmed report for updating with id " + id, err);
			updateCallback(err, null);
		} else {
			async.each(Object.keys(data), function(key, eachCallback) {
				confirmedReport[key] = data[key];
				eachCallback();
			}, function(err) {
				//validate
				confirmedReport.save(function(err) {
					updateCallback(err, confirmedReport);
				});
			});
		}
	});
};

ConfirmedReport.prototype.delete = function(paramsObject, deleteCallback) {
	var me = this;

	me.models.confirmedReport.remove(paramsObject, deleteCallback);
};<|endoftext|>