<commit_before>/*
 * include-folder
 * https://github.com/parroit/include-folder
 *
 * Copyright (c) 2013 parroit
 * Licensed under the MIT license.
 */

'use strict';

var _ = require("lodash"),
    fs = require("fs");

function includeFolder(folderName) {
    if (folderName.charAt(folderName.length - 1) === "/") {
        folderName = folderName.substring(0,folderName.length-1);
    }
    var source = includeFolder._testHook.buildSource(folderName);

    return (new Function("require", "__dirname", source))(require, folderName);

}

function normalize(name) {
    var chars = [];
    var nextUpper = false;
    var i = 0,
        l = name.length;

    for (; i < l; i++) {
        var c = name.charAt(i);
        if (/\w/.test(c)) {
            chars.push(nextUpper ? c.toUpperCase() : c);
            nextUpper = false;
        } else {
            nextUpper = true;
        }
    }
    name = chars.join("");
    return name;
}

function stripExtension(fileName) {
    return fileName.replace(/\.[^/.]+$/, "");
}

function buildSource(folderName) {
    var files = fs.readdirSync(folderName);
    var allProps = {};
    var fields = _.map(files, function (fileName) {
        var name = normalize(stripExtension(fileName));

        if (name in allProps) {
            allProps[name]++;
            name += "_" + allProps[name];
        } else {
            allProps[name] = 0;
        }

        return 'self.' + name + ' = fs.readFileSync(__dirname + "/' + fileName + '","utf8");';
    });

    return "var self={}," +
        "fs = require('fs');\n" +
        fields.join("\n") +
        "\nreturn self";
}

includeFolder._testHook = {
    buildSource: buildSource
};

module.exports = includeFolder;
<commit_msg>completed<commit_after>/*
 * include-folder
 * https://github.com/parroit/include-folder
 *
 * Copyright (c) 2013 parroit
 * Licensed under the MIT license.
 */

'use strict';

var _ = require("lodash"),
    fs = require("fs");

function includeFolder(folderName) {
    if (folderName.charAt(folderName.length - 1) === "/") {
        folderName = folderName.substring(0,folderName.length-1);
    }
    var source = includeFolder._testHook.buildSource(folderName);

    return (new Function("require", "__dirname", source))(require, folderName);

}

function normalize(name) {
    var chars = [];
    var nextUpper = false;
    var i = 0,
        l = name.length;

    for (; i < l; i++) {
        var c = name.charAt(i);
        if (/\w/.test(c)) {
            chars.push(nextUpper ? c.toUpperCase() : c);
            nextUpper = false;
        } else {
            nextUpper = true;
        }
    }
    name = chars.join("");
    return name;
}

function stripExtension(fileName) {
    return fileName.replace(/\.[^/.]+$/, "");
}

function buildSource(folderName) {
    var files = fs.readdirSync(folderName);
    var allProps = {};
    var fields = _.map(files, function (fileName) {
        var name = normalize(stripExtension(fileName));

        if (name in allProps) {
            allProps[name]++;
            name += "_" + allProps[name];
        } else {
            allProps[name] = 0;
        }

        return 'self.' + name + ' = fs.readFileSync(__dirname + "/' + fileName + '","utf8");';
    });

    return "var self={}," +
        "fs = require('fs');\n" +
        fields.join("\n") +
        "\nreturn self";
}

includeFolder._testHook = {
    buildSource: buildSource
};

module.exports = includeFolder;
<|endoftext|>


<commit_before>//> This file is part of Ymacs, an Emacs-like editor for the Web
//> http://www.ymacs.org/
//>
//> Copyright (c) 2009-2012, Mihai Bazon, Dynarch.com.  All rights reserved.
//>
//> Redistribution and use in source and binary forms, with or without
//> modification, are permitted provided that the following conditions are
//> met:
//>
//>     * Redistributions of source code must retain the above copyright
//>       notice, this list of conditions and the following disclaimer.
//>
//>     * Redistributions in binary form must reproduce the above copyright
//>       notice, this list of conditions and the following disclaimer in
//>       the documentation and/or other materials provided with the
//>       distribution.
//>
//>     * Neither the name of Dynarch.com nor the names of its contributors
//>       may be used to endorse or promote products derived from this
//>       software without specific prior written permission.
//>
//> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
//> EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//> PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
//> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//> CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//> SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//> INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
//> CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//> ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
//> THE POSSIBILITY OF SUCH DAMAGE.

// @require ymacs-keymap.js

// This is the default keymap, as configured in
// Ymacs_Buffer::makeDefaultKeymap.  It follows closely the standard
// Emacs keybindings, with some small deviations that match my taste
// (search for "my stuff" below).

// It would be nice to have more options, such as an Eclipse keymap,
// or Visual Studio -- but I'm not familiar with any of them.
// Contributions welcome.

// A keymap inherits from Ymacs_Keymap and should define its bindings
// in D.KEYS.  They can also define a defaultHandler property to take
// whatever action they consider necessary -- for example the Isearch
// keymap will, by default, print the entered character in the
// minibuffer and trigger a search action.  Isearch mode is almost
// completely defined in a keymap -- with the minor note that
// isearch_forward and isearch_backward are assigned below to key
// combinations; once pressed, they will push the Isearch keymap onto
// the buffer's keymap stack, and it will be used until isearch is
// ended.

/* KEY DEFINITIONS.  A key is generally defined in standard Emacs
   notation, with the following notes:

   - it is possible to define multiple keys at once for the same
   operation, by using the "&&" combination (separate with spaces
   from the actual keys)

   - some special characters are named literally; their names contain
   more than one character.  The available names are defined in
   DlKeyboard (see keyboard.js in DynarchLIB).  Examples:
   ARROW_RIGHT, PAGE_UP, etc. but also SPACE and DASH.

   Normally you would define commands using Ymacs_Buffer.newCommands
   (see ymacs-commands.js) and specify the command name for key
   bindings, but you can specify a function as well, if you want:

   "C-8": function() {
   alert("You pressed CTRL-8");
   }

   It is advised to define commands for more than simple cases, for
   two reasons:

   1. they can be used for "non-interactive" calls too

   2. the command name is saved in this.currentCommand /
   this.previousCommand, which is useful in a number of cases.

*/

DEFINE_SINGLETON("Ymacs_Keymap_Emacs", Ymacs_Keymap, function(D, P){

    var TMPL_INFO = String.template(
        "
",
        "
Char:	<tt> $ch </tt>
",
        "
Char code:	 $code / 0x$codeHex
",
        "
Position:	 $point
",
        "
Mark:	 $mark
",
        "
Buffer size:	 $sizeKB
",
        "
"
    );

    D.KEYS = {
        // movement
        "ARROW_UP     && C-p"                     : "backward_line",
        "ARROW_DOWN   && C-n"                     : "forward_line",
        "ARROW_LEFT   && C-b"                     : "backward_char",
        "ARROW_RIGHT  && C-f"                     : "forward_char",
        "HOME"                                    : "beginning_of_indentation_or_line",
        "END && C-e"                              : "end_of_line",
        "C-a"                                     : "beginning_of_line",
        "C-HOME && M-<"                           : "beginning_of_buffer",
        "C-END && M->"                            : "end_of_buffer",
        "C-ARROW_RIGHT && M-f"                    : "forward_word",
        "C-ARROW_LEFT && M-b"                     : "backward_word",
        "C-ARROW_DOWN"                            : "forward_paragraph",
        "C-ARROW_UP"                              : "backward_paragraph",
        "C-l"                                     : "recenter_top_bottom",
        "PAGE_UP && M-v"                          : "scroll_up_half",
        "PAGE_DOWN && C-v"                        : "scroll_down_half",
        "WHEEL_UP"                                : "scroll_up",
        "WHEEL_DOWN"                              : "scroll_down",

        // transient mark
        "S-ARROW_UP       && S-C-p"               : "backward_line_mark",
        "S-ARROW_DOWN     && S-C-n"               : "forward_line_mark",
        "S-ARROW_LEFT     && S-C-b"               : "backward_char_mark",
        "S-ARROW_RIGHT    && S-C-f"               : "forward_char_mark",
        "S-C-ARROW_RIGHT  && S-M-f"               : "forward_word_mark",
        "S-C-ARROW_LEFT   && S-M-b"               : "backward_word_mark",
        "S-C-ARROW_DOWN"                          : "forward_paragraph_mark",
        "S-C-ARROW_UP"                            : "backward_paragraph_mark",
        "S-HOME"                                  : "beginning_of_indentation_or_line_mark",
        "S-C-a"                                   : "beginning_of_line_mark",
        "S-END"                                   : "end_of_line_mark",
        "S-C-HOME"                                : "beginning_of_buffer_mark",
        "S-C-END"                                 : "end_of_buffer_mark",

        // basic editing
        "BACKSPACE"                               : "backward_delete_char",
        "DELETE && C-d"                           : "delete_char",
        "ENTER && C-m"                            : "newline",
        "M-d && C-DELETE"                         : "kill_word",
        "C-BACKSPACE && M-BACKSPACE && M-DELETE"  : "backward_kill_word",
        "C-k"                                     : "kill_line",
        "C-y && S-INSERT"                         : "yank",
        "M-y"                                     : "yank_pop",
        "C-SPACE"                                 : "set_mark_command",
        "C-x C-x"                                 : "exchange_point_and_mark",
        "C-w"                                     : "kill_region",
        "M-t"                                     : "transpose_words",
        "C-t"                                     : "transpose_chars",
        "C-x C-t"                                 : "transpose_lines",
        "M-w"                                     : "copy_region_as_kill",
        "M-c"                                     : "capitalize_word",
        "M-u"                                     : "upcase_word",
        "M-l"                                     : "downcase_word",
        "F11"                                     : "nuke_trailing_whitespace",
        "TAB"                                     : "indent_line",
        "C-M-\\"                                  : "indent_region",
        "M-q"                                     : "fill_paragraph",
        "C-/ && C-x u && C-_ && C-z"              : "undo",
        "INSERT"                                  : "overwrite_mode",
        "M-s"                                     : "center_line",
        "M-/"                                     : "dabbrev_expand",
        "C-s"                                     : "isearch_forward",
        "C-r"                                     : "isearch_backward",
        "M-C-s"                                   : "isearch_forward_regexp",
        "M-C-r"                                   : "isearch_backward_regexp",
        "C-u"                                     : "universal_argument",
        "M-g"                                     : "goto_line",
        "C-x h"                                   : "mark_whole_buffer",
        "C-g"                                     : "keyboard_quit",
        "M-^"                                     : "delete_indentation",
        "M-;"                                     : "comment_dwim",

        // vertical editing
        "C-x r t"                                 : "string_rectangle",
        "C-x r c"                                 : "clear_rectangle",
        "C-x r k"                                 : "kill_rectangle",
        "C-x r y"                                 : "yank_rectangle",

        // buffers
        "C-x C-ARROW_RIGHT && C-x ARROW_RIGHT && C-TAB" : "next_buffer",
        "C-x C-ARROW_LEFT && C-x ARROW_LEFT && C-S-TAB" : "previous_buffer",
        "C-x b"                                         : "switch_to_buffer",
        "C-x k"                                         : "kill_buffer",

        // frames
        "C-x 0"                                   : "delete_frame",
        "C-x 1"                                   : "delete_other_frames",
        "C-x 2"                                   : "split_frame_vertically",
        "C-x 3"                                   : "split_frame_horizontally",
        "C-x o"                                   : "other_frame",
        "C-x l"                                   : "toggle_line_numbers",

        // eval
        "M-x"                                     : "execute_extended_command",

        // necessary evil
        "C-S-y"                                   : "yank_from_operating_system",
        "M-S-w"                                   : "copy_for_operating_system",

        // my stuff, sorry if these have different meanings in the standard Emacs keys
        "M-S-y"                                   : "yank_shift", // that's the reverse of yank_shift
        "C-c /"                                   : "close_last_xml_tag",
        "S-BACKSPACE"                             : "backward_delete_whitespace",
        "S-DELETE"                                : "delete_whitespace",
        "C-M-d"                                   : "delete_region_or_line",
        "M-ENTER"                                 : "start_next_paragraph",
        "M-S-q"                                   : "fill_paragraph_no_prefix",
        "C-M-|"                                   : "cperl_lineup",
        "C-F4"                                    : "kill_buffer",
        "M-ARROW_LEFT"                            : [ "windmove", "left" ],
        "M-ARROW_RIGHT"                           : [ "windmove", "right" ],
        "M-ARROW_UP"                              : [ "windmove", "up" ],
        "M-ARROW_DOWN"                            : [ "windmove", "down" ],

        "C-x e"                                   : "kmacro_end_and_call_macro",
        "C-x ("                                   : "kmacro_start_macro",
        "C-x )"                                   : "kmacro_end_macro",

        // file system commands
        "C-x C-f"                                 : "find_file",
        "C-x C-w"                                 : "write_file",
        "C-x C-s"                                 : "save_buffer",
        "C-x s"                                   : "save_some_buffers",

        // others
        "C-x =": function() {
            var ch = this.charAt(), chname = ch;
            if (ch == " ")
                chname = "<SPACE>";
            else if (ch == "\n")
                chname = "<NEWLINE>";
            else if (ch == "-")
                chname = "<DASH>";
            this.signalInfo(TMPL_INFO({
                ch      : chname.htmlEscape(),
                code    : ch.charCodeAt(0),
                codeHex : ch.charCodeAt().hex(),
                point   : this.point(),
                mark    : this.markMarker.getPosition(),
                size    : this.getCodeSize(),
                sizeKB  : this.getCodeSize().formatBytes(2)
            }), true);
        }
    };

    P.defaultHandler = [ "self_insert_command" ];

});

