<commit_before>var vv = vv || {
    song: {},
    songs: {},
    storage: {},
};
vv.song = (function(){
    var tag = function(song, keys, other) {
        for (i in keys) {
            var key = keys[i];
            if (key in song) {
                return song[key];
            }
        }
        return other;
    }
    var getOrElse = function(song, key, other) {
       if (key in song) {
           return song[key];
       } else if (key == "AlbumSort") {
           return tag(song, ["Album"], other);
       } else if (key == "ArtistSort") {
           return tag(song, ["Artist"], other);
       } else if (key == "AlbumArtist") {
           return tag(song, ["Artist"], other);
       } else if (key == "AlbumArtistSort") {
           return tag(song, ["AlbumArtist", "Artist"], other);
       } else if (key == "AlbumSort") {
           return tag(song, ["Album"], other);
       } else {
           return other;
       }
    }
    var get = function(song, key) {
        return getOrElse(song, key, '[no ' + key + ']');
    }
    var str = function(song, keys) {
        var sortkey = '';
        for (i in keys) {
            sortkey += getOrElse(song, keys[i], ' ')
        }
        return sortkey;
    }
    return {
        getOrElse: getOrElse,
        get: get,
        str: str,
    };
}());
vv.songs = (function(){
    var sort = function(songs, keys) {
        return songs.map(function(song) {
            return [song, vv.song.str(song, keys)]
        }).sort(function (a, b) {
            if (a[1] < b[1]) { return -1; } else { return 1; };
        }).map(function(s) { return s[0]; });
    }
    var uniq = function(songs, key) {
        return songs.filter(function (song, i , self) {
            if (i == 0) {
                return true;
            } else if (vv.song.getOrElse(song, key, ' ') != vv.song.getOrElse(self[i - 1], key, ' ')) {
                return true;
            } else {
                return false;
            }
        });
    }
    var filter = function(songs, filters) {
        return songs.filter(function(song, i, self) {
            for (f in filters) {
                if (vv.song.get(song, f) != filters[f]) {
                    return false;
                }
            }
            return true;
        });
    }
    return {
        sort: sort,
        uniq: uniq,
        filter: filter,
    };
}());
vv.storage = (function(){
    var f = function(key, other) {
        var n = function(value) {
            if (typeof(value) == "undefined") {
                if (typeof(sessionStorage[key]) == "undefined") {
                    return other;
                }
                return JSON.parse(sessionStorage[key]);
            } else {
                sessionStorage[key] = JSON.stringify(value);
            }
        };
        return n;
    };
    return {
        tree: f("tree", []),
        current: f("current", {}),
        control: f("control", {}),
        playlist: f("playlist", []),
        library: {
            "AlbumArtist": f("library_AlbumArtist", []),
            "Genre": f("library_Genre", []),
        },
    };
}());

var TREE = {
    "AlbumArtist": {
        "sort":
            ["AlbumArtist", "Date", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["AlbumArtist", "plain"],
             ["Album", "album"],
             ["Title", "song"]
            ],
    },
    "Genre": {
        "sort":
            ["Genre", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["Genre", "plain"],
             ["Album", "album"],
             ["Title", "song"],
            ]
    },
    "date": {
        "sort":
            ["Date", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["Date", "plain"],
             ["Album", "album"],
             ["Title", "song"],
            ]
    }
}

var song_tree_list = function(tree) {
    if (!tree) {
        tree = vv.storage.tree();
    }
    var ls = [];
    if (tree.length == 0) {
        return _song_tree_list_root();
    } else {
        return _song_tree_list_child(tree);
    }
};
var song_tree_down = function(key, value) {
    var tree = vv.storage.tree();
    tree.push([key, value]);
    vv.storage.tree(tree);
};
var song_tree_abs = function(song) {
    var tree = vv.storage.tree();
    var i, root, key, selected;
    if (tree.length != 0) {
        tree = [tree[0]];
        root = tree[0][1];
        selected = TREE[root]["tree"];
        for (i in selected) {
            if (i == selected.length - 1) {
                break;
            }
            key = selected[i][0];
            tree.push([key, vv.song.get(song, key)]);
        }
        vv.storage.tree(tree);
    }
};
var song_tree_up = function() {
    var tree = vv.storage.tree()
    if (tree.length > 0) {
        tree.pop();
    }
    vv.storage.tree(tree)
};
var _song_tree_list_root = function() {
    var ret = [];
    var rootname = "";
    for (rootname in TREE) {
        ret.push({"root": rootname});
    }
    return ["root", ret, "plain"];
}
var _song_tree_list_child = function(tree) {
    var root = tree[0][1],
        library = vv.storage.library[root](),
        filters = {},
        key = TREE[root]["tree"][tree.length - 1][0],
        style = TREE[root]["tree"][tree.length - 1][1],
        song = {};
    for (leef in tree) {
        if (leef == 0) { continue; }
        filters[tree[leef][0]] = tree[leef][1];
    }
    library = vv.songs.filter(library, filters);
    library = vv.songs.uniq(library, key);
    return [key, library, style];
};

var MainView = function() {
    var mainview = function() {};
    var p = mainview.prototype;
    p.show_current = function() {
        $("#list").hide();
        $("#current").show();
    }
    p.show_list = function() {
        $("#current").hide();
        p.update_tree();
        $("#list").show();
    }
    p.up_list = function() {
        if ($("#current").css("display") == "none") {
            song_tree_up();
        } else {
            var current = vv.storage.current();
            song_tree_abs(current);
        }
        p.update_tree();
    }

    p.update_tree = function() {
        var current = {};
        var control = {};
        var tree = vv.storage.tree();
        var key, songs, style;
        var song = {};
        var root = "";
        // [key, songs, style] = song_tree_list(tree);
        var keysongs = song_tree_list(tree);
        key = keysongs[0];
        songs = keysongs[1];
        style = keysongs[2];
        if (style == "song") {
            current = vv.storage.current();
            control = vv.storage.control();
        }
        if (tree.length != 0) {
            root = tree[0][1];
        }
        $("#list ol").empty();
        for (i in songs) {
            song = songs[i];
            $("#list ol").append("

");
            var added = $("#list ol li:last-child");
            added.attr("key", vv.song.get(song, key));
            added.attr("uri", song["file"]);
            if (style == "song") {
                added.append(""+vv.song.get(song, "TrackNumber")+"");
                added.append(""+vv.song.get(song, "Title")+"");
                if (vv.song.get(song, "Artist") != vv.song.get(song, "AlbumArtist")) {
                    added.append(""+vv.song.get(song, "Artist")+"");
                }
                if (vv.song.get(song, "file") == vv.song.get(current, "file")) {
                    added.append(""+vv.song.get(song, "Length")+"");
                    added.append("/");
                }
                added.append(""+vv.song.get(song, "Length")+"");
            } else if (style == "album") {
                added.append(""+vv.song.get(song, "Date")+"");
                added.append(""+vv.song.get(song, "Album")+"");
                added.append(""+vv.song.get(song, "AlbumArtist")+"");
            } else {
                added.text(vv.song.get(song, key));
            }
        }
        $("#list ol li").bind("click", function() {
            var value = $(this).attr("key"),
                uri = $(this).attr("uri");
            if (tree.length == 0 || tree.length != TREE[root]["tree"].length) {
                song_tree_down(key, value);
                p.show_list();
            } else {
                $.ajax({
                    type: "POST",
                    url: "/api/songs",
                    contentType: 'application/json',
                    data: JSON.stringify(
                            {"action": "sort",
                             "keys": TREE[root]["sort"],
                             "uri": uri
                            }),
                    cache: false,
                    success: function(data, status) {
				        if (status == "success" && data["errors"] == null) {
				        }
			        },
                });
            }
            return false;
        });
    };
    return mainview;
}();

var update_song_request = function() {
    $.ajax({
        type: "GET",
        url: "api/songs/current",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                vv.storage.current(data["data"]);
                $("#current .title").text(data["data"]["Title"])
                $("#current .artist").text(data["data"]["Artist"])
                var key;
                $("#current .detail").empty();
                for (key in data["data"]) {
                    if (key == "Title" || key == "Artist") {
                        continue;
                    }
                    $("#current .detail").append("
" + key + ": " + data["data"][key] + "
");
                }
                var tree = vv.storage.tree();
                if (tree.length != 0 && tree.length == TREE[tree[0][1]]["tree"].length) {
                    song_tree_abs(data["data"]);
                }
                // update elapsed tag
                mainview.update_tree();
			}
		},
    })
};

var update_control_data_request = function() {
    $.ajax({
        type: "GET",
        url: "api/control",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                vv.storage.control(data["data"]);
                refreash_control_data();
			}
		},
    })
    refreash_control_data();
};

var refreash_control_data = function() {
    data = vv.storage.control()
    if ('state' in data) {
        var elapsed = parseInt(data["song_elapsed"] * 1000)
        var current = elapsed
        var last_modified = parseInt(data["last_modified"] * 1000)
        var date = new Date()
        if (data["state"] == "play") {
            current += date.getTime() - last_modified
        }
        var label = parseSongTime(current / 1000);
        if ($(".elapsed").text() != label) {
            $(".elapsed").text(label);
        }
    }
};

var update_library_request = function() {
    $.ajax({
        type: "GET",
        url: "api/library",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                vv.storage.library["AlbumArtist"](
                    vv.songs.sort(data["data"], TREE["AlbumArtist"]["sort"]));
                vv.storage.library["Genre"](
                    vv.songs.sort(data["data"], TREE["Genre"]["sort"]));
			}
		},
    })
}

function parseSongTime(val) {
    var current = parseInt(val)
    var min = parseInt(current / 60)
    var sec = current % 60
    return min + ':' + ("0" + sec).slice(-2)
}

function getOrElse(m, k, v) {
    return k in m? m[k] : v;
}

