<commit_before>(function() {
    var psaApp = new Vue({
            el: "#mainPsaApp",
            data: {
                userId: "",
                userIdKey: "psaTracker_currentUser",
                clinicalCode: "666",
                clinicalDisplay: "psa",
                clinicalSystem: "http://us.truenth.org/clinical-codes",
                loading: false,
                addErrorMessage: "",
                noResultMessage: this.i18next.t("No PSA Result To Display"),
                newItem: {
                    id: "",
                    result: "",
                    date:"",
                    edit: false
                },
                headers: [
                    this.i18next.t("PSA (ng/ml)"),
                    this.i18next.t("Date")
                ],
                items: [],
                editTitle: this.i18next.t("Edit PSA Result"),
                addTitle: this.i18next.t("Add PSA Result")
            },
            methods: {
                init: function(dependencies) {
                    var self = this;
                    dependencies = dependencies || {};
                    for (var prop in dependencies) {
                        self[prop] = dependencies[prop];
                    }
                    sessionStorage.removeItem(this.userIdKey);
                    this.getData();
                    setTimeout(function() {
                        self.initElementsEvents();
                    }, 300);
                },
                validateResult: function(val) {
                    var isValid = !(isNaN(val) || parseInt(val) < 0);
                    if (!isValid) {
                        this.addErrorMessage = this.i18next.t("Result must be a number.");
                    } else {
                        this.addErrorMessage = "";
                    }
                    return isValid;
                },
                validateDate: function(date) {
                    var isValid = this.tnthDates.isValidDefaultDateFormat(date);
                    if (!isValid) {
                        this.addErrorMessage = this.i18next.t("Date must be in the valid format.");
                    } else {
                        this.addErrorMessage = "";
                    }
                    return isValid;
                },
                formatDateString: function(date, format) {
                    return this.tnthDates.formatDateString(date, format);
                },
                initElementsEvents: function() {
                    var self = this;
                    /*
                     * date picker events
                     */
                    $("#psaDate").datepicker({"format": "d M yyyy", "forceParse": false, "endDate": new Date(), "maxViewMode": 2, "autoclose": true
                    }).on("hide", function() {
                        $("#psaDate").trigger("blur");
                    });
                    $("#psaDate").on("blur", function(e) {
                        var newDate = $(this).val();
                        if (newDate) {
                            var isValid = self.validateDate(newDate);
                            if (self.validateDate(newDate)) {
                                self.newItem.date = newDate;
                            }
                        }
                    });
                    /*
                     * new result field event
                     */
                    $("#psaResult").on("change", function() {
                        self.validateResult($(this).val());
                    });
                    /*
                     * modal event
                     */
                    $("#addPSAModal").on("shown.bs.modal", function(e) {
                        $("#psaResult").focus();
                    }).on("hidden.bs.modal", function(e) {
                        self.clearNew();
                    });
                },
                getCurrentUserId: function() {
                    var self = this;
                    if (!sessionStorage.getItem(this.userIdKey)) {
                        this.tnthAjax.sendRequest("/api/me", "GET", "", {sync:true}, function(data) {
                            if (!data.error) {
                                sessionStorage.setItem(self.userIdKey, data.id);
                            } else {
                                sessionStorage.setItem(self.userIdKey, $("#psaTracker_currentUser").val());
                            }
                        });
                    }
                    return sessionStorage.getItem(this.userIdKey);
                },
                getExistingItemByDate: function(newDate) {
                    return $.grep(this.items, function(item) {
                        return String(item.date) === String(newDate);
                    });
                },
                onEdit: function(item) {
                    var self = this;
                    if (item) {
                        for (var prop in self.newItem) {
                            self.newItem[prop] = item[prop];
                        }
                        setTimeout(function() {
                            $("#addPSAModal").modal("show");
                        }, 250);
                    }
                },
                onAdd: function(event) {
                    var newDate = this.newItem.date;
                    var newResult = this.newItem.result;
                    if (newDate && !this.validateDate(newDate)) {
                        return false;
                    }
                    if (newResult && !this.validateResult(newResult)) {
                        return false;
                    }
                    this.addErrorMessage = "";
                    var existingItem = this.getExistingItemByDate(newDate);
                    if (existingItem.length > 0) {
                        this.newItem.id = existingItem[0].id;
                    }
                    this.postData();
                },
                getData: function() {
                    var self = this;
                    this.loading = true;
                    this.tnthAjax.getClinical(this.getCurrentUserId(), function(data) {
                        if (data.error) {
                            $("#psaTrackerErrorMessageContainer").html(self.i18next.t("Error occurred retrieving PSA result data"));
                        } else {
                            if (data.entry) {
                                var results = (data.entry).map(function(item) {
                                    var dataObj = {}, content = item.content, contentCoding = content.code.coding[0];
                                    dataObj.id = content.id;
                                    dataObj.code = contentCoding.code;
                                    dataObj.display = contentCoding.display;
                                    dataObj.updated = self.formatDateString(item.updated.substring(0,19), "yyyy-mm-dd hh:mm:ss");
                                    dataObj.date = self.formatDateString(content.issued.substring(0,19), "d M y");
                                    dataObj.result = content.valueQuantity.value;
                                    dataObj.edit = true;
                                    return dataObj;
                                });
                                results = $.grep(results, function(item) {
                                    return item.display.toLowerCase() === "psa";
                                });
                                // sort from newest to oldest
                                results = results.sort(function(a, b) {
                                    return new Date(b.date) - new Date(a.date);
                                });
                                /*
                                 * display only 10 most recent results
                                 */
                                if (results.length > 10) {
                                    results = results.slice(0, 10);
                                }
                                self.items = results;
                                setTimeout(function() {
                                    self.drawGraph();
                                }, 500);
                                $("#psaTrackerErrorMessageContainer").html("");
                            } else {
                                $("#psaTrackerErrorMessageContainer").html(self.i18next.t("No result data found"));
                            }
                        }
                        setTimeout(function() {
                            self.loading = false;
                        }, 550);

                    });
                },
                postData: function() {
                    var cDate = "";
                    var self = this;
                    var userId = this.getCurrentUserId();
                    if (this.newItem.date) {
                        var dt = new Date(this.newItem.date);
                        // in 2017-07-06T12:00:00 format
                        cDate = [dt.getFullYear(), (dt.getMonth()+1), dt.getDate()].join("-");
                        cDate = cDate + "T12:00:00";
                    }
                    var url = '/api/patient/'+userId+'/clinical';
                    var method = "POST";
                    var obsCode = [{ "code": this.clinicalCode, "display": this.clinicalDisplay, "system": this.clinicalSystem }];
                    var obsArray = {};
                    obsArray["resourceType"] = "Observation";
                    obsArray["code"] = {"coding": obsCode};
                    obsArray["issued"] = cDate;
                    obsArray["valueQuantity"] = {"units": "g/dl", "code": "g/dl", "value": this.newItem.result};

                    if (this.newItem.id) {
                        method = "PUT";
                        url = url + "/" + this.newItem.id;
                    }

                    this.tnthAjax.sendRequest(url, method, userId, {data: JSON.stringify(obsArray)}, function(data) {
                        if (data.error) {
                            self.addErrorMessage = self.i18next.t("Server error occurred adding PSA result.");
                        }
                        else {
                            $("#addPSAModal").modal("hide");
                            self.getData();
                            self.clearNew();
                            self.addErrorMessage = "";
                        }
                    });
                },
                clearNew: function() {
                    var self = this;
                    for (var prop in self.newItem) {
                        self.newItem[prop] = "";
                    }
                },
                drawGraph: function() {
                    /*
                     * using d3 to draw graph
                     */
                    $("#psaTrackerGraph").html("");
                    var self = this;
                    var d3 = self.d3;
                    var i18next = self.i18next;
                    const WIDTH = 550, HEIGHT = 430, TOP = 50, RIGHT = 20, BOTTOM = 110, LEFT = 60, TIME_FORMAT = "%d %b %Y";

                    // Set the dimensions of the canvas / graph
                    var margin = {top: TOP, right: RIGHT, bottom: BOTTOM, left: LEFT},
                    width = WIDTH - margin.left - margin.right,
                    height = HEIGHT - margin.top - margin.bottom;

                    var timeFormat = d3.time.format(TIME_FORMAT);
                    // Parse the date / time func
                    var parseDate = timeFormat.parse;

                    var data = self.items;

                    data.forEach(function(d) {
                        d.graph_date = parseDate(d.date);
                        d.result = isNaN(d.result)?0:+d.result;
                    });

                    var maxResult = d3.max(data, function(d) {
                        return d.result;
                    });
                    var minResult = d3.min(data, function(d) {
                        return d.result;
                    });

                    var xDomain = d3.extent(data, function(d) { return d.graph_date; });
                    var bound = (width-margin.left-margin.right)/10;
                    var x = d3.time.scale().range([bound, width-bound]);
                    var y = d3.scale.linear().range([height, 0]);

                    function customTickFunc (t0, t1, step) {
                        const day = 1000 * 60 * 60 * 24;
                        var diff = (new Date(t1) - new Date(t0)) / day;
                        var interval = Math.ceil(diff/9);
                        var startTime = new Date(t0),
                            endTime= new Date(t1), times = [];
                        startTime.setUTCDate(startTime.getUTCDate());
                        endTime.setUTCDate(endTime.getUTCDate());
                        while (startTime < endTime && startTime <= endTime) {
                            var dateTime = new Date(startTime);
                            startTime.setUTCDate(startTime.getUTCDate() + interval);
                            var lastInterval = (new Date(startTime) - new Date(endTime)) / day;
                            if (startTime > endTime) {
                                times.push(new Date(endTime));
                                if (lastInterval < interval/2) {
                                    times.push(dateTime);
                                }
                            } else {
                                times.push(dateTime);
                            }
                        }
                        return times;
                    }

                    // Scale the range of the data
                    var endY = Math.max(10, d3.max(data, function(d) { return d.result; }));

                    if (data.length === 1) {
                        var dataArray = [];
                        var firstDate = new Date(data[0].graph_date);
                        xDomain = [data[0].graph_date, new Date(firstDate.setDate(firstDate.getDate() + 365))];
                    }

                    x.domain(xDomain);
                    y.domain([0, parseInt(endY + (endY/(data.length+1))) ]);

                    // Define the axes
                    var xAxis = d3.svg.axis()
                                .scale(x)
                                .orient("bottom")
                                .ticks(customTickFunc)
                                .tickSize(0, 0, 0)
                                .tickFormat(timeFormat);

                    var yAxis = d3.svg.axis()
                                .scale(y)
                                .ticks(5)
                                .orient("left")
                                .tickSize(0, 0, 0);

                    // Define the line
                    var valueline = d3.svg.line()
                                    .interpolate("linear")
                                    .x(function(d) { return x(d.graph_date); })
                                    .y(function(d) { return y(d.result); });

                    // Adds the svg canvas
                    var svg = d3.select("#psaTrackerGraph")
                                .append("svg")
                                .attr("width", width + margin.left + margin.right)
                                .attr("height", height + margin.top + margin.bottom);
                    //background
                    svg.append("rect")
                        .attr("x", margin.left)
                        .attr("y", margin.top)
                        .attr("width", width)
                        .attr("height", height)
                        .style("stroke", "#777")
                        .style("stroke-width", "1")
                        .style("fill", "#ececec");

                    var graphArea = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                    // Add the X Axis
                    graphArea.append("g")
                            .attr("class", "x axis x-axis")
                            .attr("transform", "translate(0," + height + ")")
                            .call(xAxis)
                            .selectAll("text")
                            .attr("y", 0)
                            .attr("x", 7)
                            .attr("dy", ".35em")
                            .attr("transform", "rotate(90)")
                            .attr("class", "axis-stroke")
                            .style("text-anchor", "start");

                    // Add the Y Axis
                    graphArea.append("g")
                            .attr("class", "y axis y-axis")
                            .call(yAxis)
                            .selectAll("text")
                            .attr("dx", "-2px")
                            .attr("dy", "6px")
                            .attr("class","axis-stroke")
                            .style("text-anchor", "end");

                    // add the X gridlines
                    graphArea.append("g")
                            .attr("class", "grid grid-x")
                            .attr("transform", "translate(0," + height + ")")
                            .call(xAxis
                                    .tickSize(-height)
                                    .tickFormat("")
                                );
                    // add the Y gridlines
                    graphArea.append("g")
                            .attr("class", "grid grid-y")
                            .call(yAxis
                                    .tickSize(-width)
                                    .tickFormat("")
                                );

                    // Add the valueline path.
                    graphArea.append("path")
                    .attr("class", "line")
                    .attr("d", valueline(data));

                    // Add the scatterplot
                    graphArea.selectAll("dot")
                            .data(data)
                            .enter().append("circle")
                            .attr("r", 3.7)
                            .attr("class", "circle")
                            .attr("cx", function(d, index) { return x(d.graph_date); })
                            .attr("cy", function(d) { return y(d.result); });

                    // Add caption
                    graphArea.append("text")
                    .attr("x", (width / 2))
                    .attr("y", 0 - (margin.top / 2))
                    .attr("text-anchor", "middle")
                    .attr("class", "graph-caption")
                    .text("PSA (ng/ml)");

                    //add axis legends
                    var xlegend = graphArea.append("g")
                                .attr("transform", "translate(" + (width/2-margin.left+margin.right) + "," + (height + margin.bottom - margin.bottom/8 + 5) + ")");

                    xlegend.append("text")
                            .text(i18next.t("PSA Test Date"))
                            .attr("class", "legend-text");

                    var ylegend = graphArea.append("g")
                                .attr("transform", "translate(" + (-margin.left + margin.left/3) + "," + (height/3) + ")");

                    ylegend.append("text")
                        .attr("transform", "rotate(90)")
                        .attr("class", "legend-text")
                        .text(i18next.t("Result (ng/ml)"));

                }
            }
        });
    $(function() {
        psaApp.init({tnthDates: tnthDates, tnthAjax: tnthAjax, i18next: i18next, d3: d3});
    });
})();
<commit_msg>psa-tracker - fix intervals<commit_after>(function() {
    var psaApp = new Vue({
            el: "#mainPsaApp",
            data: {
                userId: "",
                userIdKey: "psaTracker_currentUser",
                clinicalCode: "666",
                clinicalDisplay: "psa",
                clinicalSystem: "http://us.truenth.org/clinical-codes",
                loading: false,
                addErrorMessage: "",
                noResultMessage: this.i18next.t("No PSA Result To Display"),
                newItem: {
                    id: "",
                    result: "",
                    date:"",
                    edit: false
                },
                headers: [
                    this.i18next.t("PSA (ng/ml)"),
                    this.i18next.t("Date")
                ],
                items: [],
                editTitle: this.i18next.t("Edit PSA Result"),
                addTitle: this.i18next.t("Add PSA Result")
            },
            methods: {
                init: function(dependencies) {
                    var self = this;
                    dependencies = dependencies || {};
                    for (var prop in dependencies) {
                        self[prop] = dependencies[prop];
                    }
                    sessionStorage.removeItem(this.userIdKey);
                    this.getData();
                    setTimeout(function() {
                        self.initElementsEvents();
                    }, 300);
                },
                validateResult: function(val) {
                    var isValid = !(isNaN(val) || parseInt(val) < 0);
                    if (!isValid) {
                        this.addErrorMessage = this.i18next.t("Result must be a number.");
                    } else {
                        this.addErrorMessage = "";
                    }
                    return isValid;
                },
                validateDate: function(date) {
                    var isValid = this.tnthDates.isValidDefaultDateFormat(date);
                    if (!isValid) {
                        this.addErrorMessage = this.i18next.t("Date must be in the valid format.");
                    } else {
                        this.addErrorMessage = "";
                    }
                    return isValid;
                },
                formatDateString: function(date, format) {
                    return this.tnthDates.formatDateString(date, format);
                },
                initElementsEvents: function() {
                    var self = this;
                    /*
                     * date picker events
                     */
                    $("#psaDate").datepicker({"format": "d M yyyy", "forceParse": false, "endDate": new Date(), "maxViewMode": 2, "autoclose": true
                    }).on("hide", function() {
                        $("#psaDate").trigger("blur");
                    });
                    $("#psaDate").on("blur", function(e) {
                        var newDate = $(this).val();
                        if (newDate) {
                            var isValid = self.validateDate(newDate);
                            if (self.validateDate(newDate)) {
                                self.newItem.date = newDate;
                            }
                        }
                    });
                    /*
                     * new result field event
                     */
                    $("#psaResult").on("change", function() {
                        self.validateResult($(this).val());
                    });
                    /*
                     * modal event
                     */
                    $("#addPSAModal").on("shown.bs.modal", function(e) {
                        $("#psaResult").focus();
                    }).on("hidden.bs.modal", function(e) {
                        self.clearNew();
                    });
                },
                getCurrentUserId: function() {
                    var self = this;
                    if (!sessionStorage.getItem(this.userIdKey)) {
                        this.tnthAjax.sendRequest("/api/me", "GET", "", {sync:true}, function(data) {
                            if (!data.error) {
                                sessionStorage.setItem(self.userIdKey, data.id);
                            } else {
                                sessionStorage.setItem(self.userIdKey, $("#psaTracker_currentUser").val());
                            }
                        });
                    }
                    return sessionStorage.getItem(this.userIdKey);
                },
                getExistingItemByDate: function(newDate) {
                    return $.grep(this.items, function(item) {
                        return String(item.date) === String(newDate);
                    });
                },
                onEdit: function(item) {
                    var self = this;
                    if (item) {
                        for (var prop in self.newItem) {
                            self.newItem[prop] = item[prop];
                        }
                        setTimeout(function() {
                            $("#addPSAModal").modal("show");
                        }, 250);
                    }
                },
                onAdd: function(event) {
                    var newDate = this.newItem.date;
                    var newResult = this.newItem.result;
                    if (newDate && !this.validateDate(newDate)) {
                        return false;
                    }
                    if (newResult && !this.validateResult(newResult)) {
                        return false;
                    }
                    this.addErrorMessage = "";
                    var existingItem = this.getExistingItemByDate(newDate);
                    if (existingItem.length > 0) {
                        this.newItem.id = existingItem[0].id;
                    }
                    this.postData();
                },
                getData: function() {
                    var self = this;
                    this.loading = true;
                    this.tnthAjax.getClinical(this.getCurrentUserId(), function(data) {
                        if (data.error) {
                            $("#psaTrackerErrorMessageContainer").html(self.i18next.t("Error occurred retrieving PSA result data"));
                        } else {
                            if (data.entry) {
                                var results = (data.entry).map(function(item) {
                                    var dataObj = {}, content = item.content, contentCoding = content.code.coding[0];
                                    dataObj.id = content.id;
                                    dataObj.code = contentCoding.code;
                                    dataObj.display = contentCoding.display;
                                    dataObj.updated = self.formatDateString(item.updated.substring(0,19), "yyyy-mm-dd hh:mm:ss");
                                    dataObj.date = self.formatDateString(content.issued.substring(0,19), "d M y");
                                    dataObj.result = content.valueQuantity.value;
                                    dataObj.edit = true;
                                    return dataObj;
                                });
                                results = $.grep(results, function(item) {
                                    return item.display.toLowerCase() === "psa";
                                });
                                // sort from newest to oldest
                                results = results.sort(function(a, b) {
                                    return new Date(b.date) - new Date(a.date);
                                });
                                /*
                                 * display only 10 most recent results
                                 */
                                if (results.length > 10) {
                                    results = results.slice(0, 10);
                                }
                                self.items = results;
                                setTimeout(function() {
                                    self.drawGraph();
                                }, 500);
                                $("#psaTrackerErrorMessageContainer").html("");
                            } else {
                                $("#psaTrackerErrorMessageContainer").html(self.i18next.t("No result data found"));
                            }
                        }
                        setTimeout(function() {
                            self.loading = false;
                        }, 550);

                    });
                },
                postData: function() {
                    var cDate = "";
                    var self = this;
                    var userId = this.getCurrentUserId();
                    if (this.newItem.date) {
                        var dt = new Date(this.newItem.date);
                        // in 2017-07-06T12:00:00 format
                        cDate = [dt.getFullYear(), (dt.getMonth()+1), dt.getDate()].join("-");
                        cDate = cDate + "T12:00:00";
                    }
                    var url = '/api/patient/'+userId+'/clinical';
                    var method = "POST";
                    var obsCode = [{ "code": this.clinicalCode, "display": this.clinicalDisplay, "system": this.clinicalSystem }];
                    var obsArray = {};
                    obsArray["resourceType"] = "Observation";
                    obsArray["code"] = {"coding": obsCode};
                    obsArray["issued"] = cDate;
                    obsArray["valueQuantity"] = {"units": "g/dl", "code": "g/dl", "value": this.newItem.result};

                    if (this.newItem.id) {
                        method = "PUT";
                        url = url + "/" + this.newItem.id;
                    }

                    this.tnthAjax.sendRequest(url, method, userId, {data: JSON.stringify(obsArray)}, function(data) {
                        if (data.error) {
                            self.addErrorMessage = self.i18next.t("Server error occurred adding PSA result.");
                        }
                        else {
                            $("#addPSAModal").modal("hide");
                            self.getData();
                            self.clearNew();
                            self.addErrorMessage = "";
                        }
                    });
                },
                clearNew: function() {
                    var self = this;
                    for (var prop in self.newItem) {
                        self.newItem[prop] = "";
                    }
                },
                drawGraph: function() {
                    /*
                     * using d3 to draw graph
                     */
                    $("#psaTrackerGraph").html("");
                    var self = this;
                    var d3 = self.d3;
                    var i18next = self.i18next;
                    const WIDTH = 550, HEIGHT = 430, TOP = 50, RIGHT = 20, BOTTOM = 110, LEFT = 60, TIME_FORMAT = "%d %b %Y";

                    // Set the dimensions of the canvas / graph
                    var margin = {top: TOP, right: RIGHT, bottom: BOTTOM, left: LEFT},
                    width = WIDTH - margin.left - margin.right,
                    height = HEIGHT - margin.top - margin.bottom;

                    var timeFormat = d3.time.format(TIME_FORMAT);
                    // Parse the date / time func
                    var parseDate = timeFormat.parse;

                    var data = self.items;

                    data.forEach(function(d) {
                        d.graph_date = parseDate(d.date);
                        d.result = isNaN(d.result)?0:+d.result;
                    });

                    var maxResult = d3.max(data, function(d) {
                        return d.result;
                    });
                    var minResult = d3.min(data, function(d) {
                        return d.result;
                    });

                    var xDomain = d3.extent(data, function(d) { return d.graph_date; });
                    var bound = (width-margin.left-margin.right)/10;
                    var x = d3.time.scale().range([bound, width-bound]);
                    var y = d3.scale.linear().range([height, 0]);

                    function customTickFunc (t0, t1, step) {
                        const day = 1000 * 60 * 60 * 24;
                        var diff = (new Date(t1) - new Date(t0)) / day;
                        var interval = Math.ceil(diff/9);
                        var startTime = new Date(t0),
                            endTime= new Date(t1), times = [];
                        startTime.setUTCDate(startTime.getUTCDate());
                        endTime.setUTCDate(endTime.getUTCDate());
                        while (startTime < endTime && startTime <= endTime) {
                            var dateTime = new Date(startTime);
                            startTime.setUTCDate(startTime.getUTCDate() + interval);
                            var lastInterval = (new Date(startTime) - new Date(endTime)) / day;
                            if (startTime > endTime) {
                                times.push(new Date(endTime));
                                if (Math.ceil(lastInterval) < interval/2) {
                                    times.push(dateTime);
                                }
                            } else {
                                times.push(dateTime);
                            }
                        }
                        return times;
                    }

                    // Scale the range of the data
                    var endY = Math.max(10, d3.max(data, function(d) { return d.result; }));

                    if (data.length === 1) {
                        var dataArray = [];
                        var firstDate = new Date(data[0].graph_date);
                        xDomain = [data[0].graph_date, new Date(firstDate.setDate(firstDate.getDate() + 365))];
                    }

                    x.domain(xDomain);
                    y.domain([0, parseInt(endY + (endY/(data.length+1))) ]);

                    // Define the axes
                    var xAxis = d3.svg.axis()
                                .scale(x)
                                .orient("bottom")
                                .ticks(customTickFunc)
                                .tickSize(0, 0, 0)
                                .tickFormat(timeFormat);

                    var yAxis = d3.svg.axis()
                                .scale(y)
                                .ticks(5)
                                .orient("left")
                                .tickSize(0, 0, 0);

                    // Define the line
                    var valueline = d3.svg.line()
                                    .interpolate("linear")
                                    .x(function(d) { return x(d.graph_date); })
                                    .y(function(d) { return y(d.result); });

                    // Adds the svg canvas
                    var svg = d3.select("#psaTrackerGraph")
                                .append("svg")
                                .attr("width", width + margin.left + margin.right)
                                .attr("height", height + margin.top + margin.bottom);
                    //background
                    svg.append("rect")
                        .attr("x", margin.left)
                        .attr("y", margin.top)
                        .attr("width", width)
                        .attr("height", height)
                        .style("stroke", "#777")
                        .style("stroke-width", "1")
                        .style("fill", "#ececec");

                    var graphArea = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                    // Add the X Axis
                    graphArea.append("g")
                            .attr("class", "x axis x-axis")
                            .attr("transform", "translate(0," + height + ")")
                            .call(xAxis)
                            .selectAll("text")
                            .attr("y", 0)
                            .attr("x", 7)
                            .attr("dy", ".35em")
                            .attr("transform", "rotate(90)")
                            .attr("class", "axis-stroke")
                            .style("text-anchor", "start");

                    // Add the Y Axis
                    graphArea.append("g")
                            .attr("class", "y axis y-axis")
                            .call(yAxis)
                            .selectAll("text")
                            .attr("dx", "-2px")
                            .attr("dy", "6px")
                            .attr("class","axis-stroke")
                            .style("text-anchor", "end");

                    // add the X gridlines
                    graphArea.append("g")
                            .attr("class", "grid grid-x")
                            .attr("transform", "translate(0," + height + ")")
                            .call(xAxis
                                    .tickSize(-height)
                                    .tickFormat("")
                                );
                    // add the Y gridlines
                    graphArea.append("g")
                            .attr("class", "grid grid-y")
                            .call(yAxis
                                    .tickSize(-width)
                                    .tickFormat("")
                                );

                    // Add the valueline path.
                    graphArea.append("path")
                    .attr("class", "line")
                    .attr("d", valueline(data));

                    // Add the scatterplot
                    graphArea.selectAll("dot")
                            .data(data)
                            .enter().append("circle")
                            .attr("r", 3.7)
                            .attr("class", "circle")
                            .attr("cx", function(d, index) { return x(d.graph_date); })
                            .attr("cy", function(d) { return y(d.result); });

                    // Add caption
                    graphArea.append("text")
                    .attr("x", (width / 2))
                    .attr("y", 0 - (margin.top / 2))
                    .attr("text-anchor", "middle")
                    .attr("class", "graph-caption")
                    .text("PSA (ng/ml)");

                    //add axis legends
                    var xlegend = graphArea.append("g")
                                .attr("transform", "translate(" + (width/2-margin.left+margin.right) + "," + (height + margin.bottom - margin.bottom/8 + 5) + ")");

                    xlegend.append("text")
                            .text(i18next.t("PSA Test Date"))
                            .attr("class", "legend-text");

                    var ylegend = graphArea.append("g")
                                .attr("transform", "translate(" + (-margin.left + margin.left/3) + "," + (height/3) + ")");

                    ylegend.append("text")
                        .attr("transform", "rotate(90)")
                        .attr("class", "legend-text")
                        .text(i18next.t("Result (ng/ml)"));

                }
            }
        });
    $(function() {
        psaApp.init({tnthDates: tnthDates, tnthAjax: tnthAjax, i18next: i18next, d3: d3});
    });
})();
<|endoftext|>