DEFINE_SINGLETON("Ymacs_Keymap_UniversalArgument", Ymacs_Keymap, function(D, P){

    P.defaultHandler = [ Ymacs_Interactive("^", function(){
        var ev = this.interactiveEvent(),
        ch = String.fromCharCode(ev.charCode),
        prefix = this.getPrefixArg(true);
        if (ev.charCode && (/^[0-9]$/.test(ch) || (ch === "-" && prefix === "")) && !ev.altKey && !ev.ctrlKey) {
            prefix += ch;
            this.setPrefixArg(prefix);
            if (!this.isMinibuffer) {
                this.whenMinibuffer(function(mb){
                    mb.cmd("insert", " ", ch);
                });
            }
            return true;
        }
        this.popKeymap(Ymacs_Keymap_UniversalArgument());
        return false;
    }) ];

    P.attached = function(buffer) {
        buffer.setPrefixArg("");
    };

});
<commit_msg>add S-C-e keybinding<commit_after>//> This file is part of Ymacs, an Emacs-like editor for the Web
//> http://www.ymacs.org/
//>
//> Copyright (c) 2009-2012, Mihai Bazon, Dynarch.com.  All rights reserved.
//>
//> Redistribution and use in source and binary forms, with or without
//> modification, are permitted provided that the following conditions are
//> met:
//>
//>     * Redistributions of source code must retain the above copyright
//>       notice, this list of conditions and the following disclaimer.
//>
//>     * Redistributions in binary form must reproduce the above copyright
//>       notice, this list of conditions and the following disclaimer in
//>       the documentation and/or other materials provided with the
//>       distribution.
//>
//>     * Neither the name of Dynarch.com nor the names of its contributors
//>       may be used to endorse or promote products derived from this
//>       software without specific prior written permission.
//>
//> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
//> EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//> PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
//> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//> CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//> SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//> INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
//> CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//> ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
//> THE POSSIBILITY OF SUCH DAMAGE.

// @require ymacs-keymap.js

// This is the default keymap, as configured in
// Ymacs_Buffer::makeDefaultKeymap.  It follows closely the standard
// Emacs keybindings, with some small deviations that match my taste
// (search for "my stuff" below).

// It would be nice to have more options, such as an Eclipse keymap,
// or Visual Studio -- but I'm not familiar with any of them.
// Contributions welcome.

// A keymap inherits from Ymacs_Keymap and should define its bindings
// in D.KEYS.  They can also define a defaultHandler property to take
// whatever action they consider necessary -- for example the Isearch
// keymap will, by default, print the entered character in the
// minibuffer and trigger a search action.  Isearch mode is almost
// completely defined in a keymap -- with the minor note that
// isearch_forward and isearch_backward are assigned below to key
// combinations; once pressed, they will push the Isearch keymap onto
// the buffer's keymap stack, and it will be used until isearch is
// ended.

/* KEY DEFINITIONS.  A key is generally defined in standard Emacs
   notation, with the following notes:

   - it is possible to define multiple keys at once for the same
   operation, by using the "&&" combination (separate with spaces
   from the actual keys)

   - some special characters are named literally; their names contain
   more than one character.  The available names are defined in
   DlKeyboard (see keyboard.js in DynarchLIB).  Examples:
   ARROW_RIGHT, PAGE_UP, etc. but also SPACE and DASH.

   Normally you would define commands using Ymacs_Buffer.newCommands
   (see ymacs-commands.js) and specify the command name for key
   bindings, but you can specify a function as well, if you want:

   "C-8": function() {
   alert("You pressed CTRL-8");
   }

   It is advised to define commands for more than simple cases, for
   two reasons:

   1. they can be used for "non-interactive" calls too

   2. the command name is saved in this.currentCommand /
   this.previousCommand, which is useful in a number of cases.

*/

DEFINE_SINGLETON("Ymacs_Keymap_Emacs", Ymacs_Keymap, function(D, P){

    var TMPL_INFO = String.template(
        "
",
        "
Char:	<tt> $ch </tt>
",
        "
Char code:	 $code / 0x$codeHex
",
        "
Position:	 $point
",
        "
Mark:	 $mark
",
        "
Buffer size:	 $sizeKB
",
        "
"
    );

    D.KEYS = {
        // movement
        "ARROW_UP     && C-p"                     : "backward_line",
        "ARROW_DOWN   && C-n"                     : "forward_line",
        "ARROW_LEFT   && C-b"                     : "backward_char",
        "ARROW_RIGHT  && C-f"                     : "forward_char",
        "HOME"                                    : "beginning_of_indentation_or_line",
        "END && C-e"                              : "end_of_line",
        "C-a"                                     : "beginning_of_line",
        "C-HOME && M-<"                           : "beginning_of_buffer",
        "C-END && M->"                            : "end_of_buffer",
        "C-ARROW_RIGHT && M-f"                    : "forward_word",
        "C-ARROW_LEFT && M-b"                     : "backward_word",
        "C-ARROW_DOWN"                            : "forward_paragraph",
        "C-ARROW_UP"                              : "backward_paragraph",
        "C-l"                                     : "recenter_top_bottom",
        "PAGE_UP && M-v"                          : "scroll_up_half",
        "PAGE_DOWN && C-v"                        : "scroll_down_half",
        "WHEEL_UP"                                : "scroll_up",
        "WHEEL_DOWN"                              : "scroll_down",

        // transient mark
        "S-ARROW_UP       && S-C-p"               : "backward_line_mark",
        "S-ARROW_DOWN     && S-C-n"               : "forward_line_mark",
        "S-ARROW_LEFT     && S-C-b"               : "backward_char_mark",
        "S-ARROW_RIGHT    && S-C-f"               : "forward_char_mark",
        "S-C-ARROW_RIGHT  && S-M-f"               : "forward_word_mark",
        "S-C-ARROW_LEFT   && S-M-b"               : "backward_word_mark",
        "S-C-ARROW_DOWN"                          : "forward_paragraph_mark",
        "S-C-ARROW_UP"                            : "backward_paragraph_mark",
        "S-HOME"                                  : "beginning_of_indentation_or_line_mark",
        "S-C-a"                                   : "beginning_of_line_mark",
        "S-END && S-C-e"                          : "end_of_line_mark",
        "S-C-HOME"                                : "beginning_of_buffer_mark",
        "S-C-END"                                 : "end_of_buffer_mark",

        // basic editing
        "BACKSPACE"                               : "backward_delete_char",
        "DELETE && C-d"                           : "delete_char",
        "ENTER && C-m"                            : "newline",
        "M-d && C-DELETE"                         : "kill_word",
        "C-BACKSPACE && M-BACKSPACE && M-DELETE"  : "backward_kill_word",
        "C-k"                                     : "kill_line",
        "C-y && S-INSERT"                         : "yank",
        "M-y"                                     : "yank_pop",
        "C-SPACE"                                 : "set_mark_command",
        "C-x C-x"                                 : "exchange_point_and_mark",
        "C-w"                                     : "kill_region",
        "M-t"                                     : "transpose_words",
        "C-t"                                     : "transpose_chars",
        "C-x C-t"                                 : "transpose_lines",
        "M-w"                                     : "copy_region_as_kill",
        "M-c"                                     : "capitalize_word",
        "M-u"                                     : "upcase_word",
        "M-l"                                     : "downcase_word",
        "F11"                                     : "nuke_trailing_whitespace",
        "TAB"                                     : "indent_line",
        "C-M-\\"                                  : "indent_region",
        "M-q"                                     : "fill_paragraph",
        "C-/ && C-x u && C-_ && C-z"              : "undo",
        "INSERT"                                  : "overwrite_mode",
        "M-s"                                     : "center_line",
        "M-/"                                     : "dabbrev_expand",
        "C-s"                                     : "isearch_forward",
        "C-r"                                     : "isearch_backward",
        "M-C-s"                                   : "isearch_forward_regexp",
        "M-C-r"                                   : "isearch_backward_regexp",
        "C-u"                                     : "universal_argument",
        "M-g"                                     : "goto_line",
        "C-x h"                                   : "mark_whole_buffer",
        "C-g"                                     : "keyboard_quit",
        "M-^"                                     : "delete_indentation",
        "M-;"                                     : "comment_dwim",

        // vertical editing
        "C-x r t"                                 : "string_rectangle",
        "C-x r c"                                 : "clear_rectangle",
        "C-x r k"                                 : "kill_rectangle",
        "C-x r y"                                 : "yank_rectangle",

        // buffers
        "C-x C-ARROW_RIGHT && C-x ARROW_RIGHT && C-TAB" : "next_buffer",
        "C-x C-ARROW_LEFT && C-x ARROW_LEFT && C-S-TAB" : "previous_buffer",
        "C-x b"                                         : "switch_to_buffer",
        "C-x k"                                         : "kill_buffer",

        // frames
        "C-x 0"                                   : "delete_frame",
        "C-x 1"                                   : "delete_other_frames",
        "C-x 2"                                   : "split_frame_vertically",
        "C-x 3"                                   : "split_frame_horizontally",
        "C-x o"                                   : "other_frame",
        "C-x l"                                   : "toggle_line_numbers",

        // eval
        "M-x"                                     : "execute_extended_command",

        // necessary evil
        "C-S-y"                                   : "yank_from_operating_system",
        "M-S-w"                                   : "copy_for_operating_system",

        // my stuff, sorry if these have different meanings in the standard Emacs keys
        "M-S-y"                                   : "yank_shift", // that's the reverse of yank_shift
        "C-c /"                                   : "close_last_xml_tag",
        "S-BACKSPACE"                             : "backward_delete_whitespace",
        "S-DELETE"                                : "delete_whitespace",
        "C-M-d"                                   : "delete_region_or_line",
        "M-ENTER"                                 : "start_next_paragraph",
        "M-S-q"                                   : "fill_paragraph_no_prefix",
        "C-M-|"                                   : "cperl_lineup",
        "C-F4"                                    : "kill_buffer",
        "M-ARROW_LEFT"                            : [ "windmove", "left" ],
        "M-ARROW_RIGHT"                           : [ "windmove", "right" ],
        "M-ARROW_UP"                              : [ "windmove", "up" ],
        "M-ARROW_DOWN"                            : [ "windmove", "down" ],

        "C-x e"                                   : "kmacro_end_and_call_macro",
        "C-x ("                                   : "kmacro_start_macro",
        "C-x )"                                   : "kmacro_end_macro",

        // file system commands
        "C-x C-f"                                 : "find_file",
        "C-x C-w"                                 : "write_file",
        "C-x C-s"                                 : "save_buffer",
        "C-x s"                                   : "save_some_buffers",

        // others
        "C-x =": function() {
            var ch = this.charAt(), chname = ch;
            if (ch == " ")
                chname = "<SPACE>";
            else if (ch == "\n")
                chname = "<NEWLINE>";
            else if (ch == "-")
                chname = "<DASH>";
            this.signalInfo(TMPL_INFO({
                ch      : chname.htmlEscape(),
                code    : ch.charCodeAt(0),
                codeHex : ch.charCodeAt().hex(),
                point   : this.point(),
                mark    : this.markMarker.getPosition(),
                size    : this.getCodeSize(),
                sizeKB  : this.getCodeSize().formatBytes(2)
            }), true);
        }
    };

    P.defaultHandler = [ "self_insert_command" ];

});