$(document).ready(function(){
    mainview = new MainView();
    $("#menu .up").bind("click", function() {
        mainview.up_list();
        mainview.show_list();
        return false;
    });
    $("#menu .back").bind("click", function() {
        mainview.show_current();
        return false;
    });
    $("#menu .reset").bind("click", function() {
        sessionStorage.tree = "[]";
        sessionStorage.current = "{}";
        sessionStorage.control = "{}";
        sessionStorage.playlist = "[]";
        sessionStorage.library = "[]";
        sessionStorage.library_AlbumArtist = "[]";
        sessionStorage.library_Genre = "[]";
        return false;
    });
    $("#playback .prev").bind("click", function() {
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": "prev"},
            cache: false
        })
        return false;
    });
    $("#playback .play").bind("click", function() {
        var state = getOrElse(vv.storage.control(), "state", "stopped");
        var action = state == "play" ? "pause" : "play"
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": action},
            cache: false
        })
        return false;
    });
    $("#playback .next").bind("click", function() {
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": "next"},
            cache: false
        })
        return false;
    });

    function polling() {
        update_song_request()
        update_control_data_request()
        update_library_request()
		setTimeout(polling, 1000);
    }
	polling();
});
<commit_msg>remove sessionStorage<commit_after>var vv = vv || {
    song: {},
    songs: {},
    storage: {},
};
vv.song = (function(){
    var tag = function(song, keys, other) {
        for (i in keys) {
            var key = keys[i];
            if (key in song) {
                return song[key];
            }
        }
        return other;
    }
    var getOrElse = function(song, key, other) {
       if (key in song) {
           return song[key];
       } else if (key == "AlbumSort") {
           return tag(song, ["Album"], other);
       } else if (key == "ArtistSort") {
           return tag(song, ["Artist"], other);
       } else if (key == "AlbumArtist") {
           return tag(song, ["Artist"], other);
       } else if (key == "AlbumArtistSort") {
           return tag(song, ["AlbumArtist", "Artist"], other);
       } else if (key == "AlbumSort") {
           return tag(song, ["Album"], other);
       } else {
           return other;
       }
    }
    var get = function(song, key) {
        return getOrElse(song, key, '[no ' + key + ']');
    }
    var str = function(song, keys) {
        var sortkey = '';
        for (i in keys) {
            sortkey += getOrElse(song, keys[i], ' ')
        }
        return sortkey;
    }
    return {
        getOrElse: getOrElse,
        get: get,
        str: str,
    };
}());
vv.songs = (function(){
    var sort = function(songs, keys) {
        return songs.map(function(song) {
            return [song, vv.song.str(song, keys)]
        }).sort(function (a, b) {
            if (a[1] < b[1]) { return -1; } else { return 1; };
        }).map(function(s) { return s[0]; });
    }
    var uniq = function(songs, key) {
        return songs.filter(function (song, i , self) {
            if (i == 0) {
                return true;
            } else if (vv.song.getOrElse(song, key, ' ') != vv.song.getOrElse(self[i - 1], key, ' ')) {
                return true;
            } else {
                return false;
            }
        });
    }
    var filter = function(songs, filters) {
        return songs.filter(function(song, i, self) {
            for (f in filters) {
                if (vv.song.get(song, f) != filters[f]) {
                    return false;
                }
            }
            return true;
        });
    }
    return {
        sort: sort,
        uniq: uniq,
        filter: filter,
    };
}());
vv.storage = (function(){
    var tree = [];
    var current = [];
    var control = [];
    var library = {
        "AlbumArtist": [],
         "Genre": [],
    }

    var save = function() {
        localStorage.tree = JSON.stringify(tree);
    }
    var load = function() {
        if (localStorage.tree) {
            tree = JSON.parse(localStorage.tree);
        }
    }
    load();
    return {
        tree: tree,
        current: current,
        control: control,
        library: library,
        save: save,
        load: load,
    };
}());

var TREE = {
    "AlbumArtist": {
        "sort":
            ["AlbumArtist", "Date", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["AlbumArtist", "plain"],
             ["Album", "album"],
             ["Title", "song"]
            ],
    },
    "Genre": {
        "sort":
            ["Genre", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["Genre", "plain"],
             ["Album", "album"],
             ["Title", "song"],
            ]
    },
    "date": {
        "sort":
            ["Date", "Album", "DiscNumber", "TrackNumber", "Title", "file"],
        "tree":
            [["Date", "plain"],
             ["Album", "album"],
             ["Title", "song"],
            ]
    }
}

var song_tree_list = function() {
    var ls = [];
    if (vv.storage.tree.length == 0) {
        return _song_tree_list_root();
    } else {
        return _song_tree_list_child();
    }
};
var song_tree_down = function(key, value) {
    vv.storage.tree.push([key, value]);
    vv.storage.save();
};
var song_tree_abs = function(song) {
    var i, root, key, selected;
    if (vv.storage.tree.length != 0) {
        vv.storage.tree = [vv.storage.tree[0]];
        vv.storage.save();
        root = vv.storage.tree[0][1];
        selected = TREE[root]["tree"];
        for (i in selected) {
            if (i == selected.length - 1) {
                break;
            }
            key = selected[i][0];
            vv.storage.tree.push([key, vv.song.get(song, key)]);
        }
    }
};
var song_tree_up = function() {
    if (vv.storage.tree.length > 0) {
        vv.storage.tree.pop();
    }
    vv.storage.save();
};
var _song_tree_list_root = function() {
    var ret = [];
    var rootname = "";
    for (rootname in TREE) {
        ret.push({"root": rootname});
    }
    return ["root", ret, "plain"];
}
var _song_tree_list_child = function() {
    var root = vv.storage.tree[0][1],
        library = vv.storage.library[root],
        filters = {},
        key = TREE[root]["tree"][vv.storage.tree.length - 1][0],
        style = TREE[root]["tree"][vv.storage.tree.length - 1][1],
        song = {};
    for (leef in vv.storage.tree) {
        if (leef == 0) { continue; }
        filters[vv.storage.tree[leef][0]] = vv.storage.tree[leef][1];
    }
    library = vv.songs.filter(library, filters);
    library = vv.songs.uniq(library, key);
    return [key, library, style];
};

var MainView = function() {
    var mainview = function() {};
    var p = mainview.prototype;
    p.show_current = function() {
        $("#list").hide();
        $("#current").show();
    }
    p.show_list = function() {
        $("#current").hide();
        p.update_tree();
        $("#list").show();
    }
    p.up_list = function() {
        if ($("#current").css("display") == "none") {
            song_tree_up();
        } else {
            song_tree_abs(vv.storage.current);
        }
        p.update_tree();
    }

    p.update_tree = function() {
        var key, songs, style;
        var song = {};
        var root = "";
        var keysongs = song_tree_list();
        key = keysongs[0];
        songs = keysongs[1];
        style = keysongs[2];
        if (vv.storage.tree.length != 0) {
            root = vv.storage.tree[0][1];
        }
        $("#list ol").empty();
        for (i in songs) {
            song = songs[i];
            $("#list ol").append("

");
            var added = $("#list ol li:last-child");
            added.attr("key", vv.song.get(song, key));
            added.attr("uri", song["file"]);
            if (style == "song") {
                added.append(""+vv.song.get(song, "TrackNumber")+"");
                added.append(""+vv.song.get(song, "Title")+"");
                if (vv.song.get(song, "Artist") != vv.song.get(song, "AlbumArtist")) {
                    added.append(""+vv.song.get(song, "Artist")+"");
                }
                if (vv.song.get(song, "file") == vv.song.get(vv.storage.current, "file")) {
                    added.append(""+vv.song.get(song, "Length")+"");
                    added.append("/");
                }
                added.append(""+vv.song.get(song, "Length")+"");
            } else if (style == "album") {
                added.append(""+vv.song.get(song, "Date")+"");
                added.append(""+vv.song.get(song, "Album")+"");
                added.append(""+vv.song.get(song, "AlbumArtist")+"");
            } else {
                added.text(vv.song.get(song, key));
            }
        }
        $("#list ol li").bind("click", function() {
            var value = $(this).attr("key"),
                uri = $(this).attr("uri");
            if (vv.storage.tree.length == 0 ||
                vv.storage.tree.length != TREE[root]["tree"].length) {
                song_tree_down(key, value);
                p.show_list();
            } else {
                $.ajax({
                    type: "POST",
                    url: "/api/songs",
                    contentType: 'application/json',
                    data: JSON.stringify(
                            {"action": "sort",
                             "keys": TREE[root]["sort"],
                             "uri": uri
                            }),
                    cache: false,
                    success: function(data, status) {
				        if (status == "success" && data["errors"] == null) {
				        }
			        },
                });
            }
            return false;
        });
    };
    return mainview;
}();

var update_song_request = function() {
    $.ajax({
        type: "GET",
        url: "api/songs/current",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                vv.storage.current = data["data"];
                $("#current .title").text(data["data"]["Title"])
                $("#current .artist").text(data["data"]["Artist"])
                var key;
                $("#current .detail").empty();
                for (key in data["data"]) {
                    if (key == "Title" || key == "Artist") {
                        continue;
                    }
                    $("#current .detail").append("
" + key + ": " + data["data"][key] + "
");
                }
                if (vv.storage.tree.length != 0 &&
                    vv.storage.tree.length == TREE[vv.storage.tree[0][1]]["tree"].length) {
                    song_tree_abs(data["data"]);
                }
                // update elapsed tag
                mainview.update_tree();
			}
		},
    })
};

var update_control_data_request = function() {
    $.ajax({
        type: "GET",
        url: "api/control",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                vv.storage.control = data["data"];
                refreash_control_data();
			}
		},
    })
    refreash_control_data();
};

var refreash_control_data = function() {
    data = vv.storage.control
    if ('state' in data) {
        var elapsed = parseInt(data["song_elapsed"] * 1000)
        var current = elapsed
        var last_modified = parseInt(data["last_modified"] * 1000)
        var date = new Date()
        if (data["state"] == "play") {
            current += date.getTime() - last_modified
        }
        var label = parseSongTime(current / 1000);
        if ($(".elapsed").text() != label) {
            $(".elapsed").text(label);
        }
    }
};