<commit_before>/*jslint devel:true */
/*global Framework7, Dom7, domoticz*/
(function (Framework7, $$) {
    'use strict';

    var app = new Framework7({
            modalTitle: 'domoticz-remote7',
            animateNavBackIcon: true
        }),
        mainView = app.addView('.view-main', {
            // Enable Dynamic Navbar
            dynamicNavbar: true
        }),
		settings = JSON.parse(localStorage.getItem('settings')) || {};

	if (!settings.url) {
		app.popup('.settings');
	}

	$$('.settings-done').on('click', function () {
		settings.url = 'http://' + $$('#ip').val() + ":" + $$('#port').val();
		$$.ajax({
			url :  settings.url + '/json.htm',
			success: function (data) {
				localStorage.setItem('settings',  JSON.stringify(settings));
				app.closeModal();
			},
			error: function () {
				app.addNotification({
					title: "Server unavailable",
					message: "the server doesn't respond to the request"
				});
			}
		});
	});

    window.app = app;
}(Framework7, Dom7, domoticz));<commit_msg>Using JSONP<commit_after>/*jslint devel:true */
/*global Framework7, Dom7, domoticz*/
(function (Framework7, $$) {
    'use strict';

    var app = new Framework7({
            modalTitle: 'domoticz-remote7',
            animateNavBackIcon: true
        }),
        mainView = app.addView('.view-main', {
            // Enable Dynamic Navbar
            dynamicNavbar: true
        }),
		settings = JSON.parse(localStorage.getItem('settings')) || {};

	if (!settings.url) {
		app.popup('.settings');
	}

	$$('.settings-done').on('click', function () {
		settings.url = 'http://' + $$('#ip').val() + ":" + $$('#port').val();
		$$.getJSON(settings.url + '/json.htm?jsoncallback=?', function (data) {
			localStorage.setItem('settings',  JSON.stringify(settings));
			app.closeModal();
		});
	});

    window.app = app;
}(Framework7, Dom7, domoticz));<|endoftext|>