DEFINE_SINGLETON("Ymacs_Keymap_UniversalArgument", Ymacs_Keymap, function(D, P){

    P.defaultHandler = [ Ymacs_Interactive("^", function(){
        var ev = this.interactiveEvent(),
        ch = String.fromCharCode(ev.charCode),
        prefix = this.getPrefixArg(true);
        if (ev.charCode && (/^[0-9]$/.test(ch) || (ch === "-" && prefix === "")) && !ev.altKey && !ev.ctrlKey) {
            prefix += ch;
            this.setPrefixArg(prefix);
            if (!this.isMinibuffer) {
                this.whenMinibuffer(function(mb){
                    mb.cmd("insert", " ", ch);
                });
            }
            return true;
        }
        this.popKeymap(Ymacs_Keymap_UniversalArgument());
        return false;
    }) ];

    P.attached = function(buffer) {
        buffer.setPrefixArg("");
    };

});
<|endoftext|>


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

var Suite = require('mocha/lib/suite');
var Test = require('mocha/lib/test');
var event = require('../event');
var scenario = require('../scenario');
var recorder = require('../recorder');
var escapeRe = require('escape-string-regexp');

/**
 * Codecept-style interface:
 *
 * Feature('login')
 * Scenario('login as regular user', (I) {
 *   I.fillField();
 *   I.click()
 *   I.see('Hello, '+data.login);
 * });
 *
 * @param {Suite} suite Root suite.
 */