var update_library_request = function() {
    $.ajax({
        type: "GET",
        url: "api/library",
        ifModified: true,
		dataType: "json",
        success: function(data, status) {
			if (status == "success" && data["errors"] == null) {
                vv.storage.library["AlbumArtist"] = vv.songs.sort(data["data"], TREE["AlbumArtist"]["sort"]);
                vv.storage.library["Genre"] = vv.songs.sort(data["data"], TREE["Genre"]["sort"]);
			}
		},
    })
}

function parseSongTime(val) {
    var current = parseInt(val)
    var min = parseInt(current / 60)
    var sec = current % 60
    return min + ':' + ("0" + sec).slice(-2)
}

function getOrElse(m, k, v) {
    return k in m? m[k] : v;
}

$(document).ready(function(){
    mainview = new MainView();
    $("#menu .up").bind("click", function() {
        mainview.up_list();
        mainview.show_list();
        return false;
    });
    $("#menu .back").bind("click", function() {
        mainview.show_current();
        return false;
    });
    $("#menu .reset").bind("click", function() {
        sessionStorage.tree = "[]";
        sessionStorage.current = "{}";
        sessionStorage.control = "{}";
        sessionStorage.playlist = "[]";
        sessionStorage.library = "[]";
        sessionStorage.library_AlbumArtist = "[]";
        sessionStorage.library_Genre = "[]";
        return false;
    });
    $("#playback .prev").bind("click", function() {
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": "prev"},
            cache: false
        })
        return false;
    });
    $("#playback .play").bind("click", function() {
        var state = getOrElse(vv.storage.control, "state", "stopped");
        var action = state == "play" ? "pause" : "play"
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": action},
            cache: false
        })
        return false;
    });
    $("#playback .next").bind("click", function() {
        $.ajax({
            type: "GET",
            url: "/api/songs/current",
            data: {"action": "next"},
            cache: false
        })
        return false;
    });

    function polling() {
        update_song_request()
        update_control_data_request()
        update_library_request()
		setTimeout(polling, 1000);
    }
	polling();
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>removing app.js<commit_after><|endoftext|>


<commit_before>const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const path = require('path');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const passport = require('passport');

require('dotenv').config();

const app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'public')));
app.use(cookieParser());
app.use(
  session({
    key: process.env.SECRET_KEY,
    secret: process.env.SECRET_KEY,
    resave: false,
    saveUninitialized: true,
  }),
);
app.use(passport.initialize());
app.use(passport.session());

const PORT = 3001 || process.env.PORT;

app.listen(PORT, ()=>{
    console.log(`server is running on port ${PORT}`);
})

app.get('/',(req,res)=>{
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

const authRoutes = require('./routes/auth-routes');
app.use('/auth', authRoutes);

const profileRoutes = require('./routes/profile-routes');
app.use('/profile/', profileRoutes);

const messageRoutes = require('./routes/message-routes');
app.use('/messages', messageRoutes);

const eventRoutes = require('./routes/event-routes');
app.use('/events', eventRoutes);

app.get('*',(req,res)=>{
    res.status(400).json({
        message: 'Not found!',
      });
});
<commit_msg>change unexpected token<commit_after>const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const path = require('path');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const passport = require('passport');

require('dotenv').config();

const app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'public')));
app.use(cookieParser());
app.use(
  session({
    key: process.env.SECRET_KEY,
    secret: process.env.SECRET_KEY,
    resave: false,
    saveUninitialized: true,
  }));
app.use(passport.initialize());
app.use(passport.session());

const PORT = 3001 || process.env.PORT;

app.listen(PORT, ()=>{
    console.log(`server is running on port ${PORT}`);
})