<commit_before>import React, { Component } from 'react';

class Header extends Component {
  render() {
    return (

{this.props.title}

GALLERY

BLOG

ABOUT

    );
  }
}

class Gallery extends Component {
  render() {
    const galleryItems = this.props.url.map(function(url){
      return <GalleryItem {...url} />
    });

    return (

          {galleryItems}

    );
  }
}

class GalleryItem extends Component {

}

export class App extends Component {
  render() {
    var headerOptions = {
      title: "MY PORTFOLIO"
    };

    var galleryOptions = {
      galleryImgUrls: ["/static/dancing_drakes.jpg"]
    };

    return (

      <Gallery {...galleryOptions} />
    );
  }
}<commit_msg>add GalleryItem component, map through the galleryOptions array in Gallery and pass it into the GalleryItem component<commit_after>import React, { Component } from 'react';

class Header extends Component {
  render() {
    return (

{this.props.title}

GALLERY

BLOG

ABOUT

    );
  }
}

class Gallery extends Component {
  render() {
    const galleryItems = this.props.galleryImgUrls.map(function(url){
      return <GalleryItem src={url} />
    });

    return (

          {galleryItems}

    );
  }
}

class GalleryItem extends Component {
  render() {
    return (

        desc

    );
  }
}

export class App extends Component {
  render() {
    var headerOptions = {
      title: "MY PORTFOLIO"
    };

    var galleryOptions = {
      galleryImgUrls: ["/static/dancing_drakes.jpg"]
    };

    return (

        <Gallery {...galleryOptions} />

    );
  }
}<|endoftext|>