module.exports = function (suite) {
  var suites = [suite];
  suite.timeout(0);

  suite.on('pre-require', function (context, file, mocha) {
    var common = require('mocha/lib/interfaces/common')(suites, context);

    // create dispatcher

    context.BeforeAll = common.before;
    context.AfterAll = common.after;

    context.run = mocha.options.delay && common.runWithSuite(suite);
    /**
     * Describe a "suite" with the given `title`
     * and callback `fn` containing nested suites
     * and/or tests.
     */

    context.Feature = function (title, opts) {
      if (suites.length > 1) {
        suites.shift();
      }
      if (!opts) opts = {};
      var suite = Suite.create(suites[0], title);
      suite.timeout(0);

      if (opts.retries) suite.retries(opts.retries);
      if (opts.timeout) suite.timeout(opts.timeout);

      suite.file = file;
      suites.unshift(suite);
      suite.beforeEach('codeceptjs.before', scenario.setup);
      suite.afterEach('finialize codeceptjs', scenario.teardown);

      suite.beforeAll('codeceptjs.beforeSuite', scenario.suiteSetup);
      suite.afterAll('codeceptjs.afterSuite', scenario.suiteTeardown);

      return suite;
    };

    context.BeforeSuite = function (fn) {
      suites[0].beforeAll('BeforeSuite', scenario.injected(fn));
    };

    context.AfterSuite = function (fn) {
      suites[0].afterAll('AfterSuite', scenario.injected(fn));
    };

    context.Background = context.Before = function (fn) {
      suites[0].beforeEach('Before', scenario.injected(fn));
    };

    context.After = function (fn) {
      suites[0].afterEach('After', scenario.injected(fn));
    };

    /**
     * Describe a specification or test-case
     * with the given `title` and callback `fn`
     * acting as a thunk.
     */
    context.Scenario = function (title, opts, fn) {
      if ((typeof opts == 'function') && !fn) {
        fn = opts;
        opts = {}
      }

      var suite = suites[0];
      if (suite.pending) {
        fn = null;
      }
      var test = new Test(title, fn);
      test.fullTitle = () => `${suite.title}: ${title}`;
      test.file = file;
      test.async = true;
      test.timeout(0);

      if (opts.retries) test.retries(opts.retries);
      if (opts.timeout) test.timeout(opts.timeout);

      suite.addTest(scenario.test(test));
      return test;
    };

    /**
     * Exclusive test-case.
     */
    context.Scenario.only = function (title, fn) {
      var test = context.Scenario(title, fn);
      var reString = '^' + escapeRe(test.fullTitle()) + '$';
      mocha.grep(new RegExp(reString));
    };

    /**
     * Pending test case.
     */
    context.xScenario = context.Scenario.skip = function (title) {
      context.Scenario(title);
    };
  });
};
<commit_msg>Pass empty opts object to test when skipping (#359)<commit_after>/**
 * Module dependencies.
 */

var Suite = require('mocha/lib/suite');
var Test = require('mocha/lib/test');
var event = require('../event');
var scenario = require('../scenario');
var recorder = require('../recorder');
var escapeRe = require('escape-string-regexp');

/**
 * Codecept-style interface:
 *
 * Feature('login')
 * Scenario('login as regular user', (I) {
 *   I.fillField();
 *   I.click()
 *   I.see('Hello, '+data.login);
 * });
 *
 * @param {Suite} suite Root suite.
 */
module.exports = function (suite) {
  var suites = [suite];
  suite.timeout(0);

  suite.on('pre-require', function (context, file, mocha) {
    var common = require('mocha/lib/interfaces/common')(suites, context);

    // create dispatcher

    context.BeforeAll = common.before;
    context.AfterAll = common.after;

    context.run = mocha.options.delay && common.runWithSuite(suite);
    /**
     * Describe a "suite" with the given `title`
     * and callback `fn` containing nested suites
     * and/or tests.
     */

    context.Feature = function (title, opts) {
      if (suites.length > 1) {
        suites.shift();
      }
      if (!opts) opts = {};
      var suite = Suite.create(suites[0], title);
      suite.timeout(0);

      if (opts.retries) suite.retries(opts.retries);
      if (opts.timeout) suite.timeout(opts.timeout);

      suite.file = file;
      suites.unshift(suite);
      suite.beforeEach('codeceptjs.before', scenario.setup);
      suite.afterEach('finialize codeceptjs', scenario.teardown);

      suite.beforeAll('codeceptjs.beforeSuite', scenario.suiteSetup);
      suite.afterAll('codeceptjs.afterSuite', scenario.suiteTeardown);

      return suite;
    };

    context.BeforeSuite = function (fn) {
      suites[0].beforeAll('BeforeSuite', scenario.injected(fn));
    };

    context.AfterSuite = function (fn) {
      suites[0].afterAll('AfterSuite', scenario.injected(fn));
    };

    context.Background = context.Before = function (fn) {
      suites[0].beforeEach('Before', scenario.injected(fn));
    };

    context.After = function (fn) {
      suites[0].afterEach('After', scenario.injected(fn));
    };

    /**
     * Describe a specification or test-case
     * with the given `title` and callback `fn`
     * acting as a thunk.
     */
    context.Scenario = function (title, opts, fn) {
      if ((typeof opts == 'function') && !fn) {
        fn = opts;
        opts = {}
      }

      var suite = suites[0];
      if (suite.pending) {
        fn = null;
      }
      var test = new Test(title, fn);
      test.fullTitle = () => `${suite.title}: ${title}`;
      test.file = file;
      test.async = true;
      test.timeout(0);

      if (opts.retries) test.retries(opts.retries);
      if (opts.timeout) test.timeout(opts.timeout);

      suite.addTest(scenario.test(test));
      return test;
    };

    /**
     * Exclusive test-case.
     */
    context.Scenario.only = function (title, fn) {
      var test = context.Scenario(title, fn);
      var reString = '^' + escapeRe(test.fullTitle()) + '$';
      mocha.grep(new RegExp(reString));
    };

    /**
     * Pending test case.
     */
    context.xScenario = context.Scenario.skip = function (title) {
      context.Scenario(title, {});
    };
  });
};
<|endoftext|>


<commit_before>/*
 * Namespace: lb.base.template.html
 * Base Module for HTML Templates
 *
 * This module defines filter functions for HTML templates, for use with
 * <lb.base.template.applyFilters(input...,filters):any> in the base template
 * module.
 *
 * HTML filters are applied to DOM nodes, which get modified in place. In order
 * to keep the original template for reuse with a different set of values, the
 * node should be cloned before HTML filters are applied.
 *
 * Author:
 * Eric Bréchemier <legalbox@eric.brechemier.name>
 *
 * Copyright:
 * Legal-Box SAS (c) 2010-2011, All Rights Reserved
 *
 * License:
 * BSD License
 * http://creativecommons.org/licenses/BSD/
 *
 * Version:
 * 2011-04-20
 */
/*requires lb.base.template.js */
/*jslint white:false, plusplus:false */
/*global lb, goog, window */
lb.base.template.html = (function() {
  // Builder of
  // Closure for lb.base.template.html module

  // Declare aliases

  var /*requires lb.base.object.js */
      has = lb.base.object.has,
      /*requires lb.base.type.js */
      is = lb.base.type.is,
      /*requires lb.base.array.js */
      toArray = lb.base.array.toArray,
      /*requires lb.base.dom.js */
      dom = lb.base.dom,
      ELEMENT_NODE = dom.ELEMENT_NODE,
      ATTRIBUTE_NODE = dom.ATTRIBUTE_NODE,
      TEXT_NODE = dom.TEXT_NODE,
      applyFilters = lb.base.template.applyFilters,
      /*requires lb.base.template.string.js */
      replaceParamsInString = lb.base.template.string.replaceParams,
      /*requires lb.base.log.js */
      log = lb.base.log.print;

  function topDownParsing(node){
    // Function: topDownParsing(node[,context...],filters)
    // Apply filters recursively to attributes and child nodes.
    //
    // The attributes are processed first (the order is browser-dependent),
    // then child nodes are processed in a depth-first recursion.
    //
    // Parameters:
    //   node - DOM Node, a DOM node. Only elements are processed by this
    //          filter, other nodes are left untouched.
    //   context... - any, optional, variable number of parameters providing
    //             context to the transformation. All context arguments are
    //             forwarded in recursive calls to applyFilters().
    //   filters - array of functions, the list of filter functions to be
    //             applied recursively. This argument is required and always
    //             last, which allows filter functions applied to any number
    //             of context arguments to omit it in their declaration.
    //
    // Note:
    // In Internet Explorer, lots of attribute nodes are present with a default
    // value. Only attributes explicitly defined in the document or through
    // JavaScript are processed: attributes that do not have 'specified'
    // property set to true are ignored.
    //
    // Reference:
    //   specified - Interface Attr
    //   http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-637646024
    if ( !has(node) || node.nodeType !== ELEMENT_NODE ){
      return;
    }

    var args = toArray(arguments),
        attributes = toArray(node.attributes),
        childNodes = toArray(node.childNodes),
        i,
        length,
        attribute;

    for (i=0,length=attributes.length; i<length; i++){
      attribute = attributes[i];
      if ( attribute.specified ) {
        args[0] = attribute;
        try {
          applyFilters.apply(null,args);
        } catch( attributeFilterError ) {
          log(
            'Failed to apply HTML filters to attribute "'+attribute.name+'" '+
            'of element '+node.nodeName+ ( node.id? '#'+node.id+'' :
            (node.className?' class="'+node.className+'"':'') )+
            ': '+attributeFilterError
          );
        }
      }
    }
    for (i=0,length=childNodes.length; i<length; i++){
      args[0] = childNodes[i];
      try {
        applyFilters.apply(null,args);
      } catch ( childNodeFilterError ) {
        log(
          'Failed to apply HTML filters to child node '+childNodes[i]+
          ' in position '+(i+1)+
          ' of element '+node.nodeName+ ( node.id? '#'+node.id+'' :
          (node.className?' class="'+node.className+'"':'') )+
          ': '+childNodeFilterError
        );
      }
    }
  }

  function getBaseUrl(url){
    // (Private) getBaseUrl(url)
    // Get the base URL of the page (without the hash part).
    //
    // This method is extracted and adapted from bezen.template.js
    // in the bezen.org JavaScript library, CC-BY Eric Bréchemier.
    //
    // Parameters::
    //   url - string, optional, defaults to window.location.href, the url
    //         to truncate
    //   Note: I switched from document.URL to window.location.href for
    //         accurate results with local files in Internet Explorer.
    //         Although both share the same value for online files using the
    //         http/https protocols, with the file protocol, in IE,
    //         document.URL will look like
    //           file://D:\web\bezen.org\javascript\test\test-template.html
    //         while the corresponding window.location.href would be
    //           file:///D:/web/bezen.org/javascript/test/test-template.html
    //
    // Returns:
    //   string, the input URL, with the hash part removed
    url = has(url)? url : window.location.href;

    // Remove the fragment part of the url
    var pos = url.indexOf("#");
    return ( pos<0? url: url.slice(0,pos) );
  }

  function getNodeValue(node) {
    // (Private) getNodeValue(node)
    // Get the node value.
    //
    // This method is extracted and adapted from bezen.template.js
    // in the bezen.org JavaScript library, CC-BY Eric Bréchemier.
    //
    // A specific processing is required for URLs in (A) href and (IMG) src
    // attributes, which get transformed to an absolute path in IE 7,
    // prepending the web page URL to the left of the #param#.
    // This method removes the web page URL if found at the start of a
    // href or src attribute.
    //
    // Parameters:
    //   node - DOM node, a node with a value
    //          (PRE: node.nodeValue is truthy)
    //
    // Returns:
    //   string or any, the node value from node.nodeValue, with the URL of the
    //   page removed from the start for href and src attributes.
    //   This value is typically a string. It may also be null, e.g. for the
    //   document itself, and may be a number or even an object (for custom
    //   properties, considered as attributes) in Internet Explorer.
    if ( (node.nodeType === ATTRIBUTE_NODE) &&
         (node.name === 'href' || node.name === 'src')  ) {
      var baseUrl = getBaseUrl();
      if ( node.nodeValue.indexOf(baseUrl) === 0 ) {
        // Remove absolute URL added by IE 7 at start of local href and src
        // The URL is identical to the part of window.location.href before the '#'
        return node.nodeValue.replace(baseUrl,'');
      }
    }
    return node.nodeValue;
  }

  function replaceParams(getValue){
    // Function: replaceParams(getValue): function
    // Get a filter function to replace parameters in attribute and text nodes.
    //
    // This method applies replaceParams() from the base string templates
    // module, and follows the same conventions:
    // - parameters to replace are surrounded by '#' characters
    // - getValue() is called for replacement values
    //
    // See details of parameter format in
    // <lb.base.template.string.replaceParams(getValue): function>.
    //
    // Parameter:
    //   getValue - function, a getter function returning values for the
    //              replacement of parameters:
    //              | function(name): any
    //              The name argument is the name of the parameter to replace.
    //              The getter value should return string values when a
    //              matching property is found, and null otherwise.
    //
    // Returns:
    //   * function, a closure wrapped around the given getter function, with
    //     the following signature:
    //     | Function: filter(htmlNode)
    //     | Replace parameters in attribute and text nodes
    //     | with corresponding values returned by getValue().
    //     |
    //     | The replacements are operated in place in given node.
    //     |
    //     | Parameters:
    //     |   htmlNode - DOM Node, a DOM node. Only attribute and text nodes
    //     |              are considered for parameter replacement.
    //     |              Other nodes are left untouched.
    //   * null when the required getter argument is missing or not a function
    if ( !is(getValue,'function') ){
      return null;
    }
    var replaceParamsWithValues = replaceParamsInString(getValue);
    return function(htmlNode){
      if (  !has(htmlNode) ||
            ( htmlNode.nodeType!==ATTRIBUTE_NODE &&
              htmlNode.nodeType!==TEXT_NODE )  ){
        return;
      }
      var oldValue,
          newValue;

      // In IE7, the base location of the window (without the hash part) is
      // prepended to the nodeValue for img src and a href:
      // e.g. "#param#" becomes "http://example.org/#param#".
      oldValue = getNodeValue(htmlNode);
      newValue = replaceParamsWithValues(oldValue);

      if (newValue !== oldValue) {
        // only set if the new value differs, to avoid issues in IE:
        // for example, setting the nodeValue of input.type attribute fails
        // when the input element is in the DOM.
        htmlNode.nodeValue = newValue;
      }
    };
  }

  return { // public API
    topDownParsing: topDownParsing,
    replaceParams: replaceParams
  };
}());
<commit_msg>Removed empty strings at end of concatenations, per JSLint suggestion<commit_after>/*
 * Namespace: lb.base.template.html
 * Base Module for HTML Templates
 *
 * This module defines filter functions for HTML templates, for use with
 * <lb.base.template.applyFilters(input...,filters):any> in the base template
 * module.
 *
 * HTML filters are applied to DOM nodes, which get modified in place. In order
 * to keep the original template for reuse with a different set of values, the
 * node should be cloned before HTML filters are applied.
 *
 * Author:
 * Eric Bréchemier <legalbox@eric.brechemier.name>
 *
 * Copyright:
 * Legal-Box SAS (c) 2010-2011, All Rights Reserved
 *
 * License:
 * BSD License
 * http://creativecommons.org/licenses/BSD/
 *
 * Version:
 * 2011-05-06
 */
/*requires lb.base.template.js */
/*jslint white:false, plusplus:false */
/*global lb, goog, window */
lb.base.template.html = (function() {
  // Builder of
  // Closure for lb.base.template.html module

  // Declare aliases

  var /*requires lb.base.object.js */
      has = lb.base.object.has,
      /*requires lb.base.type.js */
      is = lb.base.type.is,
      /*requires lb.base.array.js */
      toArray = lb.base.array.toArray,
      /*requires lb.base.dom.js */
      dom = lb.base.dom,
      ELEMENT_NODE = dom.ELEMENT_NODE,
      ATTRIBUTE_NODE = dom.ATTRIBUTE_NODE,
      TEXT_NODE = dom.TEXT_NODE,
      applyFilters = lb.base.template.applyFilters,
      /*requires lb.base.template.string.js */
      replaceParamsInString = lb.base.template.string.replaceParams,
      /*requires lb.base.log.js */
      log = lb.base.log.print;

  function topDownParsing(node){
    // Function: topDownParsing(node[,context...],filters)
    // Apply filters recursively to attributes and child nodes.
    //
    // The attributes are processed first (the order is browser-dependent),
    // then child nodes are processed in a depth-first recursion.
    //
    // Parameters:
    //   node - DOM Node, a DOM node. Only elements are processed by this
    //          filter, other nodes are left untouched.
    //   context... - any, optional, variable number of parameters providing
    //             context to the transformation. All context arguments are
    //             forwarded in recursive calls to applyFilters().
    //   filters - array of functions, the list of filter functions to be
    //             applied recursively. This argument is required and always
    //             last, which allows filter functions applied to any number
    //             of context arguments to omit it in their declaration.
    //
    // Note:
    // In Internet Explorer, lots of attribute nodes are present with a default
    // value. Only attributes explicitly defined in the document or through
    // JavaScript are processed: attributes that do not have 'specified'
    // property set to true are ignored.
    //
    // Reference:
    //   specified - Interface Attr
    //   http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-637646024
    if ( !has(node) || node.nodeType !== ELEMENT_NODE ){
      return;
    }

    var args = toArray(arguments),
        attributes = toArray(node.attributes),
        childNodes = toArray(node.childNodes),
        i,
        length,
        attribute;

    for (i=0,length=attributes.length; i<length; i++){
      attribute = attributes[i];
      if ( attribute.specified ) {
        args[0] = attribute;
        try {
          applyFilters.apply(null,args);
        } catch( attributeFilterError ) {
          log(
            'Failed to apply HTML filters to attribute "'+attribute.name+'" '+
            'of element '+node.nodeName+ ( node.id? '#'+node.id :
            (node.className?' class="'+node.className+'"':'') )+
            ': '+attributeFilterError
          );
        }
      }
    }
    for (i=0,length=childNodes.length; i<length; i++){
      args[0] = childNodes[i];
      try {
        applyFilters.apply(null,args);
      } catch ( childNodeFilterError ) {
        log(
          'Failed to apply HTML filters to child node '+childNodes[i]+
          ' in position '+(i+1)+
          ' of element '+node.nodeName+ ( node.id? '#'+node.id :
          (node.className?' class="'+node.className+'"':'') )+
          ': '+childNodeFilterError
        );
      }
    }
  }

  function getBaseUrl(url){
    // (Private) getBaseUrl(url)
    // Get the base URL of the page (without the hash part).
    //
    // This method is extracted and adapted from bezen.template.js
    // in the bezen.org JavaScript library, CC-BY Eric Bréchemier.
    //
    // Parameters::
    //   url - string, optional, defaults to window.location.href, the url
    //         to truncate
    //   Note: I switched from document.URL to window.location.href for
    //         accurate results with local files in Internet Explorer.
    //         Although both share the same value for online files using the
    //         http/https protocols, with the file protocol, in IE,
    //         document.URL will look like
    //           file://D:\web\bezen.org\javascript\test\test-template.html
    //         while the corresponding window.location.href would be
    //           file:///D:/web/bezen.org/javascript/test/test-template.html
    //
    // Returns:
    //   string, the input URL, with the hash part removed
    url = has(url)? url : window.location.href;

    // Remove the fragment part of the url
    var pos = url.indexOf("#");
    return ( pos<0? url: url.slice(0,pos) );
  }

  function getNodeValue(node) {
    // (Private) getNodeValue(node)
    // Get the node value.
    //
    // This method is extracted and adapted from bezen.template.js
    // in the bezen.org JavaScript library, CC-BY Eric Bréchemier.
    //
    // A specific processing is required for URLs in (A) href and (IMG) src
    // attributes, which get transformed to an absolute path in IE 7,
    // prepending the web page URL to the left of the #param#.
    // This method removes the web page URL if found at the start of a
    // href or src attribute.
    //
    // Parameters:
    //   node - DOM node, a node with a value
    //          (PRE: node.nodeValue is truthy)
    //
    // Returns:
    //   string or any, the node value from node.nodeValue, with the URL of the
    //   page removed from the start for href and src attributes.
    //   This value is typically a string. It may also be null, e.g. for the
    //   document itself, and may be a number or even an object (for custom
    //   properties, considered as attributes) in Internet Explorer.
    if ( (node.nodeType === ATTRIBUTE_NODE) &&
         (node.name === 'href' || node.name === 'src')  ) {
      var baseUrl = getBaseUrl();
      if ( node.nodeValue.indexOf(baseUrl) === 0 ) {
        // Remove absolute URL added by IE 7 at start of local href and src
        // The URL is identical to the part of window.location.href before the '#'
        return node.nodeValue.replace(baseUrl,'');
      }
    }
    return node.nodeValue;
  }

  function replaceParams(getValue){
    // Function: replaceParams(getValue): function
    // Get a filter function to replace parameters in attribute and text nodes.
    //
    // This method applies replaceParams() from the base string templates
    // module, and follows the same conventions:
    // - parameters to replace are surrounded by '#' characters
    // - getValue() is called for replacement values
    //
    // See details of parameter format in
    // <lb.base.template.string.replaceParams(getValue): function>.
    //
    // Parameter:
    //   getValue - function, a getter function returning values for the
    //              replacement of parameters:
    //              | function(name): any
    //              The name argument is the name of the parameter to replace.
    //              The getter value should return string values when a
    //              matching property is found, and null otherwise.
    //
    // Returns:
    //   * function, a closure wrapped around the given getter function, with
    //     the following signature:
    //     | Function: filter(htmlNode)
    //     | Replace parameters in attribute and text nodes
    //     | with corresponding values returned by getValue().
    //     |
    //     | The replacements are operated in place in given node.
    //     |
    //     | Parameters:
    //     |   htmlNode - DOM Node, a DOM node. Only attribute and text nodes
    //     |              are considered for parameter replacement.
    //     |              Other nodes are left untouched.
    //   * null when the required getter argument is missing or not a function
    if ( !is(getValue,'function') ){
      return null;
    }
    var replaceParamsWithValues = replaceParamsInString(getValue);
    return function(htmlNode){
      if (  !has(htmlNode) ||
            ( htmlNode.nodeType!==ATTRIBUTE_NODE &&
              htmlNode.nodeType!==TEXT_NODE )  ){
        return;
      }
      var oldValue,
          newValue;

      // In IE7, the base location of the window (without the hash part) is
      // prepended to the nodeValue for img src and a href:
      // e.g. "#param#" becomes "http://example.org/#param#".
      oldValue = getNodeValue(htmlNode);
      newValue = replaceParamsWithValues(oldValue);

      if (newValue !== oldValue) {
        // only set if the new value differs, to avoid issues in IE:
        // for example, setting the nodeValue of input.type attribute fails
        // when the input element is in the DOM.
        htmlNode.nodeValue = newValue;
      }
    };
  }

  return { // public API
    topDownParsing: topDownParsing,
    replaceParams: replaceParams
  };
}());
<|endoftext|>


<commit_before>(function($) {
  $.shining = function() {
    $.shining.slides = {
      get length()      { return this._slides.length },
      get current()     { return (typeof this._current == 'undefined' ? this._slides[0] : this._slides[this._current]) },
      set current(_new) { this._current = this._slides.indexOf(_new); return this.current },
      get all()         { return this._slides },
      get first()       { return this._slides[0] },
      get last()        { return this._slides[ this._slides.length - 1 ] },
      get next()        { return this._slides[ this._slides.indexOf(this.current) + 1 ] },
      get previous()    { return this._slides[ this._slides.indexOf(this.current) - 1 ] },
      add: function(slides) { return Array.prototype.push.apply(this._slides, slides) },
      _slides: [],
      _current: 0
    };

    String.prototype.markup = function() { return this + '.html' };
    String.prototype.script = function() { return this + '.js' };
    String.prototype.style =  function() { return this + '.css' };

    $.extend($.shining, {
      firstSlide:     function() { getSlide($.shining.slides.first) },
      lastSlide:      function() { getSlide($.shining.slides.last ) },
      nextSlide:      function() { getSlide($.shining.slides.next) },
      previousSlide:  function() { getSlide($.shining.slides.previous) }
    });

    function init()         {
      $(document).ready(function() {
        $('#controls').ondistance(
          300,
          function(controls) { $(controls).addClass('fades-in') },
          function(controls) { $(controls).removeClass('fades-in') }
        );
        $('#controls #first').    click(function() { $.shining.firstSlide() });
        $('#controls #previous'). click(function() { $.shining.previousSlide() });
        $('#controls #next').     click(function() { $.shining.nextSlide() });
        $('#controls #last').     click(function() { $.shining.lastSlide() });
        $('#stage').centralize();
      });
      $(window).resize(function() { $('#stage').centralize() });
      $(document).click(function(event) {
        if ($(event.target).is('a')) return false;
        if (event.pageX < ($(window).width() / 2)) {
          $.shining.previousSlide();
        } else {
          $.shining.nextSlide();
        }
      })
      loadConfig(function() {
        getSlide($.shining.slides.current);
        setTitle($.shining.config.title);
        setTheme($.shining.config.theme);
        parseEffects();
      });
    }

    function getSlide(name) {
      if (!name) return false;
      if ($.shining.config.transitions) {
        $('#stage').removeClass('fades-in');
        setTimeout(
          function() {
            loadSlide(name);
            setTimeout(
              function() {
                $('#stage').addClass('fades-in');
                $.shining.scripts.run($.shining.currentScript);
              },
            200);
          }, 200);
      } else {
        loadSlide(name);
      }
    }

    function setTitle(title) {
      if (!title) { return false };
      $('title').text(title);
    }

    function setTheme(name) {
      if (!name || name == "default") { return false };
      var path = $('link.theme').attr('href').replace('default.css', name + 'css');
      return $('link.theme').attr('href', path);
    }

    // private
    function slide(name) {
      return 'slides/' + name;
    }

    function vendored() {
      return $('script:first').attr('src').match(/^vendor/);
    }

    function loadSlide(name) {
      $('#stage').load(
        slide(name).markup(),
        function(data) {
          $.shining.slides.current = name;
          $('link.slide').remove(); // remove now previous slide styles
          if (SyntaxHighlighter) SyntaxHighlighter.highlight();
          $('#stage').centralize();
          $.shining.scripts.reap();
          if (data) {
            loadSlideScript(name);
            loadSlideStyle(name);
          }
        }
      );
    }

    function loadSlideScript(name) {
      $.get(slide(name).script(), function(script) {
        if ($.shining.config.transitions) {
          $.shining.currentScript = script;
        } else {
          $.shining.scripts.run(script)
        }
      })
    }

    function loadSlideStyle(name) {
      $('head').append('<link rel="stylesheet" type="text/css" href="' + slide(name).style() + '" media="all" class="slide"/>')
    }

    function loadConfig(callback) {
      $.getJSON('config.json', function(config) {
        $.shining.config = config;
        $.shining.slides.add(config.slides);
        if (config.transitions) { $('#stage').addClass('transparent fades-in'); }
        callback.call();
      });
    }

    function parseEffects() {
      $.get($('link[href$=effects.css]').attr('href'),
        function(css) { $.shining.effects = $.parseCSS(css) }
      );
    }

    $.shining.scripts = {
      LINE: /^(\d[.\d]*),[\s]*(.*)/,
      parsed: [], processes: [],
      nextSlide:      function() { $.shining.nextSlide() },
      previousSlide:  function() { $.shining.previousSlide() },
      at:             function(seconds, method) {
        $.shining.scripts.processes.push(setTimeout(method, parseFloat(seconds) * 1000))
      },
      parse:          function(script) {
        var lines = script.split("\n"), tokens, parsed = [];
        for (var i = 0; lines.length > i; i++) {
          if ($.shining.scripts.LINE.test(lines[i])) {
            var tokens = lines[i].match($.shining.scripts.LINE);
            var time = tokens[1], code = tokens[2];
            parsed.push(time);
            if (code.length) parsed.push(code);
          } else {
            if (isNaN(parsed[parsed.length - 1])) {
              parsed[parsed.length - 1] += ("; " + lines[i]);
            } else {
              parsed.push(lines[i]);
            }
          }
        }
        return parsed;
      },
      run:          function(script) {
        var parsed = $.shining.scripts.parse(script), all = [];
        for (var i = 0; parsed.length > i; i += 2) {
          all.push(["at(", parsed[i], ", function() { ", parsed[i+1], " })"].join(''));
        }
        with($.shining.scripts) { eval(all.join(';')) };
      },
      reap: function() {
        $($.shining.scripts.processes).map(function() { clearTimeout(this) });
        return $.shining.scripts.processes = [];
      }
    }

    init();
  }
  // boots!
  $.shining();

})(jQuery);

// Dependencies!!

/*
 * JSizes - JQuery plugin v0.33
 *
 * Licensed under the revised BSD License.
 * Copyright 2008-2010 Bram Stein
 * All rights reserved.
 */
(function(b){var a=function(c){return parseInt(c,10)||0};b.each(["min","max"],function(d,c){b.fn[c+"Size"]=function(g){var f,e;if(g){if(g.width!==undefined){this.css(c+"-width",g.width)}if(g.height!==undefined){this.css(c+"-height",g.height)}return this}else{f=this.css(c+"-width");e=this.css(c+"-height");return{width:(c==="max"&&(f===undefined||f==="none"||a(f)===-1)&&Number.MAX_VALUE)||a(f),height:(c==="max"&&(e===undefined||e==="none"||a(e)===-1)&&Number.MAX_VALUE)||a(e)}}}});b.fn.isVisible=function(){return this.is(":visible")};b.each(["border","margin","padding"],function(d,c){b.fn[c]=function(e){if(e){if(e.top!==undefined){this.css(c+"-top"+(c==="border"?"-width":""),e.top)}if(e.bottom!==undefined){this.css(c+"-bottom"+(c==="border"?"-width":""),e.bottom)}if(e.left!==undefined){this.css(c+"-left"+(c==="border"?"-width":""),e.left)}if(e.right!==undefined){this.css(c+"-right"+(c==="border"?"-width":""),e.right)}return this}else{return{top:a(this.css(c+"-top"+(c==="border"?"-width":""))),bottom:a(this.css(c+"-bottom"+(c==="border"?"-width":""))),left:a(this.css(c+"-left"+(c==="border"?"-width":""))),right:a(this.css(c+"-right"+(c==="border"?"-width":"")))}}}})})(jQuery);

// http://github.com/juliocesar/jquery-ondistance
(function($){$.fn.ondistance=function(specified,close,far){var elt=this.get(0),last=new Date().getTime();$(document).mousemove(function(e){var current=new Date().getTime();if(current-last<500)return;var offset=$(elt).offset(),center={x:offset.left+($(elt).width()/2),y:offset.top+($(elt).height()/2)},last=current,distance=parseInt(Math.sqrt(Math.pow(e.pageX-center.x,2)+Math.pow(e.pageY-center.y,2)));if(specified>=distance){if($(elt).data('mouseclose')==true)return false;$(elt).data('mouseclose',true);close(elt);}else{if($(elt).data('mouseclose')==false)return false;$(elt).data('mouseclose',false);far(elt);}})}})(jQuery);

// centralizes an element vertically
(function($){$.fn.centralize=function(){var self=this.get(0);windowHeight=document.documentElement.clientHeight,elementHeight=(self.offsetHeight+$(self).padding().top+$(self).padding().bottom);$(self).css('position','relative').css('top',(windowHeight/2)-(elementHeight/2)+'px');};})(jQuery);

// Trimmed down/modified version of the original Javascript/jQuery CSS parser
// by Danny.
// http://bililite.com/blog/2009/01/16/jquery-css-parser/
(function($){$.parseCSS=function(str){var ret={};str=munge(str).replace(/@(([^;`]|`[^b]|`b[^%])*(`b%)?);?/g,function(s,rule){return'';});$.each(str.split('`b%'),function(i,css){css=css.split('%b`');if(css.length<2)return;css[0]=restore(css[0]);ret[css[0]]=$.extend(ret[css[0]]||{},parsedeclarations(css[1]));});return ret;};$.parseCSS.mediumApplies=(window.media&&window.media.query)||function(str){if(!str)return true;if(str in media)return media[str];var style=$('<style media="'+str+'">body {position: relative; z-index: 1;}</style>').appendTo('head');return media[str]=[$('body').css('z-index')==1,style.remove()][0];};$.parseCSS.parseArguments=function(str){if(!str)return[];var ret=[],mungedArguments=munge(str,true).split(/\s+/);for(var i=0;i<mungedArguments.length;++i){var a=restore(mungedArguments[i]);try{ret.push(eval('('+a+')'));}catch(err){ret.push(a);}}
return ret;};var media={};var munged={};function parsedeclarations(index){var str=munged[index].replace(/^{|}$/g,'');str=munge(str);var parsed={};$.each(str.split(';'),function(i,decl){decl=decl.split(':');if(decl.length<2)return;parsed[restore(decl[0])]=restore(decl[1]);});return parsed;}
var REbraces=/{[^{}]*}/,REfull=/\[[^\[\]]*\]|{[^{}]*}|\([^()]*\)|function(\s+\w+)?(\s*%b`\d+`b%){2}/,REatcomment=/\/\*@((?:[^\*]|\*[^\/])*)\*\//g,REcomment_string=/(?:\/\*(?:[^\*]|\*[^\/])*\*\/)|(\\.|"(?:[^\\\"]|\\.|\\\n)*"|'(?:[^\\\']|\\.|\\\n)*')/g,REmunged=/%\w`(\d+)`\w%/,uid=0;function munge(str,full){str=str.replace(REatcomment,'$1').replace(REcomment_string,function(s,string){if(!string)return'';var replacement='%s`'+(++uid)+'`s%';munged[uid]=string.replace(/^\\/,'');return replacement;});var RE=full?REfull:REbraces;while(match=RE.exec(str)){replacement='%b`'+(++uid)+'`b%';munged[uid]=match[0];str=str.replace(RE,replacement);}
return str;}
function restore(str){if(str===undefined)return str;while(match=REmunged.exec(str)){str=str.replace(REmunged,munged[match[1]]);}
return $.trim(str);}
var RESGMLcomment=/<!--([^-]|-[^-])*-->/g;var REnotATag=/(>)[^<]*/g;var REtag=/<(\w+)([^>]*)>/g;})(jQuery);<commit_msg>nice, bookmarks<commit_after>(function($) {

  $.shining = function() {
    $.shining.slides = {
      get length()      { return this._slides.length },
      get current()     { return (typeof this._current == 'undefined' ? this._slides[0] : this._slides[this._current]) },
      set current(_new) { this._current = this._slides.indexOf(_new); return this.current },
      get all()         { return this._slides },
      get first()       { return this._slides[0] },
      get last()        { return this._slides[ this._slides.length - 1 ] },
      get next()        { return this._slides[ this._slides.indexOf(this.current) + 1 ] },
      get previous()    { return this._slides[ this._slides.indexOf(this.current) - 1 ] },
      add: function(slides) { return Array.prototype.push.apply(this._slides, slides) },
      _slides: [],
      _current: 0
    };

    String.prototype.markup = function() { return this + '.html' };
    String.prototype.script = function() { return this + '.js' };
    String.prototype.style =  function() { return this + '.css' };

    $.extend($.shining, {
      firstSlide:     function() { getSlide($.shining.slides.first) },
      lastSlide:      function() { getSlide($.shining.slides.last ) },
      nextSlide:      function() { getSlide($.shining.slides.next) },
      previousSlide:  function() { getSlide($.shining.slides.previous) },
      getSlide:       function(slide) { getSlide(slide) }
    });

    function init()         {
      $(document).ready(function() {
        $('#controls').ondistance(
          300,
          function(controls) { $(controls).addClass('fades-in') },
          function(controls) { $(controls).removeClass('fades-in') }
        );
        $('#stage').centralize();
      });
      $(window).resize(function() { $('#stage').centralize() });
      loadConfig(function() {
        var startAt = document.location.hash.replace('#', '');
        if (startAt) {
          getSlide(startAt)
        } else {
          getSlide($.shining.slides.current);
        }
        setTitle($.shining.config.title);
        setTheme($.shining.config.theme);
        parseEffects();
        updateControlAnchors();
      });
    }

    function getSlide(name) {
      if (!name) return false;
      if ($.shining.config.transitions) {
        $('#stage').removeClass('fades-in');
        setTimeout(
          function() {
            loadSlide(name);
            setTimeout(
              function() {
                $('#stage').addClass('fades-in');
                $.shining.scripts.run($.shining.currentScript);
              },
            200);
          }, 200);
      } else {
        loadSlide(name);
      }
    }

    function setTitle(title) {
      if (!title) { return false };
      $('title').text(title);
    }

    function setTheme(name) {
      if (!name || name == "default") { return false };
      var path = $('link.theme').attr('href').replace('default.css', name + 'css');
      return $('link.theme').attr('href', path);
    }

    // private
    function slide(name) {
      return 'slides/' + name;
    }

    function vendored() {
      return $('script:first').attr('src').match(/^vendor/);
    }

    function loadSlide(name) {
      $('#stage').load(
        slide(name).markup(),
        function(data) {
          $.shining.slides.current = name;
          $('link.slide').remove(); // remove now previous slide styles
          if (SyntaxHighlighter) SyntaxHighlighter.highlight();
          $('#stage').centralize();
          $.shining.scripts.reap();
          updateControlAnchors();
          if (data) {
            loadSlideScript(name);
            loadSlideStyle(name);
          }
        }
      );
    }

    function loadSlideScript(name) {
      $.get(slide(name).script(), function(script) {
        if ($.shining.config.transitions) {
          $.shining.currentScript = script;
        } else {
          $.shining.scripts.run(script)
        }
      })
    }

    function loadSlideStyle(name) {
      $('head').append('<link rel="stylesheet" type="text/css" href="' + slide(name).style() + '" media="all" class="slide"/>')
    }

    function loadConfig(callback) {
      $.getJSON('config.json', function(config) {
        $.shining.config = config;
        $.shining.slides.add(config.slides);
        if (config.transitions) { $('#stage').addClass('transparent fades-in'); }
        callback.call();
      });
    }

    function parseEffects() {
      $.get($('link[href$=effects.css]').attr('href'),
        function(css) { $.shining.effects = $.parseCSS(css) }
      );
    }

    function updateControlAnchors() {
      $('#controls #first').    attr('href', '#' + $.shining.slides.first);
      $('#controls #previous'). attr('href', ($.shining.slides.previous ? '#' + $.shining.slides.previous : ''));
      $('#controls #next').     attr('href', ($.shining.slides.next ? '#' + $.shining.slides.next : ''));
      $('#controls #last').     attr('href', '#' + $.shining.slides.first);
    }

    $.shining.scripts = {
      LINE: /^(\d[.\d]*),[\s]*(.*)/,
      parsed: [], processes: [],
      nextSlide:      function() { $.shining.nextSlide() },
      previousSlide:  function() { $.shining.previousSlide() },
      at:             function(seconds, method) {
        $.shining.scripts.processes.push(setTimeout(method, parseFloat(seconds) * 1000))
      },
      parse:          function(script) {
        var lines = script.split("\n"), tokens, parsed = [];
        for (var i = 0; lines.length > i; i++) {
          if ($.shining.scripts.LINE.test(lines[i])) {
            var tokens = lines[i].match($.shining.scripts.LINE);
            var time = tokens[1], code = tokens[2];
            parsed.push(time);
            if (code.length) parsed.push(code);
          } else {
            if (isNaN(parsed[parsed.length - 1])) {
              parsed[parsed.length - 1] += ("; " + lines[i]);
            } else {
              parsed.push(lines[i]);
            }
          }
        }
        return parsed;
      },
      run:          function(script) {
        var parsed = $.shining.scripts.parse(script), all = [];
        for (var i = 0; parsed.length > i; i += 2) {
          all.push(["at(", parsed[i], ", function() { ", parsed[i+1], " })"].join(''));
        }
        with($.shining.scripts) { eval(all.join(';')) };
      },
      reap: function() {
        $($.shining.scripts.processes).map(function() { clearTimeout(this) });
        return $.shining.scripts.processes = [];
      }
    }

    init();
  }
  // boots!
  $.shining();

})(jQuery);

// Dependencies!!

/*
 * JSizes - JQuery plugin v0.33
 *
 * Licensed under the revised BSD License.
 * Copyright 2008-2010 Bram Stein
 * All rights reserved.
 */
(function(b){var a=function(c){return parseInt(c,10)||0};b.each(["min","max"],function(d,c){b.fn[c+"Size"]=function(g){var f,e;if(g){if(g.width!==undefined){this.css(c+"-width",g.width)}if(g.height!==undefined){this.css(c+"-height",g.height)}return this}else{f=this.css(c+"-width");e=this.css(c+"-height");return{width:(c==="max"&&(f===undefined||f==="none"||a(f)===-1)&&Number.MAX_VALUE)||a(f),height:(c==="max"&&(e===undefined||e==="none"||a(e)===-1)&&Number.MAX_VALUE)||a(e)}}}});b.fn.isVisible=function(){return this.is(":visible")};b.each(["border","margin","padding"],function(d,c){b.fn[c]=function(e){if(e){if(e.top!==undefined){this.css(c+"-top"+(c==="border"?"-width":""),e.top)}if(e.bottom!==undefined){this.css(c+"-bottom"+(c==="border"?"-width":""),e.bottom)}if(e.left!==undefined){this.css(c+"-left"+(c==="border"?"-width":""),e.left)}if(e.right!==undefined){this.css(c+"-right"+(c==="border"?"-width":""),e.right)}return this}else{return{top:a(this.css(c+"-top"+(c==="border"?"-width":""))),bottom:a(this.css(c+"-bottom"+(c==="border"?"-width":""))),left:a(this.css(c+"-left"+(c==="border"?"-width":""))),right:a(this.css(c+"-right"+(c==="border"?"-width":"")))}}}})})(jQuery);

// http://github.com/juliocesar/jquery-ondistance
(function($){$.fn.ondistance=function(specified,close,far){var elt=this.get(0),last=new Date().getTime();$(document).mousemove(function(e){var current=new Date().getTime();if(current-last<500)return;var offset=$(elt).offset(),center={x:offset.left+($(elt).width()/2),y:offset.top+($(elt).height()/2)},last=current,distance=parseInt(Math.sqrt(Math.pow(e.pageX-center.x,2)+Math.pow(e.pageY-center.y,2)));if(specified>=distance){if($(elt).data('mouseclose')==true)return false;$(elt).data('mouseclose',true);close(elt);}else{if($(elt).data('mouseclose')==false)return false;$(elt).data('mouseclose',false);far(elt);}})}})(jQuery);

// centralizes an element vertically
(function($){$.fn.centralize=function(){var self=this.get(0);windowHeight=document.documentElement.clientHeight,elementHeight=(self.offsetHeight+$(self).padding().top+$(self).padding().bottom);$(self).css('position','relative').css('top',(windowHeight/2)-(elementHeight/2)+'px');};})(jQuery);

// Trimmed down/modified version of the original Javascript/jQuery CSS parser
// by Danny.
// http://bililite.com/blog/2009/01/16/jquery-css-parser/
(function($){$.parseCSS=function(str){var ret={};str=munge(str).replace(/@(([^;`]|`[^b]|`b[^%])*(`b%)?);?/g,function(s,rule){return'';});$.each(str.split('`b%'),function(i,css){css=css.split('%b`');if(css.length<2)return;css[0]=restore(css[0]);ret[css[0]]=$.extend(ret[css[0]]||{},parsedeclarations(css[1]));});return ret;};$.parseCSS.mediumApplies=(window.media&&window.media.query)||function(str){if(!str)return true;if(str in media)return media[str];var style=$('<style media="'+str+'">body {position: relative; z-index: 1;}</style>').appendTo('head');return media[str]=[$('body').css('z-index')==1,style.remove()][0];};$.parseCSS.parseArguments=function(str){if(!str)return[];var ret=[],mungedArguments=munge(str,true).split(/\s+/);for(var i=0;i<mungedArguments.length;++i){var a=restore(mungedArguments[i]);try{ret.push(eval('('+a+')'));}catch(err){ret.push(a);}}
return ret;};var media={};var munged={};function parsedeclarations(index){var str=munged[index].replace(/^{|}$/g,'');str=munge(str);var parsed={};$.each(str.split(';'),function(i,decl){decl=decl.split(':');if(decl.length<2)return;parsed[restore(decl[0])]=restore(decl[1]);});return parsed;}
var REbraces=/{[^{}]*}/,REfull=/\[[^\[\]]*\]|{[^{}]*}|\([^()]*\)|function(\s+\w+)?(\s*%b`\d+`b%){2}/,REatcomment=/\/\*@((?:[^\*]|\*[^\/])*)\*\//g,REcomment_string=/(?:\/\*(?:[^\*]|\*[^\/])*\*\/)|(\\.|"(?:[^\\\"]|\\.|\\\n)*"|'(?:[^\\\']|\\.|\\\n)*')/g,REmunged=/%\w`(\d+)`\w%/,uid=0;function munge(str,full){str=str.replace(REatcomment,'$1').replace(REcomment_string,function(s,string){if(!string)return'';var replacement='%s`'+(++uid)+'`s%';munged[uid]=string.replace(/^\\/,'');return replacement;});var RE=full?REfull:REbraces;while(match=RE.exec(str)){replacement='%b`'+(++uid)+'`b%';munged[uid]=match[0];str=str.replace(RE,replacement);}
return str;}
function restore(str){if(str===undefined)return str;while(match=REmunged.exec(str)){str=str.replace(REmunged,munged[match[1]]);}
return $.trim(str);}
var RESGMLcomment=/<!--([^-]|-[^-])*-->/g;var REnotATag=/(>)[^<]*/g;var REtag=/<(\w+)([^>]*)>/g;})(jQuery);

/*
 * jQuery hashchange event - v1.2 - 2/11/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,i,b){var j,k=$.event.special,c="location",d="hashchange",l="href",f=$.browser,g=document.documentMode,h=f.msie&&(g===b||g<8),e="on"+d in i&&!h;function a(m){m=m||i[c][l];return m.replace(/^[^#]*#?(.*)$/,"$1")}$[d+"Delay"]=100;k[d]=$.extend(k[d],{setup:function(){if(e){return false}$(j.start)},teardown:function(){if(e){return false}$(j.stop)}});j=(function(){var m={},r,n,o,q;function p(){o=q=function(s){return s};if(h){n=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this);

$(window).bind('hashchange', function(event) {
  var slide = document.location.hash.replace('#', '');
  if (slide) { $.shining.getSlide(slide) };
});<|endoftext|>


<commit_before>/*
 * Namespace: lb.base.template.i18n
 * Base Module for Internationalization Templates (i18n)
 *
 * This module defines filter functions for templates used in i18n
 * (internationalization), used together with HTML filters in calls to
 * <lb.base.template.applyFilters(input...,filters):any> in the base template
 * module.
 *
 * Like HTML filters, i18n filters are applied to DOM nodes, modified in place.
 *
 * Author:
 * Eric Bréchemier <legalbox@eric.brechemier.name>
 *
 * Copyright:
 * Legal-Box SAS (c) 2010-2011, All Rights Reserved
 *
 * License:
 * BSD License
 * http://creativecommons.org/licenses/BSD/
 *
 * Version:
 * 2011-01-11
 */
/*requires lb.base.template.js */
/*jslint white:false, plusplus:false */
/*global lb */
// preserve the module, if already loaded
lb.base.template.i18n = lb.base.template.i18n || (function() {
  // Builder of
  // Closure for lb.base.template.i18n module

  // Declare aliases
      /*requires lb.base.dom.js */
  var dom = lb.base.dom,
      ELEMENT_NODE = dom.ELEMENT_NODE,
      hasAttribute = dom.hasAttribute,
      /*requires lb.base.i18n.js */
      i18n = lb.base.i18n,
      /*requires lb.base.i18n.data.js */
      getDefaultLanguageCode = i18n.data.getDefaultLanguageCode,
      /*requires lb.base.template.js */
      template = lb.base.template,
      applyFilters = template.applyFilters,
      /*requires lb.base.template.html.js */
      topDownParsing = template.html.topDownParsing,
      replaceParams = template.html.replaceParams;

  function filterByLanguage(languageCode){
    // Function: filterByLanguage(languageCode): function
    // Return a filter function that removes HTML elements that do not match
    // the given language code.
    //
    // The signature of filter functions is filter(htmlElement).
    // In filter functions, the 'lang' attribute of HTML elements is compared
    // to the given language code. If the 'lang' is not an hyphenated substring
    // of the given language code (case-insensitive), the element is removed
    // from its parent. Nothing happens in case the element has no parent.
    //
    // No processing is done in filter functions to discover or set the
    // language of elements without a 'lang' attribute. These filters should be
    // used in conjunction with <setLanguage(htmlElement)>, which is intended
    // for this purpose.
    //
    // Parameter:
    //   languageCode - string, the language code identifying the language,
    //                  as defined in RFC5646 "Tags for Identifying Languages"
    //
    // Returns:
    //   function, a filter function for the given language code,
    //   or null if the language code was missing or not a string.
    if ( typeof languageCode !== 'string' ){
      return null;
    }
    return function(htmlElement){
      // anonymous(htmlElement)
      // Closure generated by filterByLanguage(languageCode).
      // Remove the HTML element from the tree if it does not match the language
      // in the context of this closure.
      //
      // Closure Context:
      //   languageCode - string, the language code identifying the language
      //                  used for filtering, as defined in RFC5646 "Tags for
      //                  Identifying Languages"
      //
      // Parameter:
      //   htmlElement - DOM Element, the DOM Element to check.
      //                 Other types of DOM nodes and other values are ignored.
      if ( !htmlElement ||
           htmlElement.nodeType !== ELEMENT_NODE ||
           !htmlElement.parentNode ){
        return;
      }
      if ( !i18n.contains(languageCode,htmlElement.lang) ){
        htmlElement.parentNode.removeChild(htmlElement);
      }
    };
  }

  function setLanguage(htmlElement){
    // Function: setLanguage(htmlElement)
    // Compute and set the language of given HTML element.
    //
    // This filter sets the 'lang' attribute of HTML elements explicitly.
    // When a 'lang' attribute is already specified, it is preserved. When it
    // is missing, the language inherited from ancestors is computed and set
    // to the 'lang' property/attribute.
    //
    // Parameter:
    //   htmlElement - DOM Element, a DOM element with or without parent.
    //                 Other types of DOM nodes and other values are ignored.
    //
    // Note:
    // In current implementation, only the 'lang' attribute is set, not the
    // 'xml:lang' attribute. This may be added in a future implementation.
    if ( !htmlElement ||
         htmlElement.nodeType !== ELEMENT_NODE ){
      return;
    }
    if ( !hasAttribute(htmlElement,'lang') ){
      // Compute and set the language explicitly
      i18n.setLanguage(i18n.getLanguage(htmlElement), htmlElement);
    }
  }

  function filterHtml(htmlNode,data,languageCode){
    // Function: filterHtml(htmlNode[,data[,languageCode]])
    // Replace parameters and trim nodes based on html 'lang' attribute.
    //
    // This is a higher level filter, that applies a predefined selection of
    // filters to the given HTML node:
    //   * topDownParsing (from base HTML templates)
    //   * filterByLanguage
    //   * setLanguage
    //   * replaceParams (from base HTML templates)
    //
    // The given HTML node is modified in place. You should clone it beforehand
    // if you wish to preserve the original version.
    //
    // The HTML node is filtered according to the languageCode argument, or
    // if it is omitted, the language code of the application as returned by
    // getSelectedLanguage(). Multiple translations may be included
    // and only relevant translations will be kept, based on 'lang' attribute:
    // |

    // |   Hallo #user.firstName#!
    // |   Hi #user.firstName#!
    // |   Salut #user.firstName# !
    // |   こんにちは#user.lastName#!
    // |

    //
    // Filtering the HTML from the above example for the
    // language 'en-GB' would result in:
    // |

    // |   Hi #user.firstName#!
    // |

    //
    // The 'lang' attribute is inherited from ancestors, including ancestors
    // of the given HTML node, unless it has a 'lang' attribute itself. The
    // root element of the HTML node will be removed from its parent as well
    // if its language does not match the language code used for filtering.
    // Elements within the scope of the empty language '' or in the scope of
    // no language attribute are preserved by the filtering.
    //
    // Parameters of the form #param# found in text and attribute nodes are
    // replaced in the same way as using lb.base.i18n.data.getString():
    // - the parameter format is based on following regular expression:
    //   /#([a-zA-Z0-9_\-\.]+)#/g
    // - data object contains values for the parameters to replace, which may
    //   be nested:
    //   | {
    //   |   user: {
    //   |     firstName: 'Jane',
    //   |     lastName: 'Doe'
    //   |   }
    //   | }
    // - when no property is found in data for the replacement of a parameter,
    //   a lookup is performed in language properties instead
    //
    // After parameter replacement, the HTML node of the above example would
    // end up as:
    // |

    // |   Hi Jane!
    // |

    //
    // Parameters:
    //   htmlNode - DOM node, the node to apply the i18n filters to.
    //   data - object, optional, replacement values for parameters found in
    //          attributes and text of the HTML node. Defaults to an empty
    //          object.
    //   languageCode - string, optional, language code for lookup in a
    //                  specific language. Defaults to the value of
    //                  lb.base.i18n.data.getDefaultLanguageCode().
    //
    // Reference:
    //   Specifying the language of content: the lang attribute
    //   o http://www.w3.org/TR/html401/struct/dirlang.html#h-8.1
    data = data || {};
    if (typeof languageCode !== 'string'){
      languageCode = getDefaultLanguageCode();
    }
    applyFilters(
      htmlNode,
      data,
      [
        topDownParsing,
        filterByLanguage(languageCode),
        setLanguage,
        replaceParams
      ]
    );
  }

  return { // public API
    filterByLanguage: filterByLanguage,
    setLanguage: setLanguage,
    filterHtml: filterHtml
  };
}());
<commit_msg>Updated usage of replaceParams() in base i18n templates<commit_after>/*
 * Namespace: lb.base.template.i18n
 * Base Module for Internationalization Templates (i18n)
 *
 * This module defines filter functions for templates used in i18n
 * (internationalization), used together with HTML filters in calls to
 * <lb.base.template.applyFilters(input...,filters):any> in the base template
 * module.
 *
 * Like HTML filters, i18n filters are applied to DOM nodes, modified in place.
 *
 * Author:
 * Eric Bréchemier <legalbox@eric.brechemier.name>
 *
 * Copyright:
 * Legal-Box SAS (c) 2010-2011, All Rights Reserved
 *
 * License:
 * BSD License
 * http://creativecommons.org/licenses/BSD/
 *
 * Version:
 * 2011-01-12
 */
/*requires lb.base.template.js */
/*jslint white:false, plusplus:false */
/*global lb */
// preserve the module, if already loaded
lb.base.template.i18n = lb.base.template.i18n || (function() {
  // Builder of
  // Closure for lb.base.template.i18n module

  // Declare aliases
      /*requires lb.base.dom.js */
  var dom = lb.base.dom,
      ELEMENT_NODE = dom.ELEMENT_NODE,
      hasAttribute = dom.hasAttribute,
      /*requires lb.base.i18n.js */
      i18n = lb.base.i18n,
      /*requires lb.base.i18n.data.js */
      getDefaultLanguageCode = i18n.data.getDefaultLanguageCode,
      /*requires lb.base.template.js */
      template = lb.base.template,
      applyFilters = template.applyFilters,
      /*requires lb.base.template.string.js */
      withValuesFrom = template.string.withValuesFrom,
      /*requires lb.base.template.html.js */
      topDownParsing = template.html.topDownParsing,
      replaceParams = template.html.replaceParams;

  function filterByLanguage(languageCode){
    // Function: filterByLanguage(languageCode): function
    // Return a filter function that removes HTML elements that do not match
    // the given language code.
    //
    // The signature of filter functions is filter(htmlElement).
    // In filter functions, the 'lang' attribute of HTML elements is compared
    // to the given language code. If the 'lang' is not an hyphenated substring
    // of the given language code (case-insensitive), the element is removed
    // from its parent. Nothing happens in case the element has no parent.
    //
    // No processing is done in filter functions to discover or set the
    // language of elements without a 'lang' attribute. These filters should be
    // used in conjunction with <setLanguage(htmlElement)>, which is intended
    // for this purpose.
    //
    // Parameter:
    //   languageCode - string, the language code identifying the language,
    //                  as defined in RFC5646 "Tags for Identifying Languages"
    //
    // Returns:
    //   function, a filter function for the given language code,
    //   or null if the language code was missing or not a string.
    if ( typeof languageCode !== 'string' ){
      return null;
    }
    return function(htmlElement){
      // anonymous(htmlElement)
      // Closure generated by filterByLanguage(languageCode).
      // Remove the HTML element from the tree if it does not match the language
      // in the context of this closure.
      //
      // Closure Context:
      //   languageCode - string, the language code identifying the language
      //                  used for filtering, as defined in RFC5646 "Tags for
      //                  Identifying Languages"
      //
      // Parameter:
      //   htmlElement - DOM Element, the DOM Element to check.
      //                 Other types of DOM nodes and other values are ignored.
      if ( !htmlElement ||
           htmlElement.nodeType !== ELEMENT_NODE ||
           !htmlElement.parentNode ){
        return;
      }
      if ( !i18n.contains(languageCode,htmlElement.lang) ){
        htmlElement.parentNode.removeChild(htmlElement);
      }
    };
  }

  function setLanguage(htmlElement){
    // Function: setLanguage(htmlElement)
    // Compute and set the language of given HTML element.
    //
    // This filter sets the 'lang' attribute of HTML elements explicitly.
    // When a 'lang' attribute is already specified, it is preserved. When it
    // is missing, the language inherited from ancestors is computed and set
    // to the 'lang' property/attribute.
    //
    // Parameter:
    //   htmlElement - DOM Element, a DOM element with or without parent.
    //                 Other types of DOM nodes and other values are ignored.
    //
    // Note:
    // In current implementation, only the 'lang' attribute is set, not the
    // 'xml:lang' attribute. This may be added in a future implementation.
    if ( !htmlElement ||
         htmlElement.nodeType !== ELEMENT_NODE ){
      return;
    }
    if ( !hasAttribute(htmlElement,'lang') ){
      // Compute and set the language explicitly
      i18n.setLanguage(i18n.getLanguage(htmlElement), htmlElement);
    }
  }

  function filterHtml(htmlNode,data,languageCode){
    // Function: filterHtml(htmlNode[,data[,languageCode]])
    // Replace parameters and trim nodes based on html 'lang' attribute.
    //
    // This is a higher level filter, that applies a predefined selection of
    // filters to the given HTML node:
    //   * topDownParsing (from base HTML templates)
    //   * filterByLanguage
    //   * setLanguage
    //   * replaceParams (from base HTML templates)
    //
    // The given HTML node is modified in place. You should clone it beforehand
    // if you wish to preserve the original version.
    //
    // The HTML node is filtered according to the languageCode argument, or
    // if it is omitted, the language code of the application as returned by
    // getSelectedLanguage(). Multiple translations may be included
    // and only relevant translations will be kept, based on 'lang' attribute:
    // |

    // |   Hallo #user.firstName#!
    // |   Hi #user.firstName#!
    // |   Salut #user.firstName# !
    // |   こんにちは#user.lastName#!
    // |

    //
    // Filtering the HTML from the above example for the
    // language 'en-GB' would result in:
    // |

    // |   Hi #user.firstName#!
    // |

    //
    // The 'lang' attribute is inherited from ancestors, including ancestors
    // of the given HTML node, unless it has a 'lang' attribute itself. The
    // root element of the HTML node will be removed from its parent as well
    // if its language does not match the language code used for filtering.
    // Elements within the scope of the empty language '' or in the scope of
    // no language attribute are preserved by the filtering.
    //
    // Parameters of the form #param# found in text and attribute nodes are
    // replaced in the same way as using lb.base.i18n.data.getString():
    // - the parameter format is based on following regular expression:
    //   /#([a-zA-Z0-9_\-\.]+)#/g
    // - data object contains values for the parameters to replace, which may
    //   be nested:
    //   | {
    //   |   user: {
    //   |     firstName: 'Jane',
    //   |     lastName: 'Doe'
    //   |   }
    //   | }
    // - when no property is found in data for the replacement of a parameter,
    //   a lookup is performed in language properties instead
    //
    // After parameter replacement, the HTML node of the above example would
    // end up as:
    // |

    // |   Hi Jane!
    // |

    //
    // Parameters:
    //   htmlNode - DOM node, the node to apply the i18n filters to.
    //   data - object, optional, replacement values for parameters found in
    //          attributes and text of the HTML node. Defaults to an empty
    //          object.
    //   languageCode - string, optional, language code for lookup in a
    //                  specific language. Defaults to the value of
    //                  lb.base.i18n.data.getDefaultLanguageCode().
    //
    // Reference:
    //   Specifying the language of content: the lang attribute
    //   o http://www.w3.org/TR/html401/struct/dirlang.html#h-8.1
    data = data || {};
    if (typeof languageCode !== 'string'){
      languageCode = getDefaultLanguageCode();
    }
    applyFilters(
      htmlNode,
      [
        topDownParsing,
        filterByLanguage(languageCode),
        setLanguage,
        replaceParams( withValuesFrom(data) )
      ]
    );
  }

  return { // public API
    filterByLanguage: filterByLanguage,
    setLanguage: setLanguage,
    filterHtml: filterHtml
  };
}());
<|endoftext|>


<commit_before>/**
 给定月份和年，求出当月有多少天
 */

function isLeap(year) {
    if (((year % 4 == 0) && !(year % 100 == 0))
        || (year % 400 == 0)) return true;
    else return false;
}

function daysOfMonth(month, year) {
    var numDays;
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            numDays = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            numDays = 30;
            break;
        case 2:
            numDays = isLeap(year) ? 29 : 28;
            break;
        default:
            console.log("非法月份");
            break;
    }
    console.log(year + "年" + month + "月" + "有 " + numDays + "天")
    return numDays;
}
daysOfMonth(10, 2016);
daysOfMonth(2, 2016);
daysOfMonth(2, 2015);
daysOfMonth(3, 2014);
daysOfMonth(2, 2100);<commit_msg>refactor day_of_month<commit_after>/**
 给定月份和年，求出当月有多少天
 i.e 2014年8月=31天，2015年2月=28天，2016年2月=29天，2016年11月=30天，2100年2月=28天等
 */

function isLeap(year) {
    return (((year % 4 == 0) && !(year % 100 == 0))
    || (year % 400 == 0));
}

function daysOfMonth(month, year) {
    var numDays;
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            numDays = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            numDays = 30;
            break;
        case 2:
            numDays = isLeap(year) ? 29 : 28;
            break;
        default:
            console.log("非法月份");
            break;
    }
    console.log(year + "年" + month + "月" + "有 " + numDays + "天")
    return numDays;
}
daysOfMonth(10, 2016);
daysOfMonth(2, 2016);
daysOfMonth(2, 2015);
daysOfMonth(3, 2014);
daysOfMonth(2, 2100);<|endoftext|>