app.get('/',(req,res)=>{
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

const authRoutes = require('./routes/auth-routes');
app.use('/auth', authRoutes);

const profileRoutes = require('./routes/profile-routes');
app.use('/profile/', profileRoutes);

const messageRoutes = require('./routes/message-routes');
app.use('/messages', messageRoutes);

const eventRoutes = require('./routes/event-routes');
app.use('/events', eventRoutes);

app.get('*',(req,res)=>{
    res.status(400).json({
        message: 'Not found!',
      });
});
<|endoftext|>


<commit_before>/** @jsx React.DOM */

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var http = require('http');
var spawn = require('child_process').spawn;

var App = React.createClass({
  getInitialState: function() {
    return {
      blogDidLoad: false,
      editMode: false,
      path: '',
      posts: [],
      url: 'http://localhost:4000'
    }
  },
  setPath: function(path) {
    this.setState({ path: path });
  },
  setPosts: function(posts) {
    this.setState({ posts: posts });
  },
  setBlogDidLoad: function(value) {
    this.setState({ blogDidLoad: value })
  },
  setEditMode: function(value) {
    this.setState({ editMode: value });
  },
  render: function() {
    return (
      <Home
        url={this.state.url}
        posts={this.state.posts}
        editMode={this.state.editMode}
        blogDidLoad={this.state.blogDidLoad}
        path={this.state.path}
        setEditMode={this.setEditMode}
        setBlogDidLoad={this.setBlogDidLoad}
        setPath={this.setPath}
        setPosts={this.setPosts}
      />
    );
  }
});

var Home = React.createClass({
  getInitialState: function() {
    return {
      appPath: window.location.pathname.split('/').slice(0,-1).join('/'),
      savingText: ''
    }
  },
  componentDidMount: function() {
    this.refs.fileDialog.getDOMNode().setAttribute('nwdirectory', '');
    this.refs.fileDialog.getDOMNode().addEventListener('change', this.setPath);

    this.refs.motionLoop.getDOMNode().setAttribute('autoplay', '');
    this.refs.motionLoop.getDOMNode().setAttribute('loop', '');
  },
  componentDidUpdate: function() {
    if (this.props.blogDidLoad) {
      this.refs.myIframe.getDOMNode().addEventListener('load', this.iframeLoaded, true);
    }
  },
  iframeLoaded: function() {
    console.log('calling');
    var path = this.refs.myIframe.getDOMNode().contentWindow.location.pathname;
    var url = path.replace(/\//g, '');
    var posts = _.map(this.props.posts, function(post) { return post.split('-').slice(3).join('-').split('.').shift() });

    // compensate for topbar
//    this.refs.myIframe.getDOMNode().contentWindow.document.body.style.marginTop = '40px';

    if (_.contains(posts, url)) {
      this.props.setEditMode(true);

      var container = this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByClassName('post-content')[0];
      container.style.outline = 'none';

      // pen.js file
      var script = this.refs.myIframe.getDOMNode().contentWindow.document.createElement('script');
      script.type = 'text/javascript';

      script.onload = function(){
        console.log('pen loaded inside iframe');

        // instantiate pen
        var scriptInline = this.refs.myIframe.getDOMNode().contentWindow.document.createElement('script');
        scriptInline.type = 'text/javascript';
        scriptInline.text = 'var editor = new Pen(document.getElementsByClassName("post-content")[0]);';
        this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByTagName('head')[0].appendChild(scriptInline);
      }.bind(this);

      script.src = 'file://' + this.state.appPath + '/assets/js/lib/pen.js';
      this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByTagName('head')[0].appendChild(script);

      // pen styles
      var cssLink = this.refs.myIframe.getDOMNode().contentWindow.document.createElement('link');
      cssLink.href = 'file://' + this.state.appPath + '/assets/css/lib/pen.css';
      cssLink.rel = 'stylesheet';
      cssLink.type = 'text/css';
      this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByTagName('head')[0].appendChild(cssLink);
    }

    this.refs.myIframe.getDOMNode().contentWindow.document.addEventListener('keyup', _.debounce(this.handleKeyUp, 1000), true);
  },
  handleBlogDidLoad: function(value) {
    console.log('changing blog load value to ' + value);
    this.props.setBlogDidLoad(value);
  },
  handleClick: function() {
    this.refs.fileDialog.getDOMNode().click();
  },
  handlesetPosts: function(path) {
    var files = fs.readdirSync(path + '/_posts');

    var posts = _.filter(files, function(file) {
      var extension = file.split('.').pop();
      return extension === 'md' || extension === 'markdown'
    });

    this.props.setPosts(posts);
  },
  setPath: function(e) {
    this.props.setPath(e.target.value);

    var jekyll = spawn('jekyll', ['serve', '--watch', '-s', e.target.value]);

    jekyll.stdout.on('data', function (data) {
      var line = data.toString();
      var serverRunning = 'Server running...';
      var portInUse = 'Address already in use';
      if (line.match(serverRunning) && line.match(serverRunning).length ||
        line.match(portInUse) && line.match(portInUse).length) {
        this.handleBlogDidLoad(true);
      }
    }.bind(this));

    process.on('exit', function() {
      jekyll.kill();
    });

    this.handlesetPosts(e.target.value);
  },
  save: function() {
    var postsDir = path.join(this.props.path, '_posts');
    var location = this.refs.myIframe.getDOMNode().contentWindow.location.pathname;
    var postSlug = location.replace(/\//g, '');
    var container = this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByClassName('post-content')[0];
    var markdown = md(container.innerHTML, { inline:true });
    markdown = markdown.replace('’', '\'');
    _.each(this.props.posts, function(postFile) {
      if (postFile.match(postSlug)) {
        var file = fs.readFileSync(path.join(postsDir, postFile), 'utf8');
        var yaml = file.split('---').slice(0,2);
        yaml.push('\n\n');
        yaml = yaml.join('---');
        fs.writeFileSync(path.join(postsDir, postFile), yaml);
        fs.appendFileSync(path.join(postsDir, postFile), markdown);
        console.log('File saved');
      }
    });
  },
  handleKeyUp: function(e) {

    // Ignore arrow keys
    if (e.keyCode == '37' || e.keyCode == '38' ||
      e.keyCode == '39' || e.keyCode == '40') {
      return false;
    }

    console.log('keyup' + e)
      this.save();

      this.setState({
        savingText: 'Saving...'
      });

      setTimeout(function() {
        this.setState({
          savingText: ''
        });
      }.bind(this), 1000);
  },
  render: function() {
    if (this.props.blogDidLoad) {
      document.body.classList.remove('cover');
      return (

          <Topbar
            save={this.save}
            savingText={this.state.savingText}
            setBlogDidLoad={this.props.setBlogDidLoad}
            blogDidLoad={this.props.blogDidLoad}
            setEditMode={this.props.setEditMode}
            editMode={this.props.editMode}
            path={this.props.path}
          />

      );
    } else {
      return (

          <video ref="motionLoop">
            <source src="assets/video/videohive_glossy-silver.webmhd.webm" type="video/webm" />
          </video>

Jekyll Blog Editor

          <button ref="openBlog" onClick={this.handleClick} className="btn outline">Open Blog</button>
          <input ref="fileDialog" type="file" className="hidden" />

Select a local Jekyll blog

      );
    }
  }
});

var Topbar = React.createClass({
  componentDidMount: function() {
    $('span[rel=tipsy]').tipsy({ fade: true });
  },
  componentDidUpdate: function() {
    $('span[rel=tipsy]').tipsy({ fade: true });
  },
  handleHome: function() {
    this.props.setBlogDidLoad(false);
    this.props.setEditMode(false);
  },
  handlePublish: function() {

  },
  handleNewPost: function() {

  },
  handleSettings: function() {

  },
  render: function() {
    if (this.props.editMode) {
      var publishLink =

;
      var savingText =
{this.props.savingText}
;
    }
    var blogName = this.props.path.split('/').slice(-1).toString();
    return (

            {blogName}

              {publishLink}
              {savingText}

    );
  }
});

React.renderComponent(<App />, document.body);

// ========================
// Node Webkit Live Reload
// ========================

var loc = './';

fs.watch(loc, function() {
  if (location) {
    location.reload();
  }
});<commit_msg>cleanup and refactored handlesave function<commit_after>/** @jsx React.DOM */

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var http = require('http');
var spawn = require('child_process').spawn;

var App = React.createClass({
  getInitialState: function() {
    return {
      blogDidLoad: false,
      editMode: false,
      path: '',
      posts: [],
      url: 'http://localhost:4000'
    }
  },
  setPath: function(path) {
    this.setState({ path: path });
  },
  setPosts: function(posts) {
    this.setState({ posts: posts });
  },
  setBlogDidLoad: function(value) {
    this.setState({ blogDidLoad: value })
  },
  setEditMode: function(value) {
    this.setState({ editMode: value });
  },
  render: function() {
    return (
      <Home
        url={this.state.url}
        posts={this.state.posts}
        editMode={this.state.editMode}
        blogDidLoad={this.state.blogDidLoad}
        path={this.state.path}
        setBlogDidLoad={this.setBlogDidLoad}
        setEditMode={this.setEditMode}
        setPath={this.setPath}
        setPosts={this.setPosts}
      />
    );
  }
});

var Home = React.createClass({
  getInitialState: function() {
    return {
      appPath: window.location.pathname.split('/').slice(0,-1).join('/'),
      savingText: ''
    }
  },
  componentDidMount: function() {
    this.refs.fileDialog.getDOMNode().setAttribute('nwdirectory', '');
    this.refs.fileDialog.getDOMNode().addEventListener('change', this.setPath);

    this.refs.motionLoop.getDOMNode().setAttribute('autoplay', '');
    this.refs.motionLoop.getDOMNode().setAttribute('loop', '');
  },
  componentDidUpdate: function() {
    if (this.props.blogDidLoad) {
      this.refs.myIframe.getDOMNode().addEventListener('load', this.iframeLoaded, true);
    }
  },
  iframeLoaded: function() {
    console.log('calling');
    var path = this.refs.myIframe.getDOMNode().contentWindow.location.pathname;
    var url = path.replace(/\//g, '');
    var posts = _.map(this.props.posts, function(post) { return post.split('-').slice(3).join('-').split('.').shift() });

    // compensate for topbar
//    this.refs.myIframe.getDOMNode().contentWindow.document.body.style.marginTop = '40px';

    if (_.contains(posts, url)) {
      this.props.setEditMode(true);

      var container = this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByClassName('post-content')[0];
      container.style.outline = 'none';

      // pen.js file
      var script = this.refs.myIframe.getDOMNode().contentWindow.document.createElement('script');
      script.type = 'text/javascript';

      script.onload = function(){
        console.log('pen loaded inside iframe');

        // instantiate pen
        var scriptInline = this.refs.myIframe.getDOMNode().contentWindow.document.createElement('script');
        scriptInline.type = 'text/javascript';
        scriptInline.text = 'var editor = new Pen(document.getElementsByClassName("post-content")[0]);';
        this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByTagName('head')[0].appendChild(scriptInline);
      }.bind(this);

      script.src = 'file://' + this.state.appPath + '/assets/js/lib/pen.js';
      this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByTagName('head')[0].appendChild(script);

      // pen styles
      var cssLink = this.refs.myIframe.getDOMNode().contentWindow.document.createElement('link');
      cssLink.href = 'file://' + this.state.appPath + '/assets/css/lib/pen.css';
      cssLink.rel = 'stylesheet';
      cssLink.type = 'text/css';
      this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByTagName('head')[0].appendChild(cssLink);
    }

    this.refs.myIframe.getDOMNode().contentWindow.document.addEventListener('keyup', _.debounce(this.handleKeyUp, 1000), true);
  },
  handleBlogDidLoad: function(value) {
    console.log('changing blog load value to ' + value);
    this.props.setBlogDidLoad(value);
  },
  handleClick: function() {
    this.refs.fileDialog.getDOMNode().click();
  },
  handlesetPosts: function(path) {
    var files = fs.readdirSync(path + '/_posts');

    var posts = _.filter(files, function(file) {
      var extension = file.split('.').pop();
      return extension === 'md' || extension === 'markdown'
    });

    this.props.setPosts(posts);
  },
  setPath: function(e) {
    this.props.setPath(e.target.value);

    var jekyll = spawn('jekyll', ['serve', '--watch', '-s', e.target.value]);

    jekyll.stdout.on('data', function (data) {
      var line = data.toString();
      var serverRunning = 'Server running...';
      var portInUse = 'Address already in use';
      if (line.match(serverRunning) && line.match(serverRunning).length ||
        line.match(portInUse) && line.match(portInUse).length) {
        this.handleBlogDidLoad(true);
      }
    }.bind(this));

    process.on('exit', function() {
      jekyll.kill();
    });

    this.handlesetPosts(e.target.value);
  },
  handleSave: function() {
    var postsDir = path.join(this.props.path, '_posts');
    var location = this.refs.myIframe.getDOMNode().contentWindow.location.pathname;
    var postSlug = location.replace(/\//g, '');
    var container = this.refs.myIframe.getDOMNode().contentWindow.document.getElementsByClassName('post-content')[0];
    var markdown = md(container.innerHTML, { inline:true });
    markdown = markdown.replace('’', '\'');
    _.each(this.props.posts, function(postFile) {
      if (postFile.match(postSlug)) {
        var file = fs.readFileSync(path.join(postsDir, postFile), 'utf8');
        var yaml = file.split('---').slice(0,2);
        yaml.push('\n\n');
        yaml = yaml.join('---');
        fs.writeFileSync(path.join(postsDir, postFile), yaml);
        fs.appendFileSync(path.join(postsDir, postFile), markdown);
        console.log('File saved');
      }
    });
  },
  handleKeyUp: function(e) {
    if (e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40) {
      return false;
    }
    this.handleSave();
    this.setState({ savingText: 'Saving...' });
    setTimeout(function() {
      this.setState({ savingText: '' });
    }.bind(this), 1000);
  },
  render: function() {
    if (this.props.blogDidLoad) {
      document.body.classList.remove('cover');
      return (

          <Topbar
            handleSave={this.handleSave}
            savingText={this.state.savingText}
            setBlogDidLoad={this.props.setBlogDidLoad}
            blogDidLoad={this.props.blogDidLoad}
            setEditMode={this.props.setEditMode}
            editMode={this.props.editMode}
            path={this.props.path}
          />

      );
    } else {
      return (

          <video ref="motionLoop">
            <source src="assets/video/videohive_glossy-silver.webmhd.webm" type="video/webm" />
          </video>

Jekyll Blog Editor

          <button ref="openBlog" onClick={this.handleClick} className="btn outline">Open Blog</button>
          <input ref="fileDialog" type="file" className="hidden" />

Select a local Jekyll blog

      );
    }
  }
});

var Topbar = React.createClass({
  componentDidMount: function() {
    $('span[rel=tipsy]').tipsy({ fade: true });
  },
  componentDidUpdate: function() {
    $('span[rel=tipsy]').tipsy({ fade: true });
  },
  handleHome: function() {
    this.props.setBlogDidLoad(false);
    this.props.setEditMode(false);
  },
  handlePublish: function() {

  },
  handleNewPost: function() {

  },
  handleSettings: function() {

  },
  render: function() {
    if (this.props.editMode) {
      var publishLink =

;
      var savingText =
{this.props.savingText}
;
    }
    var blogName = this.props.path.split('/').slice(-1).toString();
    return (

            {blogName}

              {publishLink}
              {savingText}

    );
  }
});

React.renderComponent(<App />, document.body);

// ========================
// Node Webkit Live Reload
// ========================

var loc = './';

fs.watch(loc, function() {
  if (location) {
    location.reload();
  }
});<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>adde requires for mongodb and monk<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// mongoDB
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/PlanIt');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

var handlebars = require('handlebars');
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var version = '2.1.0';

// Handlebars Helper
handlebars.registerHelper('ifCond', function(v1, operator, v2, options) {
  switch (operator) {
    case '==':
      return (v1 == v2) ? options.fn(this) : options.inverse(this);
      break;
    case '===':
      return (v1 === v2) ? options.fn(this) : options.inverse(this);
      break;
    case '<':
      return (v1 < v2) ? options.fn(this) : options.inverse(this);
      break;
    case '<=':
      return (v1 <= v2) ? options.fn(this) : options.inverse(this);
      break;
    case '>':
      return (v1 > v2) ? options.fn(this) : options.inverse(this);
      break;
    case '>=':
      return (v1 >= v2) ? options.fn(this) : options.inverse(this);
      break;
    default:
      return options.inverse(this);
      break;
  }
  return options.inverse(this);
});

var config = {
  path: {
    css: './src/css',
    js: './src/js'
  },
  dist: {
    sublime: '/dist/sublime',
    webstorm: '/dist/webstorm'
  }
};
var prefixName = 'am-';
var fsOptions = {encoding: 'utf8'};

var data = (function readData() {
  var cssFiles = fs.readdirSync(config.path.css);
  var jsFiles = fs.readdirSync(config.path.js);
  var cssTpl = [];
  var cssConfig = [];
  var jsTpl = [];
  var jsConfig = [];

  _.each(cssFiles, function(data) {
    cssTpl.push(fs.readFileSync(path.join(config.path.css, data, 'tpl.hbs'), fsOptions));
    cssConfig.push(require('./' + path.join(config.path.css, data, 'config.js')));
  });

  _.each(jsFiles, function(data) {
    jsTpl.push(fs.readFileSync(path.join(config.path.js, data, 'tpl.hbs'), fsOptions));
    jsConfig.push(require('./' + path.join(config.path.js, data, 'config.js')));
  });

  return {
    cssTpl: cssTpl,
    cssConfig: cssConfig,
    jsTpl: jsTpl,
    jsConfig: jsConfig
  }
})();

var cssData = compileHBS(data.cssTpl, data.cssConfig);
var jsData = compileHBS(data.jsTpl, data.jsConfig);

// write sublime snippets
compileSublime(cssData);
compileSublime(jsData);

// write webstorm Live Templates

compileWebstorm();

console.log('snippets is saved');

function compileWebstorm() {

  var result = [];
  var fileName = 'AmazeUI.xml';
  var dirPath = __dirname + config.dist.webstorm;

  var data = cssData.concat(jsData);

  _.each(data, function(value) {
    var triggerName = value.triggerName;

    var regLt = /</mg,
        regGt = />/mg,
        regQuo = /\"/mg,
        regTab = /\$([^\$]+)\$/img;

    var snippet = value.data;
    var arrNum = snippet.match(regTab);
    var tabVariable = [];

    snippet = snippet.replace(regLt, '<');
    snippet = snippet.replace(regGt, '>');
    snippet = snippet.replace(regQuo, '"');

    snippet = snippet.replace(regTab, function($0, $1) {
      var num = _.indexOf(arrNum, $0) + 1;
      var varName = 'var' + num;
      tabVariable.push('    <variable name="'+ varName +'" expression="'+ $1 +'" defaultValue="" alwaysStopAt="true" />');
      return $1 = '$' + varName + '$';
    });

    var liveTpl = [
      '  <template name="'+ triggerName +'" value="'+ snippet +'" toReformat="true" toShortenFQNames="true">\n',
      tabVariable.join(''),
      '    <context>',
      '      <option name="HTML_TEXT" value="true" />',
      '      <option name="HTML" value="true" />',
      '    </context>',
      '  </template>'
    ].join('\n');

    result.push(liveTpl);

  });

  var tpl = [
    '<?xml version="1.0" encoding="UTF-8"?>',
    '<templateSet group="AmazeUI">',
    result.join(''),
    '</templateSet>'
  ].join('\n');

  mkdirsSync(dirPath);

  fs.writeFile(dirPath + '/' + fileName, tpl, function(err) {
    if (err) throw err;
  });
}

/** *
 * @param data
 */
function compileSublime(data) {
  _.each(data, function(value) {
    var dirPath = __dirname + config.dist.sublime;
    var dirName = dirPath + '/' + value.name;
    var fileName = dirName + '/' + prefixName + value.name;
    var snippet = value.data;
    var result;
    var regTab = /\$([^\$]+)\$/img;
    var arr = snippet.match(regTab);

    if (value.fileName) {
      fileName += '-' + value.fileName + '.sublime-snippet';
    } else {
      fileName += '.sublime-snippet';
    }

    snippet = snippet.replace(regTab, function($0, $1) {
      var num = _.indexOf(arr, $0) + 1;
      return '${'+ num + ':' + $1 + '}';
    });

    result = [
      '<snippet>',
      '  <content>',
      '    <![CDATA[',
      snippet,
      '    ]]>',
      '  </content>',
      '  <tabTrigger>'+ value.triggerName +'</tabTrigger>',
      '</snippet>'
    ].join('\n');

    mkdirsSync(dirName);

    fs.writeFile(fileName, result, function(err) {
      if (err) throw err;
    });
  });
}

/**
 * @param dirname
 * @param mode
 * @returns {boolean}
 */
function mkdirsSync(dirname, mode){
  if(fs.existsSync(dirname)){
    return true;
  }else{
    if(mkdirsSync(path.dirname(dirname), mode)){
      fs.mkdirSync(dirname, mode);
      return true;
    }
  }
}

/**
 * 编译 handlebars
 * @param tpl
 * @param config
 */

function compileHBS(tpl, config) {
  var result = [];
  _.each(config, function(value, index) {
    var template = handlebars.compile(tpl[index]);

    _.each(value, function(data, key, list) {
      var triggerName;

      if (_.isArray(data)) {

        _.each(data, function(v) {
          triggerName = prefixName + list.name + ':' + v;
          result.push(
              {
                name: list.name,
                fileName: v,
                triggerName: triggerName,
                data: template({className: v})
              }
          )
        })

      } else {

        triggerName = prefixName + list.name;
        result.push(
            {
              name: list.name,
              fileName: '',
              triggerName: triggerName,
              data: template({})
            }
        )

      }
    });

  });

  return result;
}<commit_msg>fix webstorm snippet expression<commit_after>'use strict';

var handlebars = require('handlebars');
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var version = '2.1.0';

// Handlebars Helper
handlebars.registerHelper('ifCond', function(v1, operator, v2, options) {
  switch (operator) {
    case '==':
      return (v1 == v2) ? options.fn(this) : options.inverse(this);
      break;
    case '===':
      return (v1 === v2) ? options.fn(this) : options.inverse(this);
      break;
    case '<':
      return (v1 < v2) ? options.fn(this) : options.inverse(this);
      break;
    case '<=':
      return (v1 <= v2) ? options.fn(this) : options.inverse(this);
      break;
    case '>':
      return (v1 > v2) ? options.fn(this) : options.inverse(this);
      break;
    case '>=':
      return (v1 >= v2) ? options.fn(this) : options.inverse(this);
      break;
    default:
      return options.inverse(this);
      break;
  }
  return options.inverse(this);
});

var config = {
  path: {
    css: './src/css',
    js: './src/js'
  },
  dist: {
    sublime: '/dist/sublime',
    webstorm: '/dist/webstorm'
  }
};
var prefixName = 'am-';
var fsOptions = {encoding: 'utf8'};

var data = (function readData() {
  var cssFiles = fs.readdirSync(config.path.css);
  var jsFiles = fs.readdirSync(config.path.js);
  var cssTpl = [];
  var cssConfig = [];
  var jsTpl = [];
  var jsConfig = [];

  _.each(cssFiles, function(data) {
    cssTpl.push(fs.readFileSync(path.join(config.path.css, data, 'tpl.hbs'), fsOptions));
    cssConfig.push(require('./' + path.join(config.path.css, data, 'config.js')));
  });

  _.each(jsFiles, function(data) {
    jsTpl.push(fs.readFileSync(path.join(config.path.js, data, 'tpl.hbs'), fsOptions));
    jsConfig.push(require('./' + path.join(config.path.js, data, 'config.js')));
  });

  return {
    cssTpl: cssTpl,
    cssConfig: cssConfig,
    jsTpl: jsTpl,
    jsConfig: jsConfig
  }
})();

var cssData = compileHBS(data.cssTpl, data.cssConfig);
var jsData = compileHBS(data.jsTpl, data.jsConfig);

// write sublime snippets
compileSublime(cssData);
compileSublime(jsData);

// write webstorm Live Templates

compileWebstorm();

console.log('snippets is saved');

function compileWebstorm() {

  var result = [];
  var fileName = 'AmazeUI.xml';
  var dirPath = __dirname + config.dist.webstorm;

  var data = cssData.concat(jsData);

  _.each(data, function(value) {
    var triggerName = value.triggerName;

    var regLt = /</mg,
        regGt = />/mg,
        regQuo = /\"/mg,
        regTab = /\$([^\$]+)\$/img;

    var snippet = value.data;
    var arrNum = snippet.match(regTab);
    var tabVariable = [];

    snippet = snippet.replace(regLt, '<');
    snippet = snippet.replace(regGt, '>');
    snippet = snippet.replace(regQuo, '"');

    snippet = snippet.replace(regTab, function($0, $1) {
      var num = _.indexOf(arrNum, $0) + 1;
      var varName = 'var' + num;
      tabVariable.push('    <variable name="'+ varName +'" expression=""'+ $1 +'"" defaultValue="" alwaysStopAt="true" />');
      return $1 = '$' + varName + '$';
    });

    var liveTpl = [
      '  <template name="'+ triggerName +'" value="'+ snippet +'" toReformat="true" toShortenFQNames="true">\n',
      tabVariable.join(''),
      '    <context>',
      '      <option name="HTML_TEXT" value="true" />',
      '      <option name="HTML" value="true" />',
      '    </context>',
      '  </template>'
    ].join('\n');

    result.push(liveTpl);

  });

  var tpl = [
    '<?xml version="1.0" encoding="UTF-8"?>',
    '<templateSet group="AmazeUI">',
    result.join(''),
    '</templateSet>'
  ].join('\n');

  mkdirsSync(dirPath);

  fs.writeFile(dirPath + '/' + fileName, tpl, function(err) {
    if (err) throw err;
  });
}

/** *
 * @param data
 */
function compileSublime(data) {
  _.each(data, function(value) {
    var dirPath = __dirname + config.dist.sublime;
    var dirName = dirPath + '/' + value.name;
    var fileName = dirName + '/' + prefixName + value.name;
    var snippet = value.data;
    var result;
    var regTab = /\$([^\$]+)\$/img;
    var arr = snippet.match(regTab);

    if (value.fileName) {
      fileName += '-' + value.fileName + '.sublime-snippet';
    } else {
      fileName += '.sublime-snippet';
    }

    snippet = snippet.replace(regTab, function($0, $1) {
      var num = _.indexOf(arr, $0) + 1;
      return '${'+ num + ':' + $1 + '}';
    });

    result = [
      '<snippet>',
      '  <content>',
      '    <![CDATA[',
      snippet,
      '    ]]>',
      '  </content>',
      '  <tabTrigger>'+ value.triggerName +'</tabTrigger>',
      '</snippet>'
    ].join('\n');

    mkdirsSync(dirName);

    fs.writeFile(fileName, result, function(err) {
      if (err) throw err;
    });
  });
}

/**
 * @param dirname
 * @param mode
 * @returns {boolean}
 */
function mkdirsSync(dirname, mode){
  if(fs.existsSync(dirname)){
    return true;
  }else{
    if(mkdirsSync(path.dirname(dirname), mode)){
      fs.mkdirSync(dirname, mode);
      return true;
    }
  }
}

/**
 * 编译 handlebars
 * @param tpl
 * @param config
 */

function compileHBS(tpl, config) {
  var result = [];
  _.each(config, function(value, index) {
    var template = handlebars.compile(tpl[index]);

    _.each(value, function(data, key, list) {
      var triggerName;

      if (_.isArray(data)) {

        _.each(data, function(v) {
          triggerName = prefixName + list.name + ':' + v;
          result.push(
              {
                name: list.name,
                fileName: v,
                triggerName: triggerName,
                data: template({className: v})
              }
          )
        })

      } else {

        triggerName = prefixName + list.name;
        result.push(
            {
              name: list.name,
              fileName: '',
              triggerName: triggerName,
              data: template({})
            }
        )

      }
    });

  });

  return result;
}<|endoftext|>


<commit_before>     var SpaceTime_FunctionsDIR = './SpaceTime_Functions/';
     var SpaceTime_coreFile = 'map.js';
     console.log('{src f}   src -f-> ??');
     console.log('');
     console.log('SpaceTime modlue loading...');
      //var M = require(SpaceTime_FunctionsDIR + SpaceTime_coreFile);
      //require(STRING) must be raw STRING to be read by Browserify
     var M = require('./SpaceTime_Functions/map.js');
     module.exports = M;
     console.log('Function: map(core)');

     var loadModulesFactory;
     if (typeof window === 'undefined')
     {
       var modulePathHiddenFromBrowserify = './loadModulesFactory';
       loadModulesFactory = require(modulePathHiddenFromBrowserify);
     }
     else
     {
       loadModulesFactory = require('./loadModulesFactoryBrowserify');
     }

     var obj = loadModulesFactory(SpaceTime_FunctionsDIR, SpaceTime_coreFile, M);
     M = obj.M;
     var loadModules = M.loadModules = obj.func;

      //=====================================
     String.prototype.replaceAll = function(org, dest)
     {
       return this
         .split(org)
         .join(dest);
     };

     var sqSymbol = '_____sq_____';
     var sqKey = 'sq___';

      //==========================
     var cmtprts = ['//', '/*', '*/', '(', ')', '\n', ' ', '　'];
     var cmtprtsE = cmtprts.map(function(s, i)
     {
       return '______mark______' + i;
     });
      //==========================

     var restoreMark = function(src)
     {
       // "thisisareplacement"+i  restore to normal string
       var src1 = [];

       cmtprtsE.map(function(mark, mark_i)
       {
         var data;
         if (mark_i === 0)
         {
           data = src;
         }
         else
         {
           data = src1[mark_i - 1];
         }
         src1[mark_i] = data.replaceAll(mark, cmtprts[mark_i]);

       });
       return src1[src1.length - 1];
     };

     var trim = function(src)
     {

       var strgs = src.match(/"(?:[^\\"]|\\.)*"/ig);
       var strgs1 = [];
       var src1 = [];

       var src2;
       // escape cmtprts  during each Strings
       if (strgs)
       {
         strgs.map(function(str, str_i)
         {
           var str1 = [];
           cmtprts.map(function(mark, mark_i)
           {
             var data;
             if (mark_i === 0)
             {
               data = str;
             }
             else
             {
               data = str1[mark_i - 1];
             }

             str1[mark_i] = data.replaceAll(mark, cmtprtsE[mark_i]);
           });

           strgs1[str_i] = str1[str1.length - 1];

           var data1;

           if (str_i === 0)
           {
             data1 = src;
           }
           else
           {
             data1 = src1[str_i - 1];
           }

           src1[str_i] = data1.replaceAll(strgs[str_i], strgs1[str_i]);

         });

         src2 = src1[src1.length - 1];
       }
       else
       {
         src2 = src;
       }

       // comment out removing
       var re2 = new RegExp('//.*?(?=[\\n\\r]+|$)|/[*](.|\n)*?[*]/', 'g');
       var src3 = src2
         .replace(re2, '');

       //beautifly
       var src4 = src3.replaceAll('　', ' '); //zenkaku>hankaku

       var src5 = src4.replaceAll('\n', ' '); //linebreak -> single space

       var src6 = src5.replace(/(\S)\(/g, '$1 ('); //foo(  -> foo (
       var src7 = src6.replace(/\)(\S)/g, ') $1'); //)foo  -> ) foo

       var src8 = src7.replace(/[　\s]+/g, ' '); // trim extra spaces
       var src9 = src8.replace(/(\()\s+|\s+(\))/g, '$1$2'); //trim a space after '(' and before ')'.
       var src10 = src9.replace(/(\[)\s+|\s+(\])/g, '$1$2'); //trim a space after '[' and before ']'.

       return src10;

     };

     var arrays = function(src)
     {
       M.$W('------------- parse ----------------');
       M.$W(src);

       var f1 = function(src)
       {
         //   M.$W('some seq');
         //    M.$W(src);

         var indexHead;
         var indexTail;
         var count = [];
         var previousCount;

         var space = [];
         for (var i = 0; i < src.length; i++)
         {
           // wt('> ' + src[i]);
           if (i === 0)
             previousCount = 0;
           else
             previousCount = count[i - 1];

           if ((previousCount === 1) && (src[i] === ' '))
             space[space.length] = i;

           if (src[i] === '(')
             count[i] = previousCount + 1;
           else if (src[i] === ')')
             count[i] = previousCount - 1;
           else
             count[i] = previousCount;

           if ((previousCount === 0) && (count[i] === 1))
           {
             indexHead = i;
           }

           if ((previousCount === 1) && (count[i] === 0))
           {
             indexTail = i;
           }

           //   wt('count ' + count[i]);

         }

         //   M.$W(indexHead);
         //   M.$W(indexTail);
         //  M.$W(space);

         var src1 = src.substring(indexHead + 1, indexTail);

         var array = [];

         if (space.length === 0)
         {
           array[0] = arrays(src1);
           // M.$W('---return');
           //  M.$W(array);
           return array;
         }
         else
         {
           for (var j = 0; j < space.length; j++)
           {
             if (j === 0)
             {
               array[array.length] = arrays(src.substring(indexHead + 1, space[j]));
             }
             if (j === space.length - 1)
             {
               array[array.length] = arrays(src.substring(space[j] + 1, indexTail));
             }
             else
             {
               array[array.length] = arrays(src.substring(space[j] + 1, space[j + 1]));
             }
           }
           //  M.$W('---return');
           //   M.$W(array);

           return array;
         }
       };

       //------------------
       if (src === '')
         return src;
       else if (!src)
         return src;
       else if (src.indexOf('(') === -1)
       {
         return src;
       }
       else
       {

         var count = 0;
         var otherCharactor = false;
         for (var i = 0; i < src.length; i++)
         {
           if (src[i] === '(')
           {
             count++;
           }
           else if (src[i] === ')')
           {
             count--;
           }
           else if (src[i] === ' ')
           {

           }
           else
           {
             otherCharactor = true;
           }
         }

         if (count !== 0)
         {
           return 'error';
         }
         else if (otherCharactor)
         {
           return f1(src);
         }
         else
         {
           return [];
         }

       }
     };

     var maybeNumberString = function(src)
     {
       console.log('maybeNumberString');
       console.log(src);

       var s1 = src * 1;
       var s2 = '' + s1;
       if (src === s2) // naked number
       {
         return s1;
       }
       else if (src.indexOf('"') !== -1) // '"some string"'
       {
         return restoreMark(src.substring(1, src.length - 1));
       }
       else
       {
         var src1;

         if (src === '+')
           src1 = 'plus';
         else if (src === '-')
           src1 = 'minus';
         else if (src === 'if')
           src1 = 'ifF';
         else if (src === '==')
           src1 = 'boolEqual';
         else if (src === '>')
           src1 = 'boolGreater';
         else if (src === '<')
           src1 = 'boolLess';
         else if (src === '>=')
           src1 = 'boolGreaterEqual';
         else if (src === '<=')
           src1 = 'boolLessEqual';
         else
           src1 = src;

         console.log(src1);
         return M[src1];
       }

     };

     var walk = function(src)
     {
       //  console.log('=======');
       // console.log(src);

       if (M.$type(src) !== 'Array')
       {
         return maybeNumberString(src);
       }
       else
       {
         var array = [];
         for (var i = 0; i < src.length; i++)
         {
           //  console.log('-------');
           //  console.log(src[i]);
           array[i] = walk(src[i]);
         }

         return array;
       }
     };

     var $parse = M.$parse = function(src)
     {
       return walk(arrays(trim(src)));
     };
      //======================================

     var $construct = M.$construct = function(result)
     {
       var result1;
       if (M.$type(result) === 'Array')
       {
         result1 = '( ';
         for (var i = 0; i < result.length; i++)
         {
           result1 += $construct(result[i]);
           result1 += ' ';
         }

         result1 += ')';
       }
       else if (M.$type(result) === 'String')
       {
         result1 = '"' + result + '"';
       }
       else if (M.$type(result) === 'Function')
       {
         result1 = 'Function';
       }
       else
       {
         result1 = result;
       }

       return result1;
     };

     if (typeof describe === 'undefined')
     {
       loadModules(function()
       {
         M.$W('------------- SpaceTime Module is Ready ----------------');

         //============================================
         // var src = [1, [M.plus, [2]], [M.map, [M.CONSOLE]]];
         //var src = '    ( ((  ) )  8 ) ';
         // var src = '';
         // var src = '(("hello   world"))';
         // var src = '  ( 2 (+(9)) )    ';
         //  var src = ' (FIB (take(10)) (map(CONSOLE))) ';
         //var src = ' (SEQ  (iterate ())  (take(10)) (map(CONSOLE))) ';

         // var src = ' (NATURAL  (take(10)) (map(CONSOLE))) ';

         /*  (
             FUNCTION_COMPOSITION VAL0(get(i(-(2))))(+(VAL0(get(i(-(1))))))
             (ifF((i <= 1)(1))))

         )*/
         //  var src = '( (1 2 3 4 5)      (take(4))   (take(2)))';
         // var src = '( () (iterate ( I ) ) (take(10)) )';
         //  var src = '(5 (ifF  ((10 (bool (>= (11) )))  9)   )  )';

         // var src = '( () (iterate (I (if ((I (bool (<= (4) )))  (1))   )  ) ) (take(10)) )';

         var src = '(3 (== (3)))';
         //var src = '(10 (bool (>= (10) )))';

         M.debug = false;
         var src1 = $parse(src);

         /*  src1 = [
          5,
          [M.ifF, [[false], [1]]]
        ];*/

         //  src1 = [10, [M.bool, [M.GREATEREQUAL, [10]]]];
         console.log(src1);
         var result = M.map(src1, [M.EVAL]);
         M.$W(' === result === ');
         M.$W(result);
         M.$W($construct(result));

         //------------------------------------------------------------------
       });
     }

      //=========================================<commit_msg>commit<commit_after>     var SpaceTime_FunctionsDIR = './SpaceTime_Functions/';
     var SpaceTime_coreFile = 'map.js';
     console.log('{src f}   src -f-> ??');
     console.log('');
     console.log('SpaceTime modlue loading...');
      //var M = require(SpaceTime_FunctionsDIR + SpaceTime_coreFile);
      //require(STRING) must be raw STRING to be read by Browserify
     var M = require('./SpaceTime_Functions/map.js');
     module.exports = M;
     console.log('Function: map(core)');

     var loadModulesFactory;
     if (typeof window === 'undefined')
     {
       var modulePathHiddenFromBrowserify = './loadModulesFactory';
       loadModulesFactory = require(modulePathHiddenFromBrowserify);
     }
     else
     {
       loadModulesFactory = require('./loadModulesFactoryBrowserify');
     }

     var obj = loadModulesFactory(SpaceTime_FunctionsDIR, SpaceTime_coreFile, M);
     M = obj.M;
     var loadModules = M.loadModules = obj.func;

      //=====================================
     String.prototype.replaceAll = function(org, dest)
     {
       return this
         .split(org)
         .join(dest);
     };

     var sqSymbol = '_____sq_____';
     var sqKey = 'sq___';

      //==========================
     var cmtprts = ['//', '/*', '*/', '(', ')', '\n', ' ', '　'];
     var cmtprtsE = cmtprts.map(function(s, i)
     {
       return '______mark______' + i;
     });
      //==========================

     var restoreMark = function(src)
     {
       // "thisisareplacement"+i  restore to normal string
       var src1 = [];

       cmtprtsE.map(function(mark, mark_i)
       {
         var data;
         if (mark_i === 0)
         {
           data = src;
         }
         else
         {
           data = src1[mark_i - 1];
         }
         src1[mark_i] = data.replaceAll(mark, cmtprts[mark_i]);

       });
       return src1[src1.length - 1];
     };

     var trim = function(src)
     {

       var strgs = src.match(/"(?:[^\\"]|\\.)*"/ig);
       var strgs1 = [];
       var src1 = [];

       var src2;
       // escape cmtprts  during each Strings
       if (strgs)
       {
         strgs.map(function(str, str_i)
         {
           var str1 = [];
           cmtprts.map(function(mark, mark_i)
           {
             var data;
             if (mark_i === 0)
             {
               data = str;
             }
             else
             {
               data = str1[mark_i - 1];
             }

             str1[mark_i] = data.replaceAll(mark, cmtprtsE[mark_i]);
           });

           strgs1[str_i] = str1[str1.length - 1];

           var data1;

           if (str_i === 0)
           {
             data1 = src;
           }
           else
           {
             data1 = src1[str_i - 1];
           }

           src1[str_i] = data1.replaceAll(strgs[str_i], strgs1[str_i]);

         });

         src2 = src1[src1.length - 1];
       }
       else
       {
         src2 = src;
       }

       // comment out removing
       var re2 = new RegExp('//.*?(?=[\\n\\r]+|$)|/[*](.|\n)*?[*]/', 'g');
       var src3 = src2
         .replace(re2, '');

       //beautifly
       var src4 = src3.replaceAll('　', ' '); //zenkaku>hankaku

       var src5 = src4.replaceAll('\n', ' '); //linebreak -> single space

       var src6 = src5.replace(/(\S)\(/g, '$1 ('); //foo(  -> foo (
       var src7 = src6.replace(/\)(\S)/g, ') $1'); //)foo  -> ) foo

       var src8 = src7.replace(/[　\s]+/g, ' '); // trim extra spaces
       var src9 = src8.replace(/(\()\s+|\s+(\))/g, '$1$2'); //trim a space after '(' and before ')'.
       var src10 = src9.replace(/(\[)\s+|\s+(\])/g, '$1$2'); //trim a space after '[' and before ']'.

       return src10;

     };

     var arrays = function(src)
     {
       M.$W('------------- parse ----------------');
       M.$W(src);

       var f1 = function(src)
       {
         //   M.$W('some seq');
         //    M.$W(src);

         var indexHead;
         var indexTail;
         var count = [];
         var previousCount;

         var space = [];
         for (var i = 0; i < src.length; i++)
         {
           // wt('> ' + src[i]);
           if (i === 0)
             previousCount = 0;
           else
             previousCount = count[i - 1];

           if ((previousCount === 1) && (src[i] === ' '))
             space[space.length] = i;

           if (src[i] === '(')
             count[i] = previousCount + 1;
           else if (src[i] === ')')
             count[i] = previousCount - 1;
           else
             count[i] = previousCount;

           if ((previousCount === 0) && (count[i] === 1))
           {
             indexHead = i;
           }

           if ((previousCount === 1) && (count[i] === 0))
           {
             indexTail = i;
           }

           //   wt('count ' + count[i]);

         }

         //   M.$W(indexHead);
         //   M.$W(indexTail);
         //  M.$W(space);

         var src1 = src.substring(indexHead + 1, indexTail);

         var array = [];

         if (space.length === 0)
         {
           array[0] = arrays(src1);
           // M.$W('---return');
           //  M.$W(array);
           return array;
         }
         else
         {
           for (var j = 0; j < space.length; j++)
           {
             if (j === 0)
             {
               array[array.length] = arrays(src.substring(indexHead + 1, space[j]));
             }
             if (j === space.length - 1)
             {
               array[array.length] = arrays(src.substring(space[j] + 1, indexTail));
             }
             else
             {
               array[array.length] = arrays(src.substring(space[j] + 1, space[j + 1]));
             }
           }
           //  M.$W('---return');
           //   M.$W(array);

           return array;
         }
       };

       //------------------
       if (src === '')
         return src;
       else if (!src)
         return src;
       else if (src.indexOf('(') === -1)
       {
         return src;
       }
       else
       {

         var count = 0;
         var otherCharactor = false;
         for (var i = 0; i < src.length; i++)
         {
           if (src[i] === '(')
           {
             count++;
           }
           else if (src[i] === ')')
           {
             count--;
           }
           else if (src[i] === ' ')
           {

           }
           else
           {
             otherCharactor = true;
           }
         }

         if (count !== 0)
         {
           return 'error';
         }
         else if (otherCharactor)
         {
           return f1(src);
         }
         else
         {
           return [];
         }

       }
     };

     var maybeNumberString = function(src)
     {
       console.log('maybeNumberString');
       console.log(src);

       var s1 = src * 1;
       var s2 = '' + s1;
       if (src === s2) // naked number
       {
         return s1;
       }
       else if (src.indexOf('"') !== -1) // '"some string"'
       {
         return restoreMark(src.substring(1, src.length - 1));
       }
       else
       {
         var src1;

         if (src === '+')
           src1 = 'plus';
         else if (src === '-')
           src1 = 'minus';
         else if (src === 'if')
           src1 = 'ifF';
         else if (src === '==')
           src1 = 'boolEqual';
         else if (src === '>')
           src1 = 'boolGreater';
         else if (src === '<')
           src1 = 'boolLess';
         else if (src === '>=')
           src1 = 'boolGreaterEqual';
         else if (src === '<=')
           src1 = 'boolLessEqual';
         else
           src1 = src;

         console.log(src1);
         return M[src1];
       }

     };

     var walk = function(src)
     {
       //  console.log('=======');
       // console.log(src);

       if (M.$type(src) !== 'Array')
       {
         return maybeNumberString(src);
       }
       else
       {
         var array = [];
         for (var i = 0; i < src.length; i++)
         {
           //  console.log('-------');
           //  console.log(src[i]);
           array[i] = walk(src[i]);
         }

         return array;
       }
     };

     var $parse = M.$parse = function(src)
     {
       return walk(arrays(trim(src)));
     };
      //======================================

     var $construct = M.$construct = function(result)
     {
       var result1;
       if (M.$type(result) === 'Array')
       {
         result1 = '( ';
         for (var i = 0; i < result.length; i++)
         {
           result1 += $construct(result[i]);
           result1 += ' ';
         }

         result1 += ')';
       }
       else if (M.$type(result) === 'String')
       {
         result1 = '"' + result + '"';
       }
       else if (M.$type(result) === 'Function')
       {
         result1 = 'Function';
       }
       else
       {
         result1 = result;
       }

       return result1;
     };

     if (typeof describe === 'undefined')
     {
       loadModules(function()
       {
         M.$W('------------- SpaceTime Module is Ready ----------------');

         //============================================
         // var src = [1, [M.plus, [2]], [M.map, [M.CONSOLE]]];
         //var src = '    ( ((  ) )  8 ) ';
         // var src = '';
         // var src = '(("hello   world"))';
         // var src = '  ( 2 (+(9)) )    ';
         //  var src = ' (FIB (take(10)) (map(CONSOLE))) ';
         //var src = ' (SEQ  (iterate ())  (take(10)) (map(CONSOLE))) ';

         // var src = ' (NATURAL  (take(10)) (map(CONSOLE))) ';

         /*  (
             FUNCTION_COMPOSITION VAL0(get(i(-(2))))(+(VAL0(get(i(-(1))))))
             (ifF((i <= 1)(1))))

         )*/
         //  var src = '( (1 2 3 4 5)      (take(4))   (take(2)))';
         // var src = '( () (iterate ( I ) ) (take(10)) )';
         //  var src = '(5 (ifF  ((10 (bool (>= (11) )))  9)   )  )';

         var src = '( () (iterate (I (if ((I (<= (4) ))  (1))   )  ) ) (take(10)) )';

         //var src = '(3 (== (3)))';
         //var src = '(10 (bool (>= (10) )))';

         M.debug = false;
         var src1 = $parse(src);

         /*  src1 = [
          5,
          [M.ifF, [[false], [1]]]
        ];*/

         //  src1 = [10, [M.bool, [M.GREATEREQUAL, [10]]]];
         console.log(src1);
         var result = M.map(src1, [M.EVAL]);
         M.$W(' === result === ');
         M.$W(result);
         M.$W($construct(result));

         //------------------------------------------------------------------
       });
     }

      //=========================================<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes');

var app = module.exports = express.createServer();
var io = require('socket.io').listen(app);
var lobbyClass = require('./lib/lobby.js');

// var rooms = {};

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);

app.get('/:id', function(req, res) {
  if (req.params.id in lobby.rooms) {
    res.render('room', { title: 'Room ' + req.params.id, script: 'room' });
  }
  res.send(404);
});

// Heroku won't actually allow us to use WebSockets
// so we have to setup polling instead.
// https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku
io.configure('production', function(){
  io.enable('browser client etag');
  io.set('log level', 1);
  io.set('transports', [
      "websocket"
    ]);
});
io.configure('development', function(){
  io.enable('browser client etag');
  io.set('log level', 2);
  io.set('transports', [
      "websocket"
    ]);
});

var port = process.env.PORT || 5000; // Use the port that Heroku provides or default to 5000
app.listen(port, function() {
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});

var lobby = new lobbyClass.Lobby(io);

/* EVENT LISTENERS */

io.sockets.on('connection', function (socket) {

  console.log("Connect");

  socket.on('disconnect', function () {
    console.log("Disconnect");
    lobby.broadcastDisconnect(socket);
  });

  socket.on('create room', function (data, callback) {
    console.log("create room");
    callback(lobby.createRoom());
  });

  socket.on('join room', function (roomUrl, callback) {
    console.log("join room");
    var response = lobby.joinRoom(socket, roomUrl);
    if(response.error) {
      callback( 'room does not exist' );
    } else {
      callback(lobby.refreshRoomInfo(roomUrl));
    }
  });

  socket.on('room info', function (roomUrl, callback) {
    console.log("room info");
    callback(lobby.refreshRoomInfo(roomUrl));
  });

});<commit_msg>no need for hardcoded error msg<commit_after>
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes');

var app = module.exports = express.createServer();
var io = require('socket.io').listen(app);
var lobbyClass = require('./lib/lobby.js');

// var rooms = {};

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);

app.get('/:id', function(req, res) {
  if (req.params.id in lobby.rooms) {
    res.render('room', { title: 'Room ' + req.params.id, script: 'room' });
  }
  res.send(404);
});

// Heroku won't actually allow us to use WebSockets
// so we have to setup polling instead.
// https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku
io.configure('production', function(){
  io.enable('browser client etag');
  io.set('log level', 1);
  io.set('transports', [
      "websocket"
    ]);
});
io.configure('development', function(){
  io.enable('browser client etag');
  io.set('log level', 2);
  io.set('transports', [
      "websocket"
    ]);
});

var port = process.env.PORT || 5000; // Use the port that Heroku provides or default to 5000
app.listen(port, function() {
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});

var lobby = new lobbyClass.Lobby(io);

/* EVENT LISTENERS */

io.sockets.on('connection', function (socket) {

  console.log("Connect");

  socket.on('disconnect', function () {
    console.log("Disconnect");
    lobby.broadcastDisconnect(socket);
  });

  socket.on('create room', function (data, callback) {
    console.log("create room");
    callback(lobby.createRoom());
  });

  socket.on('join room', function (roomUrl, callback) {
    console.log("join room");
    var response = lobby.joinRoom(socket, roomUrl);
    if(response.error) {
      callback( response.error );
    } else {
      callback(lobby.refreshRoomInfo(roomUrl));
    }
  });

  socket.on('room info', function (roomUrl, callback) {
    console.log("room info");
    callback(lobby.refreshRoomInfo(roomUrl));
  });

});<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'kies');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('kies mohamed abdelkader');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<commit_msg>view1<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'abdelkader'));
app.set('view engine', 'kies');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('kies mohamed abdelkader');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2015 Tanay PrabhuDesai

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