<commit_before>self=typeof window!=="undefined"?window:typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope?self:{};var Prism=function(){var lang=/\blang(?:uage)?-(?!\*)(\w+)\b/i;var _=self.Prism={util:{encode:function(tokens){if(tokens instanceof Token){return new Token(tokens.type,_.util.encode(tokens.content),tokens.alias)}else if(_.util.type(tokens)==="Array"){return tokens.map(_.util.encode)}else{return tokens.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ")}},type:function(o){return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1]},clone:function(o){var type=_.util.type(o);switch(type){case"Object":var clone={};for(var key in o){if(o.hasOwnProperty(key)){clone[key]=_.util.clone(o[key])}}return clone;case"Array":return o.slice()}return o}},languages:{extend:function(id,redef){var lang=_.util.clone(_.languages[id]);for(var key in redef){lang[key]=redef[key]}return lang},insertBefore:function(inside,before,insert,root){root=root||_.languages;var grammar=root[inside];var ret={};for(var token in grammar){if(grammar.hasOwnProperty(token)){if(token==before){for(var newToken in insert){if(insert.hasOwnProperty(newToken)){ret[newToken]=insert[newToken]}}}ret[token]=grammar[token]}}return root[inside]=ret},DFS:function(o,callback,type){for(var i in o){if(o.hasOwnProperty(i)){callback.call(o,i,o[i],type||i);if(_.util.type(o[i])==="Object"){_.languages.DFS(o[i],callback)}else if(_.util.type(o[i])==="Array"){_.languages.DFS(o[i],callback,i)}}}}},highlightAll:function(async,callback){var elements=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');for(var i=0,element;element=elements[i++];){_.highlightElement(element,async===true,callback)}},highlightElement:function(element,async,callback){var language,grammar,parent=element;while(parent&&!lang.test(parent.className)){parent=parent.parentNode}if(parent){language=(parent.className.match(lang)||[,""])[1];grammar=_.languages[language]}if(!grammar){return}element.className=element.className.replace(lang,"").replace(/\s+/g," ")+" language-"+language;parent=element.parentNode;if(/pre/i.test(parent.nodeName)){parent.className=parent.className.replace(lang,"").replace(/\s+/g," ")+" language-"+language}var code=element.textContent;if(!code){return}var env={element:element,language:language,grammar:grammar,code:code};_.hooks.run("before-highlight",env);if(async&&self.Worker){var worker=new Worker(_.filename);worker.onmessage=function(evt){env.highlightedCode=Token.stringify(JSON.parse(evt.data),language);_.hooks.run("before-insert",env);env.element.innerHTML=env.highlightedCode;callback&&callback.call(env.element);_.hooks.run("after-highlight",env)};worker.postMessage(JSON.stringify({language:env.language,code:env.code}))}else{env.highlightedCode=_.highlight(env.code,env.grammar,env.language);_.hooks.run("before-insert",env);env.element.innerHTML=env.highlightedCode;callback&&callback.call(element);_.hooks.run("after-highlight",env)}},highlight:function(text,grammar,language){var tokens=_.tokenize(text,grammar);return Token.stringify(_.util.encode(tokens),language)},tokenize:function(text,grammar,language){var Token=_.Token;var strarr=[text];var rest=grammar.rest;if(rest){for(var token in rest){grammar[token]=rest[token]}delete grammar.rest}tokenloop:for(var token in grammar){if(!grammar.hasOwnProperty(token)||!grammar[token]){continue}var patterns=grammar[token];patterns=_.util.type(patterns)==="Array"?patterns:[patterns];for(var j=0;j<patterns.length;++j){var pattern=patterns[j],inside=pattern.inside,lookbehind=!!pattern.lookbehind,lookbehindLength=0,alias=pattern.alias;pattern=pattern.pattern||pattern;for(var i=0;i<strarr.length;i++){var str=strarr[i];if(strarr.length>text.length){break tokenloop}if(str instanceof Token){continue}pattern.lastIndex=0;var match=pattern.exec(str);if(match){if(lookbehind){lookbehindLength=match[1].length}var from=match.index-1+lookbehindLength,match=match[0].slice(lookbehindLength),len=match.length,to=from+len,before=str.slice(0,from+1),after=str.slice(to+1);var args=[i,1];if(before){args.push(before)}var wrapped=new Token(token,inside?_.tokenize(match,inside):match,alias);args.push(wrapped);if(after){args.push(after)}Array.prototype.splice.apply(strarr,args)}}}}return strarr},hooks:{all:{},add:function(name,callback){var hooks=_.hooks.all;hooks[name]=hooks[name]||[];hooks[name].push(callback)},run:function(name,env){var callbacks=_.hooks.all[name];if(!callbacks||!callbacks.length){return}for(var i=0,callback;callback=callbacks[i++];){callback(env)}}}};var Token=_.Token=function(type,content,alias){this.type=type;this.content=content;this.alias=alias};Token.stringify=function(o,language,parent){if(typeof o=="string"){return o}if(Object.prototype.toString.call(o)=="[object Array]"){return o.map(function(element){return Token.stringify(element,language,o)}).join("")}var env={type:o.type,content:Token.stringify(o.content,language,parent),tag:"span",classes:["token",o.type],attributes:{},language:language,parent:parent};if(env.type=="comment"){env.attributes["spellcheck"]="true"}if(o.alias){var aliases=_.util.type(o.alias)==="Array"?o.alias:[o.alias];Array.prototype.push.apply(env.classes,aliases)}_.hooks.run("wrap",env);var attributes="";for(var name in env.attributes){attributes+=name+'="'+(env.attributes[name]||"")+'"'}return"<"+env.tag+' class="'+env.classes.join(" ")+'" '+attributes+">"+env.content+"</"+env.tag+">"};if(!self.document){if(!self.addEventListener){return self.Prism}self.addEventListener("message",function(evt){var message=JSON.parse(evt.data),lang=message.language,code=message.code;self.postMessage(JSON.stringify(_.util.encode(_.tokenize(code,_.languages[lang]))));self.close()},false);return self.Prism}var script=document.getElementsByTagName("script");script=script[script.length-1];if(script){_.filename=script.src;if(document.addEventListener&&!script.hasAttribute("data-manual")){document.addEventListener("DOMContentLoaded",_.highlightAll)}}return self.Prism}();if(typeof module!=="undefined"&&module.exports){module.exports=Prism}Prism.languages.markup={comment:/<!--[\w\W]*?-->/g,prolog:/<\?.+?\?>/,doctype:/<!DOCTYPE.+?>/,cdata:/<!\[CDATA\[[\w\W]*?]]>/i,tag:{pattern:/<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+))?\s*)*\/?>/gi,inside:{tag:{pattern:/^<\/?[\w:-]+/i,inside:{punctuation:/^<\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,inside:{punctuation:/=|>|"/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/\&#?[\da-z]{1,8};/gi};Prism.hooks.add("wrap",function(env){if(env.type==="entity"){env.attributes["title"]=env.content.replace(/&/,"&")}});Prism.languages.css={comment:/\/\*[\w\W]*?\*\//g,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*{))/gi,inside:{punctuation:/[;:]/g}},url:/url\((["']?).*?\1\)/gi,selector:/[^\{\}\s][^\{\};]*(?=\s*\{)/g,property:/(\b|\B)[\w-]+(?=\s*:)/gi,string:/("|')(\\?.)*?\1/g,important:/\B!important\b/gi,punctuation:/[\{\};:]/g,"function":/[-a-z0-9]+(?=\()/gi};if(Prism.languages.markup){Prism.languages.insertBefore("markup","tag",{style:{pattern:/<style[\w\W]*?>[\w\W]*?<\/style>/gi,inside:{tag:{pattern:/<style[\w\W]*?>|<\/style>/gi,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.css}}})}Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\w\W]*?\*\//g,lookbehind:true},{pattern:/(^|[^\\:])\/\/.*?(\r?\n|$)/g,lookbehind:true}],string:/("|')(\\?.)*?\1/g,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/gi,lookbehind:true,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,"function":{pattern:/[a-z0-9_]+\(/gi,inside:{punctuation:/\(/}},number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,operator:/[-+]{1,2}|!|<=?|>=?|={1,3}|&{1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|get|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?|NaN|-?Infinity)\b/g});Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:true}});if(Prism.languages.markup){Prism.languages.insertBefore("markup","tag",{script:{pattern:/<script[\w\W]*?>[\w\W]*?<\/script>/gi,inside:{tag:{pattern:/<script[\w\W]*?>|<\/script>/gi,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript}}})}(function(){if(!self.Prism||!self.document||!document.querySelector){return}var Extensions={js:"javascript",html:"markup",svg:"markup",xml:"markup",py:"python"};Array.prototype.slice.call(document.querySelectorAll("pre[data-src]")).forEach(function(pre){var src=pre.getAttribute("data-src");var extension=(src.match(/\.(\w+)$/)||[,""])[1];var language=Extensions[extension]||extension;var code=document.createElement("code");code.className="language-"+language;pre.textContent="";code.textContent="Loading…";pre.appendChild(code);var xhr=new XMLHttpRequest;xhr.open("GET",src,true);xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status<400&&xhr.responseText){code.textContent=xhr.responseText;Prism.highlightElement(code)}else if(xhr.status>=400){code.textContent="✖ Error "+xhr.status+" while fetching file: "+xhr.statusText}else{code.textContent="✖ Error: File does not exist or is empty"}}};xhr.send(null)})})();<commit_msg>chore(public): remove prism.min.js<commit_after><|endoftext|>


<commit_before>/* ************************************************** *
 * ******************** REMIE
 * ************************************************** */
let REMIE = require('../libs/index.js'),
  remie = new (require('../libs/index.js'))(),
  i18next = require('i18next'),
  EventEmitter = require('events');
  //EventListener = require('events').EventListener;
  //console.log(EventListener)
var inherits = require('util').inherits;
err = {}
err.code = 'server.400.notFound'
err.message = 'Message in an error!'
//err.stack = 'errors stacked on errors'
//err.internalMessage = 'internal message'

let options = {}
options.internalMessage = 'internal Message'
options.level = 'warning'
//options.code = 'server.400.notFound'

let locale = 'server.400.notFound'

remie.i18next = i18next

inherits(REMIE, EventEmitter.EventEmitter)

let error = remie.create('Something went wrong', options, locale)
//let error = remie.create("Something went wrong", {})
// |||
// vvv does not work if richErrorObject.error is undefined, null. must be object with property "message"
//let error2 = remie.toObject(error)
//let error2 = remie.create("Something else went wrong", {});
//let error3 = remie.create("Oh crap, what now", {});
console.log(error)

/*
remie.on('on-internal-error', function(err){
  console.log("Internal Error %s", err.internalMessage);
});
var event = 'on-internal-error'
remie.emit(event, err)
*/<commit_msg>example calls buildFromLocale<commit_after>/* ************************************************** *
 * ******************** REMIE
 * ************************************************** */
let REMIE = require('../libs/index.js'),
  remie = new (require('../libs/index.js'))(),
  i18next = require('i18next'),
  EventEmitter = require('events');
  //EventListener = require('events').EventListener;
  //console.log(EventListener)
var inherits = require('util').inherits;
err = 'server.400.notFound'
err.code = 'server.400.notFound'
err.message = 'Message in an error!'
//err.stack = 'errors stacked on errors'
//err.internalMessage = 'internal message'

let options = {}
options.internalMessage = 'internal Message'
options.level = 'warning'
//options.code = 'server.400.notFound'

let locale = 'server.400.notFound'

remie.i18next = i18next

inherits(REMIE, EventEmitter.EventEmitter)

//let error = remie.create(err, options, locale)
let error = remie.create(err)
//let error = remie.create('Something went wrong', options, locale)
//let error = remie.create("Something went wrong", {})
// |||
// vvv does not work if richErrorObject.error is undefined, null. must be object with property "message"
//let error2 = remie.toObject(error)
//let error2 = remie.create("Something else went wrong", {});
//let error3 = remie.create("Oh crap, what now", {});
console.log(error)

module.exports = error

/*
remie.on('on-internal-error', function(err){
  console.log("Internal Error %s", err.internalMessage);
});
var event = 'on-internal-error'
remie.emit(event, err)
*/<|endoftext|>


<commit_before>import React, { Component } from "react";
import _ from "lodash";
import { DayDisplay } from "../../components";
import { AppFooter, AppHeader } from "../App";
import config from "../../../config";
import apollo11logo from "../../../static/apollo11logo.jpg";
import { StoryList } from "../../components";
import Spinner from "react-spinner";

export class Apollo11Explorer extends Component {

  constructor() {
    super();
    this.state = { loading: true, stories: [] };
  }
  async componentDidMount() {
    const response = await fetch(`${config.apiEntry}/api/stories`);
    const json = await response.json();
    this.setState({ loading: false, stories: json });
  }

  checkDay() {
    var mstart;
    var mend;
    const stories = _.sortBy(this.state.stories, "met_start");
    let tempUrl = this.props.location.pathname;
    const day = tempUrl.split("/")[3];
    var targetstories = [];
    switch (day) {
      case "1":
        mstart = 0;
        mend = 55680000;
        break;
      case "2":
        mstart = 55680001;
        mend = 142080000;
        break;
      case "3":
        mstart = 142080001;
        mend = 228479999;
        break;
      case "4":
        mstart = 228480000;
        mend = 314879998;
        break;
      case "5":
        mstart = 314879999;
        mend = 401279997;
        break;
      case "6":
        mstart = 401279998;
        mend = 487679996;
        break;
      case "7":
        mstart = 487679997;
        mend = 574079995;
        break;
      case "8":
        mstart = 574079996;
        mend = 660479994;
        break;
      case "9":
        mstart = 660479995;
        mend = 746879993;
        break;
      default:
        mstart = -746879993;
        mend = 746879993;
    }

    targetstories = _.filter(stories, function (story) {
      return (
        day == null ||
        (story.met_start != null &&
          ((story.met_start >= mstart && story.met_start <= mend) ||
            (story.met_start < mstart && story.met_end > mstart)))
      );
    });

    if (_.isEmpty(targetstories)) {
      return (

 No stories on this day

      );
    } else {
      return <StoryList stories={targetstories} />;
    }
  }
  render() {
    if (this.props.loading) {
      return (

Loading Stories...

          <Spinner />

      );
    }
    const url = "/apollo11/";
    return (

        <AppHeader />

        "That's one small step for man, one giant leap for mankind." - Neil Armstrong, Apollo 11

        {" "}

         Fast Facts

          Information:

        1. Astronauts: Neil Armstrong, Buzz Aldrin, and Michael Collins

        2. This was the first manned mission to successfully reach the moon.

        3. The American flag that was planted on the moon by the astronauts was made by Sears.

        4. Apollo 11 was launched at the same time of the Soviet's Sputnik.

        5. President John F. Kennedy was more interested in the Space Race than he was of what the astronauts would find in space.

        6. When Armstrong, Aldrin, and Collins returned back to Earth, they were placed in quarantine because scientists were inconclusive about space germs entering Earth.

          Significance:

        1. Apollo 11 was the first mission to successfully place men on the moon.

        2. Neil Armstrong marked the occasion with his famous quote: "That's one small step for man,
        one giant leap for mankind."

          <DayDisplay day={this.props.location.pathname.split("/")[3]} url={url} />
          {this.checkDay()}

        <AppFooter />

    );
  }
}
<commit_msg>Lint fixes<commit_after>import React, { Component } from "react";
import _ from "lodash";
import { DayDisplay } from "../../components";
import { AppFooter, AppHeader } from "../App";
import config from "../../../config";
import apollo11logo from "../../../static/apollo11logo.jpg";
import { StoryList } from "../../components";
import Spinner from "react-spinner";

export class Apollo11Explorer extends Component {
  constructor() {
    super();
    this.state = { loading: true, stories: [] };
  }
  async componentDidMount() {
    const response = await fetch(`${config.apiEntry}/api/stories`);
    const json = await response.json();
    this.setState({ loading: false, stories: json });
  }

  checkDay() {
    var mstart;
    var mend;
    const stories = _.sortBy(this.state.stories, "met_start");
    let tempUrl = this.props.location.pathname;
    const day = tempUrl.split("/")[3];
    var targetstories = [];
    switch (day) {
      case "1":
        mstart = 0;
        mend = 55680000;
        break;
      case "2":
        mstart = 55680001;
        mend = 142080000;
        break;
      case "3":
        mstart = 142080001;
        mend = 228479999;
        break;
      case "4":
        mstart = 228480000;
        mend = 314879998;
        break;
      case "5":
        mstart = 314879999;
        mend = 401279997;
        break;
      case "6":
        mstart = 401279998;
        mend = 487679996;
        break;
      case "7":
        mstart = 487679997;
        mend = 574079995;
        break;
      case "8":
        mstart = 574079996;
        mend = 660479994;
        break;
      case "9":
        mstart = 660479995;
        mend = 746879993;
        break;
      default:
        mstart = -746879993;
        mend = 746879993;
    }

    targetstories = _.filter(stories, function (story) {
      return (
        day == null ||
        (story.met_start != null &&
          ((story.met_start >= mstart && story.met_start <= mend) ||
            (story.met_start < mstart && story.met_end > mstart)))
      );
    });

    if (_.isEmpty(targetstories)) {
      return (

 No stories on this day

      );
    } else {
      return <StoryList stories={targetstories} />;
    }
  }
  render() {
    if (this.props.loading) {
      return (

Loading Stories...

          <Spinner />

      );
    }
    const url = "/apollo11/";
    return (

        <AppHeader />

              "That's one small step for man, one giant leap for mankind." -
              Neil Armstrong, Apollo 11

              {" "}

               Fast Facts

                Information:

              1. Astronauts: Neil Armstrong, Buzz Aldrin, and Michael Collins{" "}

              2. This was the first manned mission to successfully reach the
              moon.

              3. The American flag that was planted on the moon by the
              astronauts was made by Sears.

              4. Apollo 11 was launched at the same time of the Soviet's
              Sputnik.

              5. President John F. Kennedy was more interested in the Space Race
              than he was of what the astronauts would find in space.

              6. When Armstrong, Aldrin, and Collins returned back to Earth,
              they were placed in quarantine because scientists were
              inconclusive about space germs entering Earth.

                Significance:

              1. Apollo 11 was the first mission to successfully place men on
              the moon.

              2. Neil Armstrong marked the occasion with his famous quote:
              "That's one small step for man, one giant leap for mankind."{" "}

            <DayDisplay
              day={this.props.location.pathname.split("/")[3]}
              url={url}
            />
            {this.checkDay()}

          <AppFooter />

    );
  }
}
<|endoftext|>


<commit_before>var unirest = require('unirest');
var async   = require('async');
var Logger  = require('../utility/logger');
var helper  = require('../utility/helper');
var User    = require('../models/user');
var Game    = require('../models/game');
var config  = require('../config');

function makeUserSearchRequest(ageMin, ageMax, gender, availability){
    var userSearchRequest = {
        ageMin: ageMin,
        ageMax: ageMax,
        gender: gender,
        availability: availability
    };
    return userSearchRequest;
}

function makeGameSearchRequest(){
    var gameSearchRequest = {
        //empty for now
    };
    return gameSearchRequest;
}

//returns a search request object to be used in the search function
function makeSearchRequest(req, res, query, page, users, games){
    var searchRequest = {
        req: req,     //the request object
        res: res,     //the response object
        query: query, //text that is being searched for
        page: page,   //what page number was requested
        users: users, //search request for users
        games: games  //search request for games
    };
    return searchRequest;
}

//returns an object containing functions to be called asynchronously and in parallel
function getAsyncFunctions(searchRequest){
    var query = searchRequest.query.toLowerCase();

    var asyncFunctions = {};

    if (searchRequest.users) {
        var userQuery = {
            username: {
                $regex: query + ".*"
            }
        };
        asyncFunctions.users = function (cb){
            User.find(userQuery).exec(cb);
        };
    }

    if (searchRequest.games){
        var gameQuery = {
            "name": {
                $regex : query + ".*"
            }
        };
        asyncFunctions.games = function (cb){
            Game.find(gameQuery).exec(cb);
        };
    }

    return asyncFunctions;
}

//calls the callback function with results accumulated using
//the information inside the searchRequest object
function search(searchRequest, callback){

    //if the query is too short, return
    if (searchRequest.query.length < 3){
        callback(searchRequest, null);
        return;
    }

    console.log("Query: " + searchRequest.query);

    //get the functions to be called asynchronously
    var asyncRequest = getAsyncFunctions(searchRequest);

    //call asynchronous functions
    async.parallel(asyncRequest, function(err, result){

        if (err){
            Logger.log("Querying database during search failed.", err);
            callback(searchRequest, null);
            return;
        }

        var users = result.users;
        var games = result.games;

        //the results to return
        var results = [];

        //if users returned, populate results
        if (users) {
            for (var i = 0; i < users.length; i++) {
                var name = users[i].display_name;
                var image = "/images/profile/" + users[i].display_name + ".png";
                var text = users[i].bio === undefined ? "" : users[i].bio;
                addToResults(results, "user", name, image, text);
            }
            console.log("Users: " + users.length);
        }

        //if games returned, populate results
        if (games) {
            for (var i = 0; i < games.length; i++) {
                var name = games[i].display_name;
                var image = games[i].boxart;
                var text = games[i].description;
                addToResults(results, "game", name, image, text);
            }
            console.log("Games: " + games.length);

            //if games are requested but none returned from the database
            //use the api to populate the results
            if (games.length < 1){
                callApi(searchRequest, results, callback, getAllGames);
                return;
            }
        }

        //call the callback function with the results
        callback(searchRequest, results);
    });
}

//returns the fields when searching for games via the api
function getFields(){
    var fields = ["name", "summary", "release_dates", "cover", "rating", "screenshots", "videos", "developers", "publishers"];
    return encodeURI(fields.join());
}

//makes a call to IGDB via their api to search through their databases for games
function callApi(searchRequest, results, callback, handler){

    var api = {
        fields: "?fields=" + getFields(),
        limit:  "&limit="  + config.api_max_per_query,
        offset: "&offset=" + 0,
        query:  "&search=" + searchRequest.query,
        filter: "&filter[category][eq]=0"
    };

    var request = config.api_url + api.fields + api.limit + api.offset + api.query + api.filter;

    unirest
        .get(request)
        .header("X-Mashape-Key", config.api_key)
        .header("Accept", "application/json")
        .timeout(config.api_timeout)
        .end(function (response) {

            //if something went wrong, call callback
            if (response.status != 200){
                callback(searchRequest, results);
                return;
            }

            //otherwise call handler with results and response
            results = handler(results, response);

            //finally, call callback with the results
            callback(searchRequest, results);
        }
    );
}

function getAllGames(results, response){
    //otherwise iterate through all the games and
    //add it to our results and database
    response.body.forEach(function(game){
        var name = game.name;
        var image = getBoxArt(game);
        var text = 'summary' in game ? game.summary : "";
        addToResults(results, "game", name, image, text);
        addToDatabase(game);
    });
    return results;
}

function getFirstGame(results, response){
    //in the case that no games were found
    if (response.body.length == 0){
        return;
    }

    //otherwise add every game to the database
    response.body.forEach(function(game){
        addToDatabase(game);
    });

    //then return just the first game, parsed
    return parseGame(response.body[0]);
}

//parses api data and returns a game object
function parseGame(game){
    var new_game = {
        id: game.id,
        name: helper.getCleanedGameName(game),
        display_name: game.name,
        description : 'summary' in game ? game.summary : "",
        boxart: getBoxArt(game),
        one_ups: []
    };

    var date = getReleaseDate(game);
    if (date > 0){
        new_game.release_date = new Date(date);
    }

    var rating = getRating(game);
    if (rating > 0){
        new_game.rating = rating;
    }

    var screens = getScreenshots(game);
    if (screens){
        new_game.screenshots = screens;
    }

    var videos = getVideos(game);
    if (videos){
        new_game.videos = videos;
    }

    return new_game;
}

//adds a new game to the database for further use in the future
function addToDatabase(game){

    var newGame = parseGame(game);

    var query = {
        id: game.id
    };

    var options = {
        upsert: true
    };

    Game.findOneAndUpdate(query, newGame, options, function (err, doc) {
            if (err){
                Logger.log("Failed to add " + game.name + " from API.", err);
                return;
            }
            console.log("Added " + game.name + ".");
        }
    );
}

function getBoxArt(game){
    if ('cover' in game){
        return "https://res.cloudinary.com/igdb/image/upload/t_cover_big/" + game.cover.cloudinary_id + ".jpg";
    } else {
        return config.game_not_found_boxart;
    }
}

function getScreenshots(game){
    try {
        var screenshots = [];
        game.screenshots.forEach(function(screen){
            screenshots.push(screen.cloudinary_id);
        });
        return screenshots;
    } catch (err) {
        return null;
    }
}

function getVideos(game){
    try {
        var videos = [];
        game.videos.forEach(function(video){
            videos.push({
                title: video.name,
                link: video.video_id
            });
        });
        return videos;
    } catch (err) {
        return null;
    }
}

function getReleaseDate(game){
    try {
        return game.release_dates[0].date;
    } catch (err){
        return 0;
    }
}

function getRating(game){
    try {
        return game.rating;
    } catch (err){
        return 0;
    }
}

function addToResults(results, type, name, image, description){
    var item = {
        type: type,
        name: name,
        image: image,
        description: description
    };
    results.push(item);
}

module.exports = {
    callApi: callApi,
    search: search,
    makeUserSearchRequest: makeUserSearchRequest,
    makeGameSearchRequest: makeGameSearchRequest,
    makeSearchRequest: makeSearchRequest,
    getAllGames: getAllGames,
    getFirstGame: getFirstGame
};
<commit_msg>Age user filtering added<commit_after>var unirest = require('unirest');
var async   = require('async');
var Logger  = require('../utility/logger');
var helper  = require('../utility/helper');
var User    = require('../models/user');
var Game    = require('../models/game');
var config  = require('../config');

function makeUserSearchRequest(ageMin, ageMax, gender, availability){
    var userSearchRequest = {
        ageMin: ageMin,
        ageMax: ageMax,
        gender: gender,
        availability: availability
    };
    return userSearchRequest;
}

function makeGameSearchRequest(){
    var gameSearchRequest = {
        //empty for now
    };
    return gameSearchRequest;
}

//returns a search request object to be used in the search function
function makeSearchRequest(req, res, query, page, users, games){
    var searchRequest = {
        req: req,     //the request object
        res: res,     //the response object
        query: query, //text that is being searched for
        page: page,   //what page number was requested
        users: users, //search request for users
        games: games  //search request for games
    };
    return searchRequest;
}

//returns an object containing functions to be called asynchronously and in parallel
function getAsyncFunctions(searchRequest){
    var query = searchRequest.query.toLowerCase();

    var asyncFunctions = {};

    if (searchRequest.users) {
        var userQuery = {
            username: {
                $regex: query + ".*"
            }
        };
        if (searchRequest.users.ageMin && searchRequest.users.ageMax){
            var today = new Date();

            var min = new Date(today);
            min.setFullYear(today.getFullYear() - searchRequest.users.ageMin);

            var max = new Date(today);
            max.setFullYear(today.getFullYear() - searchRequest.users.ageMax);

            userQuery.birthday = {
                $gte: max,
                $lt: min
            }
        }
        asyncFunctions.users = function (cb){
            User.find(userQuery).exec(cb);
        };
    }

    if (searchRequest.games){
        var gameQuery = {
            "name": {
                $regex : query + ".*"
            }
        };
        asyncFunctions.games = function (cb){
            Game.find(gameQuery).exec(cb);
        };
    }

    return asyncFunctions;
}

//calls the callback function with results accumulated using
//the information inside the searchRequest object
function search(searchRequest, callback){

    //if the query is too short, return
    if (searchRequest.query.length < 3){
        callback(searchRequest, null);
        return;
    }

    console.log("Query: " + searchRequest.query);

    //get the functions to be called asynchronously
    var asyncRequest = getAsyncFunctions(searchRequest);

    //call asynchronous functions
    async.parallel(asyncRequest, function(err, result){

        if (err){
            Logger.log("Querying database during search failed.", err);
            callback(searchRequest, null);
            return;
        }

        var users = result.users;
        var games = result.games;

        //the results to return
        var results = [];

        //if users returned, populate results
        if (users) {
            for (var i = 0; i < users.length; i++) {
                var name = users[i].display_name;
                var image = "/images/profile/" + users[i].display_name + ".png";
                var text = users[i].bio === undefined ? "" : users[i].bio;
                addToResults(results, "user", name, image, text);
            }
            console.log("Users: " + users.length);
        }

        //if games returned, populate results
        if (games) {
            for (var i = 0; i < games.length; i++) {
                var name = games[i].display_name;
                var image = games[i].boxart;
                var text = games[i].description;
                addToResults(results, "game", name, image, text);
            }
            console.log("Games: " + games.length);

            //if games are requested but none returned from the database
            //use the api to populate the results
            if (games.length < 1){
                callApi(searchRequest, results, callback, getAllGames);
                return;
            }
        }

        //call the callback function with the results
        callback(searchRequest, results);
    });
}

//returns the fields when searching for games via the api
function getFields(){
    var fields = ["name", "summary", "release_dates", "cover", "rating", "screenshots", "videos", "developers", "publishers"];
    return encodeURI(fields.join());
}

//makes a call to IGDB via their api to search through their databases for games
function callApi(searchRequest, results, callback, handler){

    var api = {
        fields: "?fields=" + getFields(),
        limit:  "&limit="  + config.api_max_per_query,
        offset: "&offset=" + 0,
        query:  "&search=" + searchRequest.query,
        filter: "&filter[category][eq]=0"
    };

    var request = config.api_url + api.fields + api.limit + api.offset + api.query + api.filter;

    unirest
        .get(request)
        .header("X-Mashape-Key", config.api_key)
        .header("Accept", "application/json")
        .timeout(config.api_timeout)
        .end(function (response) {

            //if something went wrong, call callback
            if (response.status != 200){
                callback(searchRequest, results);
                return;
            }

            //otherwise call handler with results and response
            results = handler(results, response);

            //finally, call callback with the results
            callback(searchRequest, results);
        }
    );
}

function getAllGames(results, response){
    //otherwise iterate through all the games and
    //add it to our results and database
    response.body.forEach(function(game){
        var name = game.name;
        var image = getBoxArt(game);
        var text = 'summary' in game ? game.summary : "";
        addToResults(results, "game", name, image, text);
        addToDatabase(game);
    });
    return results;
}

function getFirstGame(results, response){
    //in the case that no games were found
    if (response.body.length == 0){
        return;
    }

    //otherwise add every game to the database
    response.body.forEach(function(game){
        addToDatabase(game);
    });

    //then return just the first game, parsed
    return parseGame(response.body[0]);
}

//parses api data and returns a game object
function parseGame(game){
    var new_game = {
        id: game.id,
        name: helper.getCleanedGameName(game),
        display_name: game.name,
        description : 'summary' in game ? game.summary : "",
        boxart: getBoxArt(game),
        one_ups: []
    };

    var date = getReleaseDate(game);
    if (date > 0){
        new_game.release_date = new Date(date);
    }

    var rating = getRating(game);
    if (rating > 0){
        new_game.rating = rating;
    }

    var screens = getScreenshots(game);
    if (screens){
        new_game.screenshots = screens;
    }

    var videos = getVideos(game);
    if (videos){
        new_game.videos = videos;
    }

    return new_game;
}

//adds a new game to the database for further use in the future
function addToDatabase(game){

    var newGame = parseGame(game);

    var query = {
        id: game.id
    };

    var options = {
        upsert: true
    };

    Game.findOneAndUpdate(query, newGame, options, function (err, doc) {
            if (err){
                Logger.log("Failed to add " + game.name + " from API.", err);
                return;
            }
            console.log("Added " + game.name + ".");
        }
    );
}

function getBoxArt(game){
    if ('cover' in game){
        return "https://res.cloudinary.com/igdb/image/upload/t_cover_big/" + game.cover.cloudinary_id + ".jpg";
    } else {
        return config.game_not_found_boxart;
    }
}

function getScreenshots(game){
    try {
        var screenshots = [];
        game.screenshots.forEach(function(screen){
            screenshots.push(screen.cloudinary_id);
        });
        return screenshots;
    } catch (err) {
        return null;
    }
}

function getVideos(game){
    try {
        var videos = [];
        game.videos.forEach(function(video){
            videos.push({
                title: video.name,
                link: video.video_id
            });
        });
        return videos;
    } catch (err) {
        return null;
    }
}

function getReleaseDate(game){
    try {
        return game.release_dates[0].date;
    } catch (err){
        return 0;
    }
}

function getRating(game){
    try {
        return game.rating;
    } catch (err){
        return 0;
    }
}

function addToResults(results, type, name, image, description){
    var item = {
        type: type,
        name: name,
        image: image,
        description: description
    };
    results.push(item);
}

module.exports = {
    callApi: callApi,
    search: search,
    makeUserSearchRequest: makeUserSearchRequest,
    makeGameSearchRequest: makeGameSearchRequest,
    makeSearchRequest: makeSearchRequest,
    getAllGames: getAllGames,
    getFirstGame: getFirstGame
};
<|endoftext|>


<commit_before>import React, { Component } from "react";
import moment from "moment";
import classNames from "classnames";
import { debounce } from 'lodash/function';

class Day extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editing: false,
      text: "",
    };

    this.saveTodo = this.saveTodo.bind(this);
    this.onFocus = this.onFocus.bind(this);
    this.onBlur = this.onBlur.bind(this);
    this.onChange = this.onChange.bind(this);
    this.onKeyDown = this.onKeyDown.bind(this);

    this.saveTodoHandler = debounce(function () {
      this.saveTodo()
    }, 500);
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      text: nextProps.text
    });
  }

  componentDidUpdate() {
    // if (this.props.isTargetDay && !this.props.aDayIsFocused) {
    //   this.props.scrollTo(this.textarea);
    // }
  }

  saveTodo() {
    this.props.saveTodo(this.props.firebaseKey, this.props.day.valueOf(), this.state.text);
  }

  onFocus() {
    this.setState({editing: true});
    this.props.focusDay(this.props.day, this.textarea);
  }

  onBlur() {
    this.setState({
      editing: false
    });
    this.props.unfocusDay();
    this.saveTodo();
  }

  onChange(event) {
    this.setState({text: event.target.value})
    this.saveTodoHandler();
  }

  onKeyDown(event) {
    if (event.keyCode === 27 /*esc*/) {
      this.textarea.blur();
    }
  }

  render() {
    const colorNumber = this.props.isInFocusedWeek ? 2 : 1;

    const dayClasses = classNames({
      "day flex vertical padding-0-5 padding-top min-day-width border-1": true,
      [`color-${colorNumber+4}`]: !this.props.aDayIsFocused ||  this.props.isFocusedDay,
      [`color-${colorNumber+3}`]:  this.props.aDayIsFocused && !this.props.isFocusedDay,
      // [`bg-${this.props.weekNumber}`]: !this.props.isFocusedDay,
      // [`bg-bright-${this.props.weekNumber}`]: this.props.isFocusedDay,
    });

    let dayLabel, monthLabel;
    const todayLabel = this.props.isToday? ", Today" : false

    if (this.props.someday) {
      dayLabel = `Someday ${this.props.day.format("D")}`;
    }
    else {
      dayLabel = this.props.day.format("ddd DD");

      if (
          (
            this.props.weekNumber === 1 &&
            this.props.day.isSame(moment(this.props.day).startOf("isoweek"))
          ) ||
          this.props.day.isSame(moment(this.props.day).startOf("month"))
      ) {
        monthLabel = `, ${this.props.day.format("MMM YYYY")}`;
      }
    }

    let placeholder;
    if (this.props.anonymous) {
      if (this.props.someday && +this.props.day.format("D") === 1) {
        placeholder = "This row is not tied to any week and will always stay put. Useful for stuff like grocery lists and grandiose plans.";
      }
      // else if (this.props.weekNumber === 1 && +this.props.day.format("d") === 1) {
      //   placeholder = "This row is always last week."
      // }
      else if (this.props.weekNumber === 1) {
        if (+this.props.day.format("d") === 1) {
          placeholder = "This row is always the current week."
        }
        else if (+this.props.day.format("d") === 2) {
          placeholder = "Try typing something here. Text is auto-saved as you type.";
        }
        else if (+this.props.day.format("d") === 3) {
          placeholder = "You are currently using a temporary account. Your entries are saved in this browser only.";
        }
        else if (+this.props.day.format("d") === 4) {
          placeholder = "To access your entries in other browsers or devices, SIGN UP from the bottom menu. \n\nSigning up will also make these messages go away.";
        }
        else if (+this.props.day.format("d") === 5) {
          placeholder = "Protips:\n\nWhen using this app for todos I find it handy to mark completed tasks with an x. Like this ->\n\nTo move todos from one day to another, just cut and paste.";
        }
        else if (+this.props.day.format("d") === 6) {
          placeholder = "x 9:00 Dentist\n12:00 Lunch\n18:00 Play video games";
        }
      }
      else if (this.props.weekNumber === 2) {
        if (+this.props.day.format("d") === 1) {
          placeholder = "This row is always next week."
        }
        else if (+this.props.day.format("d") === 2) {
          placeholder = "To access weeks further in the future or in the past, ZOOM OUT from the bottom menu.";
        }
      }
    }

    return (

        <label
          htmlFor={this.props.day.valueOf()}
          className={classNames({
            "all-caps padding-0-25 padding-top-0": true,
            [`color-${colorNumber+3}`]: (this.props.aDayIsFocused && this.props.isFocusedDay) || !this.props.aDayIsFocused,
            [`color-${colorNumber+2}`]:  this.props.aDayIsFocused,
            [`color-bright-${colorNumber+4}`]: this.props.isToday && (!this.props.aDayIsFocused || (this.props.aDayIsFocused && this.props.isFocusedDay)),
            [`color-bright-${colorNumber+3}`]: this.props.isToday && !this.props.aDayIsFocused,
            // "color-5": !this.props.aDayIsFocused || this.props.isFocusedDay,
            // "color-3": this.props.aDayIsFocused && !this.props.isFocusedDay,
            // "color-bright-6": this.props.isToday && !this.props.aDayIsFocused,
            // "color-bright-4": this.props.isToday && this.props.aDayIsFocused,
          })}
        >
          {dayLabel}{monthLabel}{todayLabel}

        <textarea
          id={this.props.day.valueOf()}
          ref={(c) => this.textarea = c}
          className={classNames({
            "padding-0-25 padding-top-0 grow width-100": true,
            // "nowrap": !this.state.editing,
          })}
          onFocus={this.onFocus}
          onBlur={this.onBlur}
          onChange={this.onChange}
          value={this.state.text}
          onKeyDown={this.onKeyDown}
          readOnly={!this.props.connected}
          placeholder={placeholder}
        />

    );
  }
}