var express = require('express');
var bodyParser = require('body-parser');
var https = require('https');
var querystring = require('querystring');

var env = (function(){
      var Habitat = require("habitat");
      Habitat.load();
      return new Habitat();
    }());

var app = express();

var port = Number(process.env.PORT || 5000);

app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
  extended: true
}));

app.set('views',__dirname+'/views/');
app.set('view engine','jade');
app.engine('jade', require('jade').__express);

// Use all the public files
app.use(express.static(__dirname + '/public/js'));
app.use(express.static(__dirname + '/public/css'));
app.use(express.static(__dirname + '/public/css/font/'));
app.use(express.static(__dirname + '/public/res'));

function postCaptcha(response,ip,res_in,captchaVerified) {
	var post_data = querystring.stringify({
      'secret' : process.env.SECRET_KEY || env.get("SECRET_KEY"),
      'response': response,
      'remoteip': ip
  });
  console.log('Response:'+response);
  console.log('Ip:'+ip);
  var post_options = {
      host: 'www.google.com',
      port: '443',
      path: '/recaptcha/api/siteverify',
      method: 'POST',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': post_data.length
      }
  };
  var post_req = https.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
          captchaVerified(chunk,res_in);
      });
  });
  console.log('Post completed');
  post_req.write(post_data);
  post_req.end();
}

app.get('/', function (req, res) {
  res.render('login.jade',{msg:''});
});

function captchaVerified(chunk, res) {
	var txt = 'Please complete the captcha challenge';
	var obj = JSON.parse(chunk);
	console.log(typeof(obj)+' '+obj+' '+obj.success);
	if (obj["success"]) {
		res.render('game.jade');
	} else {
		res.render('login.jade',{msg:txt});
	}
}

app.post('/play',function(req, res){
	if (req.body['username'] == '') {
		var txt = 'Username cannot be left empty';
  	res.render('login.jade',{msg:txt});
	} else {
		postCaptcha(req.body['g-recaptcha-response'],req.ip,res,captchaVerified)
	}
});

var server = app.listen(port, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Pitchy Bird started at http://%s:%s', host, port);
});<commit_msg>Changed the line for captcha error<commit_after>// The MIT License (MIT)

// Copyright (c) 2015 Tanay PrabhuDesai

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

var express = require('express');
var bodyParser = require('body-parser');
var https = require('https');
var querystring = require('querystring');

var env = (function(){
      var Habitat = require("habitat");
      Habitat.load();
      return new Habitat();
    }());

var app = express();

var port = Number(process.env.PORT || 5000);

app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
  extended: true
}));

app.set('views',__dirname+'/views/');
app.set('view engine','jade');
app.engine('jade', require('jade').__express);