export default Day;
<commit_msg>Fixes menu wording<commit_after>import React, { Component } from "react";
import moment from "moment";
import classNames from "classnames";
import { debounce } from 'lodash/function';

class Day extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editing: false,
      text: "",
    };

    this.saveTodo = this.saveTodo.bind(this);
    this.onFocus = this.onFocus.bind(this);
    this.onBlur = this.onBlur.bind(this);
    this.onChange = this.onChange.bind(this);
    this.onKeyDown = this.onKeyDown.bind(this);

    this.saveTodoHandler = debounce(function () {
      this.saveTodo()
    }, 500);
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      text: nextProps.text
    });
  }

  componentDidUpdate() {
    // if (this.props.isTargetDay && !this.props.aDayIsFocused) {
    //   this.props.scrollTo(this.textarea);
    // }
  }

  saveTodo() {
    this.props.saveTodo(this.props.firebaseKey, this.props.day.valueOf(), this.state.text);
  }

  onFocus() {
    this.setState({editing: true});
    this.props.focusDay(this.props.day, this.textarea);
  }

  onBlur() {
    this.setState({
      editing: false
    });
    this.props.unfocusDay();
    this.saveTodo();
  }

  onChange(event) {
    this.setState({text: event.target.value})
    this.saveTodoHandler();
  }

  onKeyDown(event) {
    if (event.keyCode === 27 /*esc*/) {
      this.textarea.blur();
    }
  }

  render() {
    const colorNumber = this.props.isInFocusedWeek ? 2 : 1;

    const dayClasses = classNames({
      "day flex vertical padding-0-5 padding-top min-day-width border-1": true,
      [`color-${colorNumber+4}`]: !this.props.aDayIsFocused ||  this.props.isFocusedDay,
      [`color-${colorNumber+3}`]:  this.props.aDayIsFocused && !this.props.isFocusedDay,
      // [`bg-${this.props.weekNumber}`]: !this.props.isFocusedDay,
      // [`bg-bright-${this.props.weekNumber}`]: this.props.isFocusedDay,
    });

    let dayLabel, monthLabel;
    const todayLabel = this.props.isToday? ", Today" : false

    if (this.props.someday) {
      dayLabel = `Someday ${this.props.day.format("D")}`;
    }
    else {
      dayLabel = this.props.day.format("ddd DD");

      if (
          (
            this.props.weekNumber === 1 &&
            this.props.day.isSame(moment(this.props.day).startOf("isoweek"))
          ) ||
          this.props.day.isSame(moment(this.props.day).startOf("month"))
      ) {
        monthLabel = `, ${this.props.day.format("MMM YYYY")}`;
      }
    }

    let placeholder;
    if (this.props.anonymous) {
      if (this.props.someday && +this.props.day.format("D") === 1) {
        placeholder = "This row is not tied to any week and will always stay put. Useful for stuff like grocery lists and grandiose plans.";
      }
      // else if (this.props.weekNumber === 1 && +this.props.day.format("d") === 1) {
      //   placeholder = "This row is always last week."
      // }
      else if (this.props.weekNumber === 1) {
        if (+this.props.day.format("d") === 1) {
          placeholder = "This row is always the current week."
        }
        else if (+this.props.day.format("d") === 2) {
          placeholder = "Try typing something here. Text is auto-saved as you type.";
        }
        else if (+this.props.day.format("d") === 3) {
          placeholder = "You are currently using a temporary account. Your entries are saved in this browser only.";
        }
        else if (+this.props.day.format("d") === 4) {
          placeholder = "To access your entries in other browsers or devices, SIGN UP from the top menu. \n\nSigning up will also make these messages go away.";
        }
        else if (+this.props.day.format("d") === 5) {
          placeholder = "Protips:\n\nWhen using this app for todos I find it handy to mark completed tasks with an x. Like this ->\n\nTo move todos from one day to another, just cut and paste.";
        }
        else if (+this.props.day.format("d") === 6) {
          placeholder = "x 9:00 Dentist\n12:00 Lunch\n18:00 Play video games";
        }
      }
      else if (this.props.weekNumber === 2) {
        if (+this.props.day.format("d") === 1) {
          placeholder = "This row is always next week."
        }
        else if (+this.props.day.format("d") === 2) {
          placeholder = "To access weeks further in the future or in the past, ZOOM OUT from the top menu.";
        }
      }
    }

    return (

        <label
          htmlFor={this.props.day.valueOf()}
          className={classNames({
            "all-caps padding-0-25 padding-top-0": true,
            [`color-${colorNumber+3}`]: (this.props.aDayIsFocused && this.props.isFocusedDay) || !this.props.aDayIsFocused,
            [`color-${colorNumber+2}`]:  this.props.aDayIsFocused,
            [`color-bright-${colorNumber+4}`]: this.props.isToday && (!this.props.aDayIsFocused || (this.props.aDayIsFocused && this.props.isFocusedDay)),
            [`color-bright-${colorNumber+3}`]: this.props.isToday && !this.props.aDayIsFocused,
            // "color-5": !this.props.aDayIsFocused || this.props.isFocusedDay,
            // "color-3": this.props.aDayIsFocused && !this.props.isFocusedDay,
            // "color-bright-6": this.props.isToday && !this.props.aDayIsFocused,
            // "color-bright-4": this.props.isToday && this.props.aDayIsFocused,
          })}
        >
          {dayLabel}{monthLabel}{todayLabel}

        <textarea
          id={this.props.day.valueOf()}
          ref={(c) => this.textarea = c}
          className={classNames({
            "padding-0-25 padding-top-0 grow width-100": true,
            // "nowrap": !this.state.editing,
          })}
          onFocus={this.onFocus}
          onBlur={this.onBlur}
          onChange={this.onChange}
          value={this.state.text}
          onKeyDown={this.onKeyDown}
          readOnly={!this.props.connected}
          placeholder={placeholder}
        />

    );
  }
}