// Use all the public files
app.use(express.static(__dirname + '/public/js'));
app.use(express.static(__dirname + '/public/css'));
app.use(express.static(__dirname + '/public/css/font/'));
app.use(express.static(__dirname + '/public/res'));

function postCaptcha(response,ip,res_in,captchaVerified) {
	var post_data = querystring.stringify({
      'secret' : process.env.SECRET_KEY || env.get("SECRET_KEY"),
      'response': response,
      'remoteip': ip
  });
  console.log('Response:'+response);
  console.log('Ip:'+ip);
  var post_options = {
      host: 'www.google.com',
      port: '443',
      path: '/recaptcha/api/siteverify',
      method: 'POST',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': post_data.length
      }
  };
  var post_req = https.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
          captchaVerified(chunk,res_in);
      });
  });
  console.log('Post completed');
  post_req.write(post_data);
  post_req.end();
}

app.get('/', function (req, res) {
  res.render('login.jade',{msg:''});
});

function captchaVerified(chunk, res) {
	var txt = 'Please prove that you are not a robot';
	var obj = JSON.parse(chunk);
	console.log(typeof(obj)+' '+obj+' '+obj.success);
	if (obj["success"]) {
		res.render('game.jade');
	} else {
		res.render('login.jade',{msg:txt});
	}
}

app.post('/play',function(req, res){
	if (req.body['username'] == '') {
		var txt = 'Username cannot be left empty';
  	res.render('login.jade',{msg:txt});
	} else {
		postCaptcha(req.body['g-recaptcha-response'],req.ip,res,captchaVerified)
	}
});

var server = app.listen(port, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Pitchy Bird started at http://%s:%s', host, port);
});<|endoftext|>