export default Day;
<|endoftext|>


<commit_before>'use strict';

var grunt = require('grunt');

// Check that the version we're exporting is the same one we expect in the
// package. This is not an ideal way to do this, but makes sure that we keep
// them in sync.
var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/;

module.exports = function() {
  var reactVersion = reactVersionExp.exec(
    grunt.file.read('./src/core/React.js')
  )[1];
  var npmReactVersion = grunt.file.readJSON('./npm-react/package.json').version;
  var reactToolsVersion = grunt.config.data.pkg.version;

  if (reactVersion !== reactToolsVersion) {
    grunt.log.error(
      'React version does not match react-tools version. Expected %s, saw %s',
      reactToolsVersion,
      reactVersion
    );
    return false;
  }
  if (npmReactVersion !== reactToolsVersion) {
    grunt.log.error(
      'npm-react version does not match react-tools veersion. Expected %s, saw %s',
      reactToolsVersion,
      npmReactVersion
    );
    return false;
  }
};
<commit_msg>Fix version check test<commit_after>'use strict';

var grunt = require('grunt');

// Check that the version we're exporting is the same one we expect in the
// package. This is not an ideal way to do this, but makes sure that we keep
// them in sync.
var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/;

module.exports = function() {
  var reactVersion = reactVersionExp.exec(
    grunt.file.read('./src/browser/React.js')
  )[1];
  var npmReactVersion = grunt.file.readJSON('./npm-react/package.json').version;
  var reactToolsVersion = grunt.config.data.pkg.version;

  if (reactVersion !== reactToolsVersion) {
    grunt.log.error(
      'React version does not match react-tools version. Expected %s, saw %s',
      reactToolsVersion,
      reactVersion
    );
    return false;
  }
  if (npmReactVersion !== reactToolsVersion) {
    grunt.log.error(
      'npm-react version does not match react-tools veersion. Expected %s, saw %s',
      reactToolsVersion,
      npmReactVersion
    );
    return false;
  }
};
<|endoftext|>