<commit_before>/*
 * append to your ~/.vimperatorc
 * =====
 * javascript if (typeof hBookmark != 'undefined') liberator.loadScript('chrome://hatenabookmark/content/vimperator/plugin/hatenabookmark.js', {__proto__: this});
 * =====
 */

liberator.plugins.hBookmark = (function() {
    let p = function(msg) {
        Application.console.log('mes: ' + msg);
    }

    styles.registerSheet("chrome://hatenabookmark/skin/vimperator.css");

    let HatenaBookmark = window.hBookmark;

    const DEFAULT_SHORTCUTS = {
        hintsAdd     : 'c',
        hintsComment : 'C',
        add          : ['c'],
        comment      : ['C'],
    };

    const DEFAULT_COMMAND_NAMES = {
        hbsearch             : 'hb[search]',
        hbsearch_tab         : 'hbt[absearch]',
        hbsearch_comment     : 'hbc[omment]',
        hbsearch_comment_tab : 'hbtc[omment]',
        hbsearch_url         : 'hbu[rl]',
        hbsearch_url_tab     : 'hbtu[rl]',
        hbsearch_title       : 'hbti[tle]',
        hbsearch_title_tab   : 'hbtti[tle]',
    };

    let globalS = liberator.globalVariables.hBookmark_shortcuts;

    let shortcuts = {};
    if (globalS) {
        for (let key in DEFAULT_SHORTCUTS) {
            shortcuts[key] = globalS[key] || DEFAULT_SHORTCUTS[key];
        }
    } else {
        shortcuts = DEFAULT_SHORTCUTS;
    }

    let globalC = liberator.globalVariables.hBookmark_commands;

    let commandNames = {};
    if (globalC) {
        for (let key in DEFAULT_COMMAND_NAMES) {
            commandNames[key] = globalC[key] || DEFAULT_COMMAND_NAMES[key];
        }
    } else {
        commandNames = DEFAULT_COMMAND_NAMES;
    }

    let plugin = {};

    if (shortcuts.hintsAdd) {
        hints.addMode(shortcuts.hintsAdd, 'Hatena Bookmark - Add', function(elem) {
            let link = elem.href;
            if (link)
                plugin.showPanel(link);
        });
    }

    if (shortcuts.hintsComment) {
        hints.addMode(shortcuts.hintsComment, 'Hatena Bookmark - Comment', function(elem) {
            let link = elem.href;
            if (link)
                plugin.showComment(link);
        });
    }

    if (shortcuts.comment && shortcuts.comment.length) {
        mappings.addUserMap([modes.NORMAL],
            shortcuts.comment,
            'HatenaBookmark - Comment (toggle)',
            function() {
                plugin.toggleComment();
            }, {
            noremap: true,
            }
        );
    }

    if (shortcuts.add && shortcuts.add.length) {
        mappings.addUserMap([modes.NORMAL],
            shortcuts.add,
            'HatenaBookmark - Add',
            function() {
                plugin.showPanel();
            }, {
            noremap: true,
            }
        );
    }

    this.__defineGetter__('searchLimit', function() liberator.globalVariables.hBookmark_search_limit || 10);

    plugin.search = function(word, limit, asc, offset) {
        if (!limit) limit = searchLimit;
        return HatenaBookmark.model('Bookmark').search(word, limit, asc, offset);
    }

    plugin.searchByTitle = function(word, limit, asc, offset) {
        if (!limit) limit = searchLimit;
        return HatenaBookmark.model('Bookmark').searchByTitle(word, limit, asc, offset);
    }

    plugin.searchByComment = function(word, limit, asc, offset) {
        if (!limit) limit = searchLimit;
        return HatenaBookmark.model('Bookmark').searchByComment(word, limit, asc, offset);
    }

    plugin.searchByUrl = function(word, limit, asc, offset) {
        if (!limit) limit = searchLimit;
        return HatenaBookmark.model('Bookmark').searchByUrl(word, limit, asc, offset);
    }

    let BookmarkAdapter = new Struct('b');
    BookmarkAdapter.prototype.__defineGetter__('title', function() this.b.title);
    BookmarkAdapter.prototype.__defineGetter__('comment', function() this.b.comment);
    BookmarkAdapter.prototype.__defineGetter__('url', function() this.b.url);
    BookmarkAdapter.prototype.__defineGetter__('icon', function() this.b.favicon);
    BookmarkAdapter.prototype.__defineGetter__("extra", function () [
        ["comment", this.comment, "Comment"],
    ].filter(function (item) item[1]));

    plugin.command = {
        execute: function(args, openTag) {
            if (args['-sync']) {
                if (!plugin.user) {
                    liberator.echoerr('You need to login to Hatena first.');
                } else {
                    HatenaBookmark.Sync.sync();
                }
                return;
            }

            if (args['-edit']) {
                plugin.showPanel(args['-edit']);
            } else {
                let url = plugin.command.genURL(args);
                if (openTag) {
                    liberator.open(url, liberator.NEW_TAB);
                } else {
                    liberator.open(url);
                }
            }
        },
        executeTab: function(args) {
            plugin.command.execute(args, true);
        },
        genURL: function(args) {
            let url = (args.string || '').replace(/\s/g, '');
            if (url.length) {
                if (args.bang) {
                    return 'http://b.hatena.ne.jp/entry/' + url.replace('#', '%23');
                } else {
                    return url;
                }
            } else {
                if (args.bang) {
                    return 'http://b.hatena.ne.jp/';
                } else {
                    return 'http://b.hatena.ne.jp/my';
                }
            }
        },
        adapter: BookmarkAdapter,
        templateDescription: function (item, text) {
           return <>
               {
                   !(item.extra && item.extra.length) ? "" :

                       {
                           template.map(item.extra, function (e)
                           <>{e[1]}</>,
                           <> </>/* Non-breaking space */)
                       }

               }
           </>
        },
        templateTitleIcon: function (item, text) {
           var simpleURL = text.replace(/^https?:\/\//, '');
           if (simpleURL.indexOf('/') == simpleURL.length-1)
               simpleURL = simpleURL.replace('/', '');
           return <>{item.icon ?  : <></>}{item.item.title}

           {
                 simpleURL
           }
           </>
        },
        options: {
            completer: null,
            literal: 0,
            argCount: '*',
            bang: true,
        },
        createCompleter: function(titles, searchMethod) {
            return function(context) {
                context.format = {
                    anchored: true,
                    title: titles,
                    keys: { text: "url", description: "url", icon: "icon", extra: "extra"},
                    process: [
                        plugin.command.templateTitleIcon,
                        plugin.command.templateDescription,
                    ],
                }
                let word = context.filter;
                let res = plugin[searchMethod || 'search'](word);
                context.filters = [];
                context.completions = res.map(function(b) new plugin.command.adapter(b));
            }
        }
    };

    plugin.command.options.options = [
        [['-edit', '-e'], commands.OPTION_STRING],
        [['-sync'], commands.OPTION_NOARG],
    ];

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment']);

    plugin.toggleComment = function(url) {
        HatenaBookmark.CommentViewer.toggle(url);
    }

    plugin.showComment = function(url) {
        HatenaBookmark.CommentViewer.show(url);
    }

    plugin.showPanel = function(url, options) {
        if (url) {
            HatenaBookmark.AddPanelManager.showPanel(url, options || {});
        } else if (content.location.href.indexOf('reader.livedoor.com/reader') >= 0) {
              // domain match
              let item = content.window.wrappedJSObject.get_active_item(true);
              if (item) {
                HatenaBookmark.AddPanelManager.showPanel(item.link, {title: item.title});
              }
        } else {
            HatenaBookmark.AddPanelManager.toggle();
        }
    }

    plugin.__defineGetter__('user', function() HatenaBookmark.User.user);

    if (commandNames.hbsearch) commands.addUserCommand(
        [commandNames.hbsearch],
        'Hatena Bookmark Search',
        plugin.command.execute,
        plugin.command.options,
        true
    );

    if (commandNames.hbsearch_tab) commands.addUserCommand(
        [commandNames.hbsearch_tab],
        'Hatena Bookmark Search (open tab)',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment'], 'searchByComment');
    if (commandNames.hbsearch_comment) commands.addUserCommand(
        [commandNames.hbsearch_comment],
        'Hatena Bookmark Comment Search',
        plugin.command.execute,
        plugin.command.options,
        true
    );

    if (commandNames.hbsearch_comment_tab) commands.addUserCommand(
        [commandNames.hbsearch_comment_tab],
        'Hatena Bookmark Comment Search (open tab)',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment'], 'searchByUrl');
    if (commandNames.hbsearch_url) commands.addUserCommand(
        [commandNames.hbsearch_url],
        'Hatena Bookmark Url Search',
        plugin.command.execute,
        plugin.command.options,
        true
    );

    if (commandNames.hbsearch_url_tab) commands.addUserCommand(
        [commandNames.hbsearch_url_tab],
        'Hatena Bookmark Url Search (open tab)',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment'], 'searchByTitle');
    if (commandNames.hbsearch_title) commands.addUserCommand(
        [commandNames.hbsearch_title],
        'Hatena Bookmark Title Search',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    if (commandNames.hbsearch_title_tab) commands.addUserCommand(
        [commandNames.hbsearch_title_tab],
        'Hatena Bookmark Title Search (open tab)',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment']);

    completion.addUrlCompleter("H", "Hatena Bookmarks", plugin.command.createCompleter(['Hatena Bookmark']));
    config.guioptions['H'] = ['HatenaBookmark Toolbar',['hBookmarkToolbar']];
    config.dialogs.push([
        "hatenabookmark", "HatenaBookmark Config",
        function(){ window.openDialog("chrome://hatenabookmark/content/config.xul","", "chrome,titlebar,toolbar,centerscreen,dialog=no"); }
    ]);

    return plugin;
})();

<commit_msg>liberator.globalVariables.hBookmark_bangFunction 追加 bang 挙動の変更が可能に<commit_after>/*
 * append to your ~/.vimperatorc
 * =====
 * javascript if (typeof hBookmark != 'undefined') liberator.loadScript('chrome://hatenabookmark/content/vimperator/plugin/hatenabookmark.js', {__proto__: this});
 * =====
 */

liberator.plugins.hBookmark = (function() {
    let p = function(msg) {
        Application.console.log('mes: ' + msg);
    }

    let plugin = {};

    styles.registerSheet("chrome://hatenabookmark/skin/vimperator.css");

    let HatenaBookmark = window.hBookmark;

    const DEFAULT_SHORTCUTS = {
        hintsAdd     : 'c',
        hintsComment : 'C',
        add          : ['c'],
        comment      : ['C'],
    };

    const DEFAULT_COMMAND_NAMES = {
        hbsearch             : 'hb[search]',
        hbsearch_tab         : 'hbt[absearch]',
        hbsearch_comment     : 'hbc[omment]',
        hbsearch_comment_tab : 'hbtc[omment]',
        hbsearch_url         : 'hbu[rl]',
        hbsearch_url_tab     : 'hbtu[rl]',
        hbsearch_title       : 'hbti[tle]',
        hbsearch_title_tab   : 'hbtti[tle]',
    };

    let globalS = liberator.globalVariables.hBookmark_shortcuts;

    let shortcuts = {};
    if (globalS) {
        for (let key in DEFAULT_SHORTCUTS) {
            shortcuts[key] = globalS[key] || DEFAULT_SHORTCUTS[key];
        }
    } else {
        shortcuts = DEFAULT_SHORTCUTS;
    }

    let globalC = liberator.globalVariables.hBookmark_commands;

    let commandNames = {};
    if (globalC) {
        for (let key in DEFAULT_COMMAND_NAMES) {
            commandNames[key] = globalC[key] || DEFAULT_COMMAND_NAMES[key];
        }
    } else {
        commandNames = DEFAULT_COMMAND_NAMES;
    }

    let bangFunction;
    let bangFunctions =  {
        openNewTab: function(url) {
            let url = plugin.command.genURL(url);
            liberator.open(url, liberator.NEW_TAB);
        },
        entryPage: function() {
            let url = plugin.command.genURL(url, true);
            liberator.open(url, liberator.NEW_TAB);
        }
    }

    let globalBangFunction = liberator.globalVariables.hBookmark_bangFunction;
    if (globalBangFunction) {
        if (typeof globalBangFunction == 'function') {
            bangFunction = globalBangFunction;
        } else {
            bangFunction = bangFunctions[globalBangFunction];
        }
    }

    if (!bangFunction)
        bangFunction = bangFunctions['entryPage'];

    if (shortcuts.hintsAdd) {
        hints.addMode(shortcuts.hintsAdd, 'Hatena Bookmark - Add', function(elem) {
            let link = elem.href;
            if (link)
                plugin.showPanel(link);
        });
    }

    if (shortcuts.hintsComment) {
        hints.addMode(shortcuts.hintsComment, 'Hatena Bookmark - Comment', function(elem) {
            let link = elem.href;
            if (link)
                plugin.showComment(link);
        });
    }

    if (shortcuts.comment && shortcuts.comment.length) {
        mappings.addUserMap([modes.NORMAL],
            shortcuts.comment,
            'HatenaBookmark - Comment (toggle)',
            function() {
                plugin.toggleComment();
            }, {
            noremap: true,
            }
        );
    }

    if (shortcuts.add && shortcuts.add.length) {
        mappings.addUserMap([modes.NORMAL],
            shortcuts.add,
            'HatenaBookmark - Add',
            function() {
                plugin.showPanel();
            }, {
            noremap: true,
            }
        );
    }

    this.__defineGetter__('searchLimit', function() liberator.globalVariables.hBookmark_search_limit || 10);

    plugin.search = function(word, limit, asc, offset) {
        if (!limit) limit = searchLimit;
        return HatenaBookmark.model('Bookmark').search(word, limit, asc, offset);
    }

    plugin.searchByTitle = function(word, limit, asc, offset) {
        if (!limit) limit = searchLimit;
        return HatenaBookmark.model('Bookmark').searchByTitle(word, limit, asc, offset);
    }

    plugin.searchByComment = function(word, limit, asc, offset) {
        if (!limit) limit = searchLimit;
        return HatenaBookmark.model('Bookmark').searchByComment(word, limit, asc, offset);
    }

    plugin.searchByUrl = function(word, limit, asc, offset) {
        if (!limit) limit = searchLimit;
        return HatenaBookmark.model('Bookmark').searchByUrl(word, limit, asc, offset);
    }

    let BookmarkAdapter = new Struct('b');
    BookmarkAdapter.prototype.__defineGetter__('title', function() this.b.title);
    BookmarkAdapter.prototype.__defineGetter__('comment', function() this.b.comment);
    BookmarkAdapter.prototype.__defineGetter__('url', function() this.b.url);
    BookmarkAdapter.prototype.__defineGetter__('icon', function() this.b.favicon);
    BookmarkAdapter.prototype.__defineGetter__("extra", function () [
        ["comment", this.comment, "Comment"],
    ].filter(function (item) item[1]));

    plugin.command = {
        execute: function(args, openTab) {
            if (args['-sync']) {
                if (!plugin.user) {
                    liberator.echoerr('You need to login to Hatena first.');
                } else {
                    HatenaBookmark.Sync.sync();
                }
                return;
            }

            if (args['-edit']) {
                plugin.showPanel(args['-edit']);
            } else {
                if (openTab) {
                    let url = plugin.command.genURL(args.string, args.bang);
                    bangFunctions.openNewTab(url);
                } else {
                    if (args.bang) {
                        bangFunction(args.string || '');
                    } else {
                        let url = plugin.command.genURL(args.string);
                        liberator.open(url);
                    }
                }
            }
        },
        executeTab: function(args) {
            plugin.command.execute(args, true);
        },
        genURL: function(url, bang) {
            let url = (url|| '').replace(/\s/g, '');
            if (url.length) {
                if (bang) {
                    return 'http://b.hatena.ne.jp/entry/' + url.replace('#', '%23');
                } else {
                    return url;
                }
            } else {
                if (bang) {
                    return 'http://b.hatena.ne.jp/';
                } else {
                    return 'http://b.hatena.ne.jp/my';
                }
            }
        },
        adapter: BookmarkAdapter,
        templateDescription: function (item, text) {
           return <>
               {
                   !(item.extra && item.extra.length) ? "" :

                       {
                           template.map(item.extra, function (e)
                           <>{e[1]}</>,
                           <> </>/* Non-breaking space */)
                       }

               }
           </>
        },
        templateTitleIcon: function (item, text) {
           var simpleURL = text.replace(/^https?:\/\//, '');
           if (simpleURL.indexOf('/') == simpleURL.length-1)
               simpleURL = simpleURL.replace('/', '');
           return <>{item.icon ?  : <></>}{item.item.title}

           {
                 simpleURL
           }
           </>
        },
        options: {
            completer: null,
            literal: 0,
            argCount: '*',
            bang: true,
        },
        createCompleter: function(titles, searchMethod) {
            return function(context) {
                context.format = {
                    anchored: true,
                    title: titles,
                    keys: { text: "url", description: "url", icon: "icon", extra: "extra"},
                    process: [
                        plugin.command.templateTitleIcon,
                        plugin.command.templateDescription,
                    ],
                }
                let word = context.filter;
                let res = plugin[searchMethod || 'search'](word);
                context.filters = [];
                context.completions = res.map(function(b) new plugin.command.adapter(b));
            }
        }
    };

    plugin.command.options.options = [
        [['-edit', '-e'], commands.OPTION_STRING],
        [['-sync'], commands.OPTION_NOARG],
    ];

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment']);

    plugin.toggleComment = function(url) {
        HatenaBookmark.CommentViewer.toggle(url);
    }

    plugin.showComment = function(url) {
        HatenaBookmark.CommentViewer.show(url);
    }

    plugin.showPanel = function(url, options) {
        if (url) {
            HatenaBookmark.AddPanelManager.showPanel(url, options || {});
        } else if (content.location.href.indexOf('reader.livedoor.com/reader') >= 0) {
              // domain match
              let item = content.window.wrappedJSObject.get_active_item(true);
              if (item) {
                HatenaBookmark.AddPanelManager.showPanel(item.link, {title: item.title});
              }
        } else {
            HatenaBookmark.AddPanelManager.toggle();
        }
    }

    plugin.__defineGetter__('user', function() HatenaBookmark.User.user);

    if (commandNames.hbsearch) commands.addUserCommand(
        [commandNames.hbsearch],
        'Hatena Bookmark Search',
        plugin.command.execute,
        plugin.command.options,
        true
    );

    if (commandNames.hbsearch_tab) commands.addUserCommand(
        [commandNames.hbsearch_tab],
        'Hatena Bookmark Search (open tab)',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment'], 'searchByComment');
    if (commandNames.hbsearch_comment) commands.addUserCommand(
        [commandNames.hbsearch_comment],
        'Hatena Bookmark Comment Search',
        plugin.command.execute,
        plugin.command.options,
        true
    );

    if (commandNames.hbsearch_comment_tab) commands.addUserCommand(
        [commandNames.hbsearch_comment_tab],
        'Hatena Bookmark Comment Search (open tab)',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment'], 'searchByUrl');
    if (commandNames.hbsearch_url) commands.addUserCommand(
        [commandNames.hbsearch_url],
        'Hatena Bookmark Url Search',
        plugin.command.execute,
        plugin.command.options,
        true
    );

    if (commandNames.hbsearch_url_tab) commands.addUserCommand(
        [commandNames.hbsearch_url_tab],
        'Hatena Bookmark Url Search (open tab)',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment'], 'searchByTitle');
    if (commandNames.hbsearch_title) commands.addUserCommand(
        [commandNames.hbsearch_title],
        'Hatena Bookmark Title Search',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    if (commandNames.hbsearch_title_tab) commands.addUserCommand(
        [commandNames.hbsearch_title_tab],
        'Hatena Bookmark Title Search (open tab)',
        plugin.command.executeTab,
        plugin.command.options,
        true
    );

    plugin.command.options.completer = plugin.command.createCompleter(['URL','Comment']);

    completion.addUrlCompleter("H", "Hatena Bookmarks", plugin.command.createCompleter(['Hatena Bookmark']));
    config.guioptions['H'] = ['HatenaBookmark Toolbar',['hBookmarkToolbar']];
    config.dialogs.push([
        "hatenabookmark", "HatenaBookmark Config",
        function(){ window.openDialog("chrome://hatenabookmark/content/config.xul","", "chrome,titlebar,toolbar,centerscreen,dialog=no"); }
    ]);

    return plugin;
})();

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Navigator, Text, StyleSheet, View, TouchableNativeFeedback } from 'react-native';

import HomePage from '../views/HomePageView';
import Signup from '../views/signup';
var Login = require('../views/login');
import TestPage from '../views/testpage';
import OtherTestPage from '../views/othertestpage';
import Club from '../views/club';
import Profile from '../views/profile';
//import FindAClub from '../views/findaclub';
//import FindAClubResults from '../views/findaclubresults';
//import FindAnEvent from '../views/findanevent';
//import FindAnEventResults from '../views/findaneventresults';
import AllViews from '../views/allviews.js';

var TouchableElement = TouchableNativeFeedback; //TODO: not this

export default class ClubLifeNavigator extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userId: ""
        };
    }

    render() {
        //initial route for navigation
        var initialRoute = this.props.initialRoute || {
            type: 'login',
            index: 0
        }

        //determine which scene to render based on route information.
        var renderScene = (route, navigator) => {
            var scene = "";
            switch(route.type) {
                case "signup":
                    scene = (
                        <Signup
                            navigator={navigator}
                            onSignup={()=>{
                                const leIndex = route.index+1;
                                navigator.push({
                                    "type": "login",
                                    index: leIndex
                                });
                            }}
                        />
                    );
                    break;
                case "login":
                    scene = (
                        <Login
                            navigator={navigator}
                            callbackOnSuccessfulLogin={(userId)=>{
                                const leIndex = route.index+1;
                                this.setState({
                                    userId: userId
                                });
                                navigator.push({
                                    "type": "homepage",
                                    index: leIndex
                                });
                            }}
                            onGoSignup={()=>{
                                const leIndex = route.index+1;
                                navigator.push({
                                    "type": "signup",
                                    index: leIndex
                                })
                            }}
                        />
                    );
                    break;
                case "homepage":
                    scene = (
                        <HomePage
                            onGoHome={()=>{
                                const leIndex = route.index+1;
                                navigator.push({
                                    "type": "homepage",
                                    index: leIndex
                                })
                            }}
                            onGoProfile={()=>{
                                const leIndex = route.index + 1;
                                navigator.push({
                                    "type": "profile",
                                    index: leIndex
                                })
                            }}
                            onGoFindAnEvent={()=>{
                                const leIndsex = route.index + 1;
                                navigator.push({
                                    "type": "findanevent",
                                    index: leIndsex
                                })
                            }}
                            onGoFindAClub={()=>{
                                const leIndsex = route.index + 1;
                                navigator.push({
                                    "type": "findaclub",
                                    index: leIndsex
                                })
                            }}
                        />
                    );
                    break;
                case "club":
                    scene = (
                        <Club

                        />
                    ); //TODO later: integrate props in meaningful fashion
                    break;
                case "profile":
                    scene = (
                        <Profile

                        />
                    );
                    break;
                case "findaclub":
                    scene = (
                        <FindAClub

                        />
                    );
                    break;
                case "findanevent":
                    scene = (
                        <FindAnEvent

                        />
                    );
                    break;
                case "testpage":
                    scene = (
                        <TestPage
                            navigator={navigator}
                            onGoOther={()=>{
                                const leIndex = route.index + 1;
                                navigator.push({
                                    "type": "othertestpage",
                                    index: leIndex
                                });
                            }}
                            onGoBack={()=>{
                                if(route.index > 0) {
                                    navigator.pop();
                                }
                            }}
                            onGoForward={()=>{

                            }}
                        />
                    );
                    break;
                case "othertestpage":
                    scene = (
                        <OtherTestPage
                            navigator={navigator}
                            onGoOther={()=>{
                                const leIndex = route.index + 1;
                                navigator.push({
                                    type: "testpage",
                                    index: leIndex
                                })
                            }}
                            onGoBack={()=>{
                                if(route.index > 0) {
                                    navigator.pop();
                                }
                            }}
                            onGoForward={()=>{

                            }}
                        />

                    );
                    break;
                case "allviews":
                    //link to all views debug page
                    scene = (
                        <AllViews
                            views={[{
                                name: "login",
                                pressCallback: ()=> {navigator.resetTo({type: 'login', index: 0});}
                            }, {
                                name: "signup",
                                pressCallback: ()=> {navigator.resetTo({type: "signup", index: 0});}
                            }, {
                                name: "homepage",
                                pressCallback: ()=> {navigator.resetTo({type: "homepage", index: 0});}
                            }, {
                                name: "findaclub",
                                pressCallback: ()=> {navigator.resetTo({type: "findaclub", index: 0});}
                            }]}
                        />
                    );
                    break;
                default:
                    //oh shi-
                    scene = (
                        <View><Text>Something went horribly wrong with routing.</Text></View>
                    );
            }
            return scene;
        };

        //conigure the scene transition based on route information.
        var configureScene = (route, routeStack) => {
            return Navigator.SceneConfigs.FloatFromBottom; //TODO: different transitions based on different routes?
        };

        return (
            <Navigator
                initialRoute={initialRoute}
                renderScene={renderScene}
                configureScene={configureScene}
                navigationBar={navbar}
            />
        );
    }
}

/*
    Styles
*/

const styles = StyleSheet.create({
    navbar: {
        marginBottom: 40
    }
});

var navbar = (
    <Navigator.NavigationBar
        routeMapper={{
            LeftButton: (route, navigator, index, navState) => {
                var button = "";
                switch(route.type) {
                        case "login":
                            button = (
                                <Text></Text> //empty
                            );
                            break;
                        case "profile":
                            button = (
                                <TouchableElement onPress={()=>{navigator.pop()}}><Text>BABYGOTBACK</Text></TouchableElement>
                            );
                        default:
                            button = <Text>⚾</Text>;

                }
                return button;
            },
            RightButton: (route, navigator, index, navState) => {
                var button = "";
                switch(route.type) {
                    case "login":
                         button = (
                             <TouchableElement onPress={()=>{navigator.resetTo({type: "allviews", index: 0})}}><View><Text>ALLVIEWS</Text></View></TouchableElement>
                         );
                         break;
                    default:
                        button = (
                            <Text>☃</Text>
                        )
                }
                return button;
            },
            Title: (route, navigator, index, navState) => {
                return (<Text style={{flex: 1, justifyContent: 'center'}}>ClubLife</Text>);
            },
        }}
        style={styles.navbar}
    />
);
<commit_msg>added the club pages and edit pages after navigator mess up<commit_after>import React, { Component } from 'react';
import { Navigator, Text, StyleSheet, View, TouchableNativeFeedback } from 'react-native';

import HomePage from '../views/HomePageView';
import Signup from '../views/signup';
var Login = require('../views/login');
import TestPage from '../views/testpage';
import OtherTestPage from '../views/othertestpage';
import Club from '../views/club';
import Profile from '../views/profile';
//import FindAClub from '../views/findaclub';
//import FindAClubResults from '../views/findaclubresults';
//import FindAnEvent from '../views/findanevent';
//import FindAnEventResults from '../views/findaneventresults';
import AllViews from '../views/allviews.js';
import EditClub from '../views/EditClub';
import ClubPage from '../views/clubPage';
import ClubInfo from '../views/clubInfo';

var TouchableElement = TouchableNativeFeedback; //TODO: not this

export default class ClubLifeNavigator extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userId: ""
        };
    }

    render() {
        //initial route for navigation
        var initialRoute = this.props.initialRoute || {
            type: 'login',
            index: 0
        }

        //determine which scene to render based on route information.
        var renderScene = (route, navigator) => {
            var scene = "";
            switch(route.type) {
                case "signup":
                    scene = (
                        <Signup
                            navigator={navigator}
                            onSignup={()=>{
                                const leIndex = route.index+1;
                                navigator.push({
                                    "type": "login",
                                    index: leIndex
                                });
                            }}
                        />
                    );
                    break;
                case "login":
                    scene = (
                        <Login
                            navigator={navigator}
                            callbackOnSuccessfulLogin={(userId)=>{
                                const leIndex = route.index+1;
                                this.setState({
                                    userId: userId
                                });
                                navigator.push({
                                    "type": "homepage",
                                    index: leIndex
                                });
                            }}
                            onGoSignup={()=>{
                                const leIndex = route.index+1;
                                navigator.push({
                                    "type": "signup",
                                    index: leIndex
                                })
                            }}
                        />
                    );
                    break;
                case "homepage":
                    scene = (
                        <HomePage
                            onGoHome={()=>{
                                const leIndex = route.index+1;
                                navigator.push({
                                    "type": "homepage",
                                    index: leIndex
                                })
                            }}
                            onGoProfile={()=>{
                                const leIndex = route.index + 1;
                                navigator.push({
                                    "type": "profile",
                                    index: leIndex
                                })
                            }}
                            onGoFindAnEvent={()=>{
                                const leIndsex = route.index + 1;
                                navigator.push({
                                    "type": "findanevent",
                                    index: leIndsex
                                })
                            }}
                            onGoClubList={()=>{
                                const leIndsex = route.index + 1;
                                navigator.push({
                                    "type": "clubPage",
                                    index: leIndsex
                                })
                            }}
                            onGoFindAClub={()=>{
                                const leIndsex = route.index + 1;
                                navigator.push({
                                    "type": "findaclub",
                                    index: leIndsex
                                })
                            }}
                        />
                    );
                    break;
                case "club":
                    scene = (
                        <Club
                            onGoEditClub={()=>{
                                const leIndex = route.index+1;
                                navigator.push({
                                    "type": "EditClub",
                                    index: leIndex,
                                })
                            }}
                            onGoClubInfo={()=>{
                                const leIndex = route.index+1;
                                navigator.push({
                                    "type": "clubInfo",
                                    index: leIndex,
                                })
                            }}
                        />

                    ); //TODO later: integrate props in meaningful fashion
                    break;
                case "profile":
                    scene = (
                        <Profile

                        />
                    );
                    break;
                case "findaclub":
                    scene = (
                        <FindAClub

                        />
                    );
                    break;
                case "findanevent":
                    scene = (
                        <FindAnEvent

                        />
                    );
                    break;
                case "testpage":
                    scene = (
                        <TestPage
                            navigator={navigator}
                            onGoOther={()=>{
                                const leIndex = route.index + 1;
                                navigator.push({
                                    "type": "othertestpage",
                                    index: leIndex
                                });
                            }}
                            onGoBack={()=>{
                                if(route.index > 0) {
                                    navigator.pop();
                                }
                            }}
                            onGoForward={()=>{

                            }}
                        />
                    );
                    break;
                case "othertestpage":
                    scene = (
                        <OtherTestPage
                            navigator={navigator}
                            onGoOther={()=>{
                                const leIndex = route.index + 1;
                                navigator.push({
                                    type: "testpage",
                                    index: leIndex
                                })
                            }}
                            onGoBack={()=>{
                                if(route.index > 0) {
                                    navigator.pop();
                                }
                            }}
                            onGoForward={()=>{

                            }}
                        />

                    );
                    break;
                case "allviews":
                    //link to all views debug page
                    scene = (
                        <AllViews
                            views={[{
                                name: "login",
                                pressCallback: ()=> {navigator.resetTo({type: 'login', index: 0});}
                            }, {
                                name: "signup",
                                pressCallback: ()=> {navigator.resetTo({type: "signup", index: 0});}
                            }, {
                                name: "homepage",
                                pressCallback: ()=> {navigator.resetTo({type: "homepage", index: 0});}
                            }, {
                                name: "findaclub",
                                pressCallback: ()=> {navigator.resetTo({type: "findaclub", index: 0});}
                            }]}
                        />
                    );
                    break;
                case "clubPage":
                    scene = (
                        <ClubPage
                            navigator = {navigator}
                            onGoClub={()=>{
                                const leIndex = route.index + 1;
                                navigator.push({
                                    type: "club",
                                    index: leIndex
                                })
                            }}
                        />

                    );
                    break;

                case "EditClub":
                    scene = (
                        <EditClub
                            navigator = {navigator}
                            onGoClub={()=>{
                                const leIndex = route.index + 1;
                                navigator.push({
                                    type: "club",
                                    index: leIndex
                                })
                            }}
                        />

                    );
                    break;

                case "clubInfo":
                    scene = (
                        <ClubInfo
                            onGoClub={()=>{
                                const leIndex = route.index + 1;
                                navigator.push({
                                    type: "club",
                                    index: leIndex
                                })
                            }}
                        />
                    );
                    break;

                default:
                    //oh shi-
                    scene = (
                        <View><Text>Something went horribly wrong with routing.</Text></View>
                    );
            }
            return scene;
        };

        //conigure the scene transition based on route information.
        var configureScene = (route, routeStack) => {
            return Navigator.SceneConfigs.FloatFromBottom; //TODO: different transitions based on different routes?
        };

        return (
            <Navigator
                initialRoute={initialRoute}
                renderScene={renderScene}
                configureScene={configureScene}
                navigationBar={navbar}
            />
        );
    }
}

/*
    Styles
*/

const styles = StyleSheet.create({
    navbar: {
        marginBottom: 40
    }
});

var navbar = (
    <Navigator.NavigationBar
        routeMapper={{
            LeftButton: (route, navigator, index, navState) => {
                var button = "";
                switch(route.type) {
                        case "login":
                            button = (
                                <Text></Text> //empty
                            );
                            break;
                        case "profile":
                            button = (
                                <TouchableElement onPress={()=>{navigator.pop()}}><Text>BABYGOTBACK</Text></TouchableElement>
                            );
                        default:
                            button = <Text>⚾</Text>;

                }
                return button;
            },
            RightButton: (route, navigator, index, navState) => {
                var button = "";
                switch(route.type) {
                    case "login":
                         button = (
                             <TouchableElement onPress={()=>{navigator.resetTo({type: "allviews", index: 0})}}><View><Text>ALLVIEWS</Text></View></TouchableElement>
                         );
                         break;
                    default:
                        button = (
                            <Text>☃</Text>
                        )
                }
                return button;
            },
            Title: (route, navigator, index, navState) => {
                return (<Text style={{flex: 1, justifyContent: 'center'}}>ClubLife</Text>);
            },
        }}
        style={styles.navbar}
    />
);
<|endoftext|>


<commit_before>
var now = new Date();
var nowOffset = 0;

function showTalks(){
    var currentTalks = [];
    var nextTalks = [];

    for(var t in tracks){
        var track = tracks[t];
        for(var i=0;i<track.length;i++){
            var talk = track[i];
            if(talk.start <= now && talk.end >= now){
                currentTalks.push(talk);
            } else if(talk.start > now) {
                var addIt = true;
                for(var n = 0; n < nextTalks.length; n++){
                	// only keep the closest talks
                    if(nextTalks[n].start > talk.start){
                        nextTalks.splice(n, 1);
                    }else if(nextTalks[n].start < talk.start){
                        addIt = false;
                        break;
                    }
                }
                if(addIt) {
                    nextTalks.push(talk);
                }
            }
        }
    }

    // Display the current date
    $(".js-live-currentDate").text(formatDate(new Date(now)) + " " + formatTimeSeconds(new Date(now)));

    var t = jQuery("#target");
    t.empty();

    var markup = "
Currently
";

    // -- Current talks
    if (currentTalks.length > 0) {
        markup += "
";
        //markup += "Currently in other tracks:";
        markup += "
";
        for(var n = 0; n < currentTalks.length; n++) {
            var talk = currentTalks[n];
            markup += "
";
            markup +=     "
";
            markup +=         "
"+talk.track+"
";
            markup +=         talkToString(talk);
            markup +=     "
";
            markup += "
";
        }
        markup += "
";
        markup += "
";
    }else{
    	markup += "
Oh noes!! We haven’ts gots any talks righter now!! :(
";
    }

    markup += "
Next
";

    // -- Next talks
    if (nextTalks.length > 0) {
        markup += "
";
        //markup += "Next in other tracks:";
        markup += "
";
        for (var n = 0; n < nextTalks.length; n++) {
            var talk = nextTalks[n];
            markup += "
";
            markup +=     "
";
            markup +=         "
"+talk.track+"
";
            markup +=         talkToString(talk);
            markup +=     "
";
            markup += "
";
        }
        markup += "
";
        markup += "
";
    }else{
    	markup += "
Oh noes!! Its a doner, see youse nexts years!! :)
";
    }

    t.append(markup);
}
var months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
function formatDate(date){
    return pad(date.getDate()) + " " + months[date.getMonth()];
}
function formatTime(date){
    return pad(date.getHours()) + ":" + pad(date.getMinutes());
}
function formatTimeSeconds(date){
    return formatTime(date) + ":" + pad(date.getSeconds());
}
function pad(num) {
    var s = num+"";
    while (s.length < 2) s = "0" + s;
    return s;
}
function duration(time){
    var seconds = Math.floor(time / 1000);
    var minutes = Math.floor(seconds / 60);
    var secondsMod = seconds % 60;
    var hours = Math.floor(minutes / 60);
    var minutesMod = minutes % 60;
    var days = Math.floor(hours / 24);
    var hoursMod = hours % 24;
    var weeks = Math.floor(days / 7);
    var daysMod = days % 7;

    var ret=" ";
    if(weeks > 0)
        ret += weeks+" week"+(weeks>1?"s":"")+" ";
    if(daysMod > 0)
        ret += daysMod+" day"+(days>1?"s":"")+" ";
    ret += pad(hoursMod)+":"+pad(minutesMod)+":"+pad(secondsMod);
    if(ret.endsWith(" "))
    	ret = ret.substring(0, ret.length-1);
    if(ret.startsWith(" "))
    	ret = ret.substring(1);
    return ret;
}

function talkToString(talk){
    if(talk == null)
        return "";
    var start = new Date(talk.start);
    var end = new Date(talk.end);
    var durationString;
    if(start.getTime() > now){
        durationString = " (in " + duration(start.getTime() - now)+")";
    }else{
        durationString = " (" + duration(end.getTime() - now)+" remaining)";
    }
    var markup = "
";

    // Title
    markup += "
" + talk.title + "
";

    // Slot
    markup += "
"
            + "    "
            +      formatTime(start) + " - " + formatTime(end) + durationString
            + "
";

    // Theme
    if (talk.theme) {
        markup += "" + talk.theme + "";
    }

    // Level
    if (talk.level) {
        markup += "" + talk.level + "";
    }

    //markup += "
"+talk.description+"
";

    // Speakers
    markup += "
";
    for(var n = 0; n < talk.speakers.length; n++) {
        var speaker = talk.speakers[n];
        markup += "
";
            markup += "

";
            markup += "
" + speaker.name + "
";
        markup += "
";
    }
    markup += "
";

    // End of the div .talk
    markup += "
";
    return markup;
}

jQuery(function(){
	window.setInterval(function(){
		now = new Date().getTime() + nowOffset;
		showTalks();
	}, 1000);
});
<commit_msg>Hit network every 30 minutes in live.js<commit_after>
var now = new Date();
var nowOffset = 0;

function showTalks(){
    var currentTalks = [];
    var nextTalks = [];

    for(var t in tracks){
        var track = tracks[t];
        for(var i=0;i<track.length;i++){
            var talk = track[i];
            if(talk.start <= now && talk.end >= now){
                currentTalks.push(talk);
            } else if(talk.start > now) {
                var addIt = true;
                for(var n = 0; n < nextTalks.length; n++){
                	// only keep the closest talks
                    if(nextTalks[n].start > talk.start){
                        nextTalks.splice(n, 1);
                    }else if(nextTalks[n].start < talk.start){
                        addIt = false;
                        break;
                    }
                }
                if(addIt) {
                    nextTalks.push(talk);
                }
            }
        }
    }

    // Display the current date
    $(".js-live-currentDate").text(formatDate(new Date(now)) + " " + formatTimeSeconds(new Date(now)));

    var t = jQuery("#target");
    t.empty();

    var markup = "
Currently
";

    // -- Current talks
    if (currentTalks.length > 0) {
        markup += "
";
        //markup += "Currently in other tracks:";
        markup += "
";
        for(var n = 0; n < currentTalks.length; n++) {
            var talk = currentTalks[n];
            markup += "
";
            markup +=     "
";
            markup +=         "
"+talk.track+"
";
            markup +=         talkToString(talk);
            markup +=     "
";
            markup += "
";
        }
        markup += "
";
        markup += "
";
    }else{
    	markup += "
Oh noes!! We haven’ts gots any talks righter now!! :(
";
    }

    markup += "
Next
";

    // -- Next talks
    if (nextTalks.length > 0) {
        markup += "
";
        //markup += "Next in other tracks:";
        markup += "
";
        for (var n = 0; n < nextTalks.length; n++) {
            var talk = nextTalks[n];
            markup += "
";
            markup +=     "
";
            markup +=         "
"+talk.track+"
";
            markup +=         talkToString(talk);
            markup +=     "
";
            markup += "
";
        }
        markup += "
";
        markup += "
";
    }else{
    	markup += "
Oh noes!! Its a doner, see youse nexts years!! :)
";
    }

    t.append(markup);
}
var months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
function formatDate(date){
    return pad(date.getDate()) + " " + months[date.getMonth()];
}
function formatTime(date){
    return pad(date.getHours()) + ":" + pad(date.getMinutes());
}
function formatTimeSeconds(date){
    return formatTime(date) + ":" + pad(date.getSeconds());
}
function pad(num) {
    var s = num+"";
    while (s.length < 2) s = "0" + s;
    return s;
}
function duration(time){
    var seconds = Math.floor(time / 1000);
    var minutes = Math.floor(seconds / 60);
    var secondsMod = seconds % 60;
    var hours = Math.floor(minutes / 60);
    var minutesMod = minutes % 60;
    var days = Math.floor(hours / 24);
    var hoursMod = hours % 24;
    var weeks = Math.floor(days / 7);
    var daysMod = days % 7;

    var ret=" ";
    if(weeks > 0)
        ret += weeks+" week"+(weeks>1?"s":"")+" ";
    if(daysMod > 0)
        ret += daysMod+" day"+(days>1?"s":"")+" ";
    ret += pad(hoursMod)+":"+pad(minutesMod)+":"+pad(secondsMod);
    if(ret.endsWith(" "))
    	ret = ret.substring(0, ret.length-1);
    if(ret.startsWith(" "))
    	ret = ret.substring(1);
    return ret;
}

function talkToString(talk){
    if(talk == null)
        return "";
    var start = new Date(talk.start);
    var end = new Date(talk.end);
    var durationString;
    if(start.getTime() > now){
        durationString = " (in " + duration(start.getTime() - now)+")";
    }else{
        durationString = " (" + duration(end.getTime() - now)+" remaining)";
    }
    var markup = "
";

    // Title
    markup += "
" + talk.title + "
";

    // Slot
    markup += "
"
            + "    "
            +      formatTime(start) + " - " + formatTime(end) + durationString
            + "
";

    // Theme
    if (talk.theme) {
        markup += "" + talk.theme + "";
    }

    // Level
    if (talk.level) {
        markup += "" + talk.level + "";
    }

    //markup += "
"+talk.description+"
";

    // Speakers
    markup += "
";
    for(var n = 0; n < talk.speakers.length; n++) {
        var speaker = talk.speakers[n];
        markup += "
";
            markup += "

";
            markup += "
" + speaker.name + "
";
        markup += "
";
    }
    markup += "
";

    // End of the div .talk
    markup += "
";
    return markup;
}

jQuery(function(){
	showTalks();
	window.setInterval(function(){
		now = new Date().getTime() + nowOffset;
		showTalks();
	}, 1000);
	window.setInterval(function(){
		jQuery.get("http://rivieradev.fr");
	}, 1000 *60*30 );
});
<|endoftext|>


<commit_before>function whatToTestSpidermonkeyTrunk(code)
{
  /* jshint laxcomma: true */
  // regexps can't match across lines, so replace whitespace with spaces.
  var codeL = code.replace(/\s/g, " ");

  return {

    allowParse: true,

    allowExec: unlikelyToHang(code)
      && (jsshell || code.indexOf("nogeckoex") == -1)
    ,

    allowIter: true,

    // Ideally we'd detect whether the shell was compiled with --enable-more-deterministic
    expectConsistentOutput: true
       && (gcIsQuiet || code.indexOf("gc") == -1)
       && code.indexOf("/*NODIFF*/") == -1          // Ignore diff testing on these labels
       && code.indexOf("Date") == -1                // time marches on
       && code.indexOf("timeout") == -1             // time runs and crawls
       && code.indexOf("random") == -1
       && code.indexOf("backtrace") == -1           // shows memory addresses
       && code.indexOf("dumpObject") == -1          // shows heap addresses
       && code.indexOf("dumpHeapComplete") == -1    // shows heap addresses
       && code.indexOf("dumpStringRepresentation") == -1  // shows memory addresses
       && code.indexOf("evalInWorker") == -1        // causes diffs in --no-threads vs --ion-offthread-compile=off
       && code.indexOf("offThreadCompileScript") == -1  // causes diffs in --no-threads vs --ion-offthread-compile=off
       && code.indexOf("oomAfterAllocations") == -1
       && code.indexOf("printProfilerEvents") == -1 // causes diffs in --ion-eager vs --baseline-eager
       && code.indexOf("load") == -1                // load()ed regression test might output dates, etc
       && code.indexOf("drainAllocationsLog") == -1 // drainAllocationsLog returns an object with a timestamp, see bug 1066313
       && code.indexOf("getBacktrace") == -1        // getBacktrace returns memory addresses which differs depending on flags
       && code.indexOf("inJit") == -1               // may become true after several iterations, or return a string with --no-baseline
       && code.indexOf("inIon") == -1               // may become true after several iterations, or return a string with --no-ion
    ,

    expectConsistentOutputAcrossIter: true
       && code.indexOf("options") == -1             // options() is per-cx, and the js shell doesn't create a new cx for each sandbox/compartment
    ,

    expectConsistentOutputAcrossJITs: true
       && code.indexOf("'strict") == -1             // see bug 743425
       && code.indexOf("Object.seal") == -1         // bug 937922
       && code.indexOf("length") == -1              // bug 1027846
       && code.indexOf("preventExtensions") == -1   // bug 1085299
       && !( codeL.match(/\/.*[\u0000\u0080-\uffff]/)) // doesn't stay valid utf-8 after going through python (?)

  };
}

function whatToTestSpidermonkeyMozilla31(code)
{
  /* jshint laxcomma: true */
  // regexps can't match across lines, so replace whitespace with spaces.
  var codeL = code.replace(/\s/g, " ");

  return {

    allowParse: true,

    allowExec: unlikelyToHang(code)
      && (jsshell || code.indexOf("nogeckoex") == -1)
    ,

    allowIter: true,

    // Ideally we'd detect whether the shell was compiled with --enable-more-deterministic
    expectConsistentOutput: true
       && (gcIsQuiet || code.indexOf("gc") == -1)
       && code.indexOf("Date") == -1                // time marches on
       && code.indexOf("random") == -1
       && code.indexOf("dumpObject") == -1          // shows heap addresses
       && code.indexOf("oomAfterAllocations") == -1
       && code.indexOf("reducePar") == -1           // only deterministic for associative elemental-reducers
       && code.indexOf("scanPar") == -1             // only deterministic for associative elemental-reducers
       && code.indexOf("scatterPar") == -1          // only deterministic for associative conflict-resolvers
    ,

    expectConsistentOutputAcrossIter: true
       && code.indexOf("options") == -1             // options() is per-cx, and the js shell doesn't create a new cx for each sandbox/compartment
    ,

    expectConsistentOutputAcrossJITs: true
       && code.indexOf("/*NODIFF*/") == -1          // Ignore diff testing on these labels
       && code.indexOf("'strict") == -1             // see bug 743425
       && code.indexOf("Object.seal") == -1         // bug 937922 (31 branch)
       && code.indexOf("length") == -1              // bug 998059 (31 branch)
       && code.indexOf("buildPar") == -1            // bug 998262 (31 branch)
       && code.indexOf("with") == -1                // bug 998580 (31 branch)
       && code.indexOf("use asm") == -1             // bug 999790 (31 branch)
       && code.indexOf("Math.round") == -1          // bug 1000606 (31 branch)
       && code.indexOf("Math.fround") == -1         // bug 1000606 (31 branch)
       && code.indexOf("Math.ceil") == -1           // bug 1000605 (31 branch)
       && code.indexOf("Math.asinh") == -1          // bug 1007213 (31 branch)
       && code.indexOf("use strict") == -1          // bug 1008818 (31 branch)
       && code.indexOf("Math.ceil") == -1           // bug 1015656 (31 branch)
       && code.indexOf("arguments") == -1           // bug 1024444 (31 branch)
       && code.indexOf("use strict") == -1          // bug 1025587 (31 branch)
       && code.indexOf("length") == -1              // bug 1027846 (31 branch)
       && code.indexOf("enumerable") == -1          // bug 1054545 (31 branch)
       && code.indexOf("buildPar") == -1            // bug 1066496 (31 branch)
       && !( codeL.match(/\/.*[\u0000\u0080-\uffff]/)) // doesn't stay valid utf-8 after going through python (?)

  };
}

function whatToTestJavaScriptCore(code)
{
  return {

    allowParse: true,
    allowExec: unlikelyToHang(code),
    allowIter: false, // JavaScriptCore does not support |yield| and |Iterator|
    expectConsistentOutput: false,
    expectConsistentOutputAcrossIter: false,
    expectConsistentOutputAcrossJITs: false

  };
}

function whatToTestGeneric(code)
{
  return {
    allowParse: true,
    allowExec: unlikelyToHang(code),
    allowIter: (typeof Iterator == "function"),
    expectConsistentOutput: false,
    expectConsistentOutputAcrossIter: false,
    expectConsistentOutputAcrossJITs: false
  };
}

var whatToTest;
if (engine == ENGINE_SPIDERMONKEY_TRUNK)
  whatToTest = whatToTestSpidermonkeyTrunk;
else if (engine == ENGINE_SPIDERMONKEY_MOZILLA24)
  whatToTest = whatToTestSpidermonkeyMozilla24;
else if (engine == ENGINE_JAVASCRIPTCORE)
  whatToTest = whatToTestJavaScriptCore;
else
  whatToTest = whatToTestGeneric;

function unlikelyToHang(code)
{
  var codeL = code.replace(/\s/g, " ");

  // Things that are likely to hang in all JavaScript engines
  return true
    && code.indexOf("infloop") == -1
    && !( codeL.match( /const.*for/ )) // can be an infinite loop: function() { const x = 1; for each(x in ({a1:1})) dumpln(3); }
    && !( codeL.match( /for.*const/ )) // can be an infinite loop: for each(x in ...); const x;
    && !( codeL.match( /for.*in.*uneval/ )) // can be slow to loop through the huge string uneval(this), for example
    && !( codeL.match( /for.*for.*for/ )) // nested for loops (including for..in, array comprehensions, etc) can take a while
    && !( codeL.match( /for.*for.*gc/ ))
    ;
}
<commit_msg>Reorder and adjust comment positions of functions in whatToTestSpidermonkeyTrunk in js/jsfunfuzz/avoid-known-bugs.js.<commit_after>function whatToTestSpidermonkeyTrunk(code)
{
  /* jshint laxcomma: true */
  // regexps can't match across lines, so replace whitespace with spaces.
  var codeL = code.replace(/\s/g, " ");

  return {

    allowParse: true,

    allowExec: unlikelyToHang(code)
      && (jsshell || code.indexOf("nogeckoex") == -1)
    ,

    allowIter: true,

    // Ideally we'd detect whether the shell was compiled with --enable-more-deterministic
    expectConsistentOutput: true
       && (gcIsQuiet || code.indexOf("gc") == -1)
       && code.indexOf("/*NODIFF*/") == -1                // Ignore diff testing on these labels
       && code.indexOf("Date") == -1                      // time marches on
       && code.indexOf("backtrace") == -1                 // shows memory addresses
       && code.indexOf("drainAllocationsLog") == -1       // drainAllocationsLog returns an object with a timestamp, see bug 1066313
       && code.indexOf("dumpObject") == -1                // shows heap addresses
       && code.indexOf("dumpHeapComplete") == -1          // shows heap addresses
       && code.indexOf("dumpStringRepresentation") == -1  // shows memory addresses
       && code.indexOf("evalInWorker") == -1              // causes diffs in --no-threads vs --ion-offthread-compile=off
       && code.indexOf("getBacktrace") == -1              // getBacktrace returns memory addresses which differs depending on flags
       && code.indexOf("load") == -1                      // load()ed regression test might output dates, etc
       && code.indexOf("offThreadCompileScript") == -1    // causes diffs in --no-threads vs --ion-offthread-compile=off
       && code.indexOf("oomAfterAllocations") == -1
       && code.indexOf("printProfilerEvents") == -1       // causes diffs in --ion-eager vs --baseline-eager
       && code.indexOf("inIon") == -1                     // may become true after several iterations, or return a string with --no-ion
       && code.indexOf("inJit") == -1                     // may become true after several iterations, or return a string with --no-baseline
       && code.indexOf("random") == -1
       && code.indexOf("timeout") == -1                   // time runs and crawls
    ,

    expectConsistentOutputAcrossIter: true
       && code.indexOf("options") == -1             // options() is per-cx, and the js shell doesn't create a new cx for each sandbox/compartment
    ,

    expectConsistentOutputAcrossJITs: true
       && code.indexOf("'strict") == -1                 // see bug 743425
       && code.indexOf("Object.seal") == -1             // bug 937922
       && code.indexOf("length") == -1                  // bug 1027846
       && code.indexOf("preventExtensions") == -1       // bug 1085299
       && !( codeL.match(/\/.*[\u0000\u0080-\uffff]/))  // doesn't stay valid utf-8 after going through python (?)

  };
}

function whatToTestSpidermonkeyMozilla31(code)
{
  /* jshint laxcomma: true */
  // regexps can't match across lines, so replace whitespace with spaces.
  var codeL = code.replace(/\s/g, " ");

  return {

    allowParse: true,

    allowExec: unlikelyToHang(code)
      && (jsshell || code.indexOf("nogeckoex") == -1)
    ,

    allowIter: true,

    // Ideally we'd detect whether the shell was compiled with --enable-more-deterministic
    expectConsistentOutput: true
       && (gcIsQuiet || code.indexOf("gc") == -1)
       && code.indexOf("Date") == -1                // time marches on
       && code.indexOf("random") == -1
       && code.indexOf("dumpObject") == -1          // shows heap addresses
       && code.indexOf("oomAfterAllocations") == -1
       && code.indexOf("reducePar") == -1           // only deterministic for associative elemental-reducers
       && code.indexOf("scanPar") == -1             // only deterministic for associative elemental-reducers
       && code.indexOf("scatterPar") == -1          // only deterministic for associative conflict-resolvers
    ,

    expectConsistentOutputAcrossIter: true
       && code.indexOf("options") == -1             // options() is per-cx, and the js shell doesn't create a new cx for each sandbox/compartment
    ,

    expectConsistentOutputAcrossJITs: true
       && code.indexOf("/*NODIFF*/") == -1          // Ignore diff testing on these labels
       && code.indexOf("'strict") == -1             // see bug 743425
       && code.indexOf("Object.seal") == -1         // bug 937922 (31 branch)
       && code.indexOf("length") == -1              // bug 998059 (31 branch)
       && code.indexOf("buildPar") == -1            // bug 998262 (31 branch)
       && code.indexOf("with") == -1                // bug 998580 (31 branch)
       && code.indexOf("use asm") == -1             // bug 999790 (31 branch)
       && code.indexOf("Math.round") == -1          // bug 1000606 (31 branch)
       && code.indexOf("Math.fround") == -1         // bug 1000606 (31 branch)
       && code.indexOf("Math.ceil") == -1           // bug 1000605 (31 branch)
       && code.indexOf("Math.asinh") == -1          // bug 1007213 (31 branch)
       && code.indexOf("use strict") == -1          // bug 1008818 (31 branch)
       && code.indexOf("Math.ceil") == -1           // bug 1015656 (31 branch)
       && code.indexOf("arguments") == -1           // bug 1024444 (31 branch)
       && code.indexOf("use strict") == -1          // bug 1025587 (31 branch)
       && code.indexOf("length") == -1              // bug 1027846 (31 branch)
       && code.indexOf("enumerable") == -1          // bug 1054545 (31 branch)
       && code.indexOf("buildPar") == -1            // bug 1066496 (31 branch)
       && !( codeL.match(/\/.*[\u0000\u0080-\uffff]/)) // doesn't stay valid utf-8 after going through python (?)

  };
}

function whatToTestJavaScriptCore(code)
{
  return {

    allowParse: true,
    allowExec: unlikelyToHang(code),
    allowIter: false, // JavaScriptCore does not support |yield| and |Iterator|
    expectConsistentOutput: false,
    expectConsistentOutputAcrossIter: false,
    expectConsistentOutputAcrossJITs: false

  };
}

function whatToTestGeneric(code)
{
  return {
    allowParse: true,
    allowExec: unlikelyToHang(code),
    allowIter: (typeof Iterator == "function"),
    expectConsistentOutput: false,
    expectConsistentOutputAcrossIter: false,
    expectConsistentOutputAcrossJITs: false
  };
}

var whatToTest;
if (engine == ENGINE_SPIDERMONKEY_TRUNK)
  whatToTest = whatToTestSpidermonkeyTrunk;
else if (engine == ENGINE_SPIDERMONKEY_MOZILLA24)
  whatToTest = whatToTestSpidermonkeyMozilla24;
else if (engine == ENGINE_JAVASCRIPTCORE)
  whatToTest = whatToTestJavaScriptCore;
else
  whatToTest = whatToTestGeneric;

function unlikelyToHang(code)
{
  var codeL = code.replace(/\s/g, " ");

  // Things that are likely to hang in all JavaScript engines
  return true
    && code.indexOf("infloop") == -1
    && !( codeL.match( /const.*for/ )) // can be an infinite loop: function() { const x = 1; for each(x in ({a1:1})) dumpln(3); }
    && !( codeL.match( /for.*const/ )) // can be an infinite loop: for each(x in ...); const x;
    && !( codeL.match( /for.*in.*uneval/ )) // can be slow to loop through the huge string uneval(this), for example
    && !( codeL.match( /for.*for.*for/ )) // nested for loops (including for..in, array comprehensions, etc) can take a while
    && !( codeL.match( /for.*for.*gc/ ))
    ;
}
<|endoftext|>


<commit_before>
//Listener for database for decision-are-you-hapy
firebase.database().ref('decision-are-you-happy').on('value', function(snapshot){
	var numberOfNo=0;
	var numberOfYes=0;
	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Yes"){
			numberOfYes++;
		}else{
			numberOfNo++;
		}
	});

	//console.log("yes:" +numberOfYes);
	if(numberOfYes>numberOfNo){
		$(".decision-are-you-happy-result").html("YES");
	}else{
		$(".decision-are-you-happy-result").html("NO");
	}
});

//Listener for the database for decision-clothing
firebase.database().ref('decision-clothing').on('value', function(snapshot){
	var list ={
		"Tie": 0,
		"Shoes" : 0,
		"Jacket" : 0,
		"Trousers" :0,
	}

	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Shoes"){
			list.Shoes++;
		}else if (data.val()==="Tie"){
			list.Tie++;
		}else if (data.val()==="Jacket"){
			list.Jacket++;
		}else if (data.val()=="Trousers"){
			list.Trousers++;
		}
	});

	//create an array to hold all of the choices and the number of users that chose each choice
	var keyValues = [];

	//transfer the options and user choices into the array from the list object
	for(var key in list){
		keyValues.push([key,list[key]])
	}
	//sort the array so that the highest value (option selected by most users) is in the last element
	keyValues.sort(function compare(kv1,kv2){
		return kv1[1]-kv2[1];
	});

	//send the key of the last element to the html, this is the name of the option that most users selected
	$(".decision-clothing-result").html(keyValues[3][0]);

});

//Listener for the decision-emotion page
firebase.database().ref('decision-emotion').on('value', function(snapshot){
	var list ={
		"Unhappy": 0,
		"Joyful" : 0,
		"Needy" : 0,
		"Frustrated" :0,
		"Apathetic" :0
	}

	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Unhappy"){
			list.Unhappy++;
		}else if (data.val()==="Joyful"){
			list.Joyfull++;
		}else if (data.val()==="Needy"){
			list.Needy++;
		}else if (data.val()=="Frustrated"){
			list.Frustrated++;
		}else if (data.val()=="Apathetic"){
			list.Apathetic++;
		}
	});

	//create an array to hold all of the choices and the number of users that chose each choice
	var keyValues = [];

	//transfer the options and user choices into the array from the list object
	for(var key in list){
		keyValues.push([key,list[key]])
	}
	//sort the array so that the highest value (option selected by most users) is in the last element
	keyValues.sort(function compare(kv1,kv2){
		return kv1[1]-kv2[1];
	});

	//send the key of the last element to the html, this is the name of the option that most users selected
	$(".decision-emotion-result").html(keyValues[4][0]);

});

firebase.database().ref('decision-are-you-finished').on('value', function(snapshot){
	var numberOfNo=0;
	var numberOfYes=0;
	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Yes"){
			numberOfYes++;
		}else{
			numberOfNo++;
		}
	});

	//console.log("yes:" +numberOfYes);
	if(numberOfYes>numberOfNo){
		$(".decision-are-you-finished-result").html("YES");
	}else{
		$(".decision-are-you-finished-result").html("NO");
	}
});

firebase.database().ref('decision-where-david').on('value', function(snapshot){
	var values = [];
	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		values.push([data.key,data.val()])
	});
	var length = values.length;
	var random =  Math.floor((Math.random() * length-1) + 1);

	//console.log(values);
	//console.log(random);
	var name = values[random][0];
	var position = values[random][1]
	$(".decision-where-david-name").html(name);
	$(".decision-where-david-result").html(position);
});

firebase.database().ref('clicks').on('value', function(snapshot){
	var clicks = 0;
	var users = 0;
	snapshot.forEach(function(data){
		clicks = clicks +data.val();
		users += 1;
	});
	//console.log(clicks);
	const maxClicksPerUser = 80;
	var clicksPerUser = 0;
	if (users > 0) {
		clicksPerUser = clicks/users/maxClicksPerUser;
	}
	var level = 0;
	if (clicksPerUser < 0.25){
		speed=4000;
		level = 1;
	} else if (clicksPerUser < 0.5){
		speed=3000;
		level = 2;
	} else if (clicksPerUser < 0.75){
		speed=2500;
		level = 3;
	} else if (clicksPerUser < 1){
		speed=2000;
		level = 4;
	} else{
		speed=1500
		level = 5;
	}

	updateLevelCss(level);

	//console.log(level);

	database.ref('heartbeat/').update({
		level: level
	});
});

firebase.database().ref('decision-want-more').on('value', function(snapshot){
	var numberOfNo=0;
	var numberOfYes=0;
	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Yes"){
			numberOfYes++;
		}else{
			numberOfNo++;
		}
	});

	//console.log("yes:" +numberOfYes);
	if(numberOfYes<numberOfNo){
		$(".decision-want-more-result").html("NO");
	}else{
		$(".decision-want-more-result").html("YES");
	}
});

var previousLevel=0;

function updateLevelCss(level){
	if(level!=previousLevel){
		if(level==1){
			$('.heartbeat-content').addClass('heartbeat-level-1');
		}else if(level==2){
			$('.heartbeat-content').addClass('heartbeat-level-2');
		}else if(level==3){
			$('.heartbeat-content').addClass('heartbeat-level-3');
		}else if(level==4){
			$('.heartbeat-content').addClass('heartbeat-level-4');
		}else if(level==5){
			$('.heartbeat-content').addClass('heartbeat-level-5');
		}
		previousLevel=level;
	}

}

firebase.database().ref('clear').on('value', function(snapshot) {
  var toClear = snapshot.val().clear;
  if(toClear ==='true'){
  	clearInterval(interval);
    $('.view').hide();
  }
});
<commit_msg>Revert "ChangeSpellingOfJoyful"<commit_after>
//Listener for database for decision-are-you-hapy
firebase.database().ref('decision-are-you-happy').on('value', function(snapshot){
	var numberOfNo=0;
	var numberOfYes=0;
	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Yes"){
			numberOfYes++;
		}else{
			numberOfNo++;
		}
	});

	//console.log("yes:" +numberOfYes);
	if(numberOfYes>numberOfNo){
		$(".decision-are-you-happy-result").html("YES");
	}else{
		$(".decision-are-you-happy-result").html("NO");
	}
});

//Listener for the database for decision-clothing
firebase.database().ref('decision-clothing').on('value', function(snapshot){
	var list ={
		"Tie": 0,
		"Shoes" : 0,
		"Jacket" : 0,
		"Trousers" :0,
	}

	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Shoes"){
			list.Shoes++;
		}else if (data.val()==="Tie"){
			list.Tie++;
		}else if (data.val()==="Jacket"){
			list.Jacket++;
		}else if (data.val()=="Trousers"){
			list.Trousers++;
		}
	});

	//create an array to hold all of the choices and the number of users that chose each choice
	var keyValues = [];

	//transfer the options and user choices into the array from the list object
	for(var key in list){
		keyValues.push([key,list[key]])
	}
	//sort the array so that the highest value (option selected by most users) is in the last element
	keyValues.sort(function compare(kv1,kv2){
		return kv1[1]-kv2[1];
	});

	//send the key of the last element to the html, this is the name of the option that most users selected
	$(".decision-clothing-result").html(keyValues[3][0]);

});

//Listener for the decision-emotion page
firebase.database().ref('decision-emotion').on('value', function(snapshot){
	var list ={
		"Unhappy": 0,
		"Joyfull" : 0,
		"Needy" : 0,
		"Frustrated" :0,
		"Apathetic" :0
	}

	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Unhappy"){
			list.Unhappy++;
		}else if (data.val()==="Joyfull"){
			list.Joyfull++;
		}else if (data.val()==="Needy"){
			list.Needy++;
		}else if (data.val()=="Frustrated"){
			list.Frustrated++;
		}else if (data.val()=="Apathetic"){
			list.Apathetic++;
		}
	});

	//create an array to hold all of the choices and the number of users that chose each choice
	var keyValues = [];

	//transfer the options and user choices into the array from the list object
	for(var key in list){
		keyValues.push([key,list[key]])
	}
	//sort the array so that the highest value (option selected by most users) is in the last element
	keyValues.sort(function compare(kv1,kv2){
		return kv1[1]-kv2[1];
	});

	//send the key of the last element to the html, this is the name of the option that most users selected
	$(".decision-emotion-result").html(keyValues[4][0]);

});

firebase.database().ref('decision-are-you-finished').on('value', function(snapshot){
	var numberOfNo=0;
	var numberOfYes=0;
	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Yes"){
			numberOfYes++;
		}else{
			numberOfNo++;
		}
	});

	//console.log("yes:" +numberOfYes);
	if(numberOfYes>numberOfNo){
		$(".decision-are-you-finished-result").html("YES");
	}else{
		$(".decision-are-you-finished-result").html("NO");
	}
});

firebase.database().ref('decision-where-david').on('value', function(snapshot){
	var values = [];
	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		values.push([data.key,data.val()])
	});
	var length = values.length;
	var random =  Math.floor((Math.random() * length-1) + 1);

	//console.log(values);
	//console.log(random);
	var name = values[random][0];
	var position = values[random][1]
	$(".decision-where-david-name").html(name);
	$(".decision-where-david-result").html(position);
});

firebase.database().ref('clicks').on('value', function(snapshot){
	var clicks = 0;
	var users = 0;
	snapshot.forEach(function(data){
		clicks = clicks +data.val();
		users += 1;
	});
	//console.log(clicks);
	const maxClicksPerUser = 80;
	var clicksPerUser = 0;
	if (users > 0) {
		clicksPerUser = clicks/users/maxClicksPerUser;
	}
	var level = 0;
	if (clicksPerUser < 0.25){
		speed=4000;
		level = 1;
	} else if (clicksPerUser < 0.5){
		speed=3000;
		level = 2;
	} else if (clicksPerUser < 0.75){
		speed=2500;
		level = 3;
	} else if (clicksPerUser < 1){
		speed=2000;
		level = 4;
	} else{
		speed=1500
		level = 5;
	}

	updateLevelCss(level);

	//console.log(level);

	database.ref('heartbeat/').update({
		level: level
	});
});

firebase.database().ref('decision-want-more').on('value', function(snapshot){
	var numberOfNo=0;
	var numberOfYes=0;
	snapshot.forEach(function(data){
		//console.log(data.key + ": " +data.val() );
		if(data.val()==="Yes"){
			numberOfYes++;
		}else{
			numberOfNo++;
		}
	});

	//console.log("yes:" +numberOfYes);
	if(numberOfYes<numberOfNo){
		$(".decision-want-more-result").html("NO");
	}else{
		$(".decision-want-more-result").html("YES");
	}
});

var previousLevel=0;

function updateLevelCss(level){
	if(level!=previousLevel){
		if(level==1){
			$('.heartbeat-content').addClass('heartbeat-level-1');
		}else if(level==2){
			$('.heartbeat-content').addClass('heartbeat-level-2');
		}else if(level==3){
			$('.heartbeat-content').addClass('heartbeat-level-3');
		}else if(level==4){
			$('.heartbeat-content').addClass('heartbeat-level-4');
		}else if(level==5){
			$('.heartbeat-content').addClass('heartbeat-level-5');
		}
		previousLevel=level;
	}

}

firebase.database().ref('clear').on('value', function(snapshot) {
  var toClear = snapshot.val().clear;
  if(toClear ==='true'){
  	clearInterval(interval);
    $('.view').hide();
  }
});
<|endoftext|>


<commit_before>var ShareDB = require('sharedb/lib/client');
var Quill = require('quill');
var QuillCursors = require('quill-cursors');
var ReconnectingWebSocket = require('reconnectingwebsocket');
var cursors = require('./cursors');

ShareDB.types.register(require('rich-text').type);

var shareDBSocket = new WebSocket(((location.protocol === 'https:') ? 'wss' : 'ws') + '://' + window.location.host + '/sharedb');

var shareDBConnection = new ShareDB.Connection(shareDBSocket);

var quill = window.quill = new Quill('#editor', {
  theme: 'snow',
  modules: {
    cursors: {
      autoRegisterListener: false
    }
  },
  readOnly: true
});

var doc = shareDBConnection.get('documents', 'foobar');

var cursorsModule = quill.getModule('cursors');

doc.subscribe(function(err) {

  if (err) throw err;

  if (!doc.type)
    doc.create([{
      insert: '\n'
    }], 'rich-text');

  // update editor contents
  quill.setContents(doc.data);

  // local -> server
  quill.on('text-change', function(delta, oldDelta, source) {
    if (source == 'user') {

      if (cursors.localConnection.range && cursors.localConnection.range.length) {
        cursors.localConnection.range.index += cursors.localConnection.range.length;
        cursors.localConnection.range.length = 0;
        cursors.update();
      }

      doc.submitOp(delta, {
        source: quill
      }, function(err) {
        if (err)
          console.error('Submit OP returned an error:', err);
      });

      updateUserList();
    }
  });

  cursorsModule.registerTextChangeListener();

  // server -> local
  doc.on('op', function(op, source) {
    if (source !== quill) {
      quill.updateContents(op);
      updateUserList();
    }
  });

  //
  function sendCursorData(range) {
    cursors.localConnection.range = range;
    cursors.update();
  }

  function updateCursors(source) {
    var activeConnections = {},
      updateAll = Object.keys(cursorsModule.cursors).length == 0;

    cursors.connections.forEach(function(connection) {
      if (connection.id != cursors.localConnection.id) {

        // Update cursor that sent the update, source (or update all if we're initting)
        if ((connection.id == source.id || updateAll) && connection.range) {
          cursorsModule.setCursor(
            connection.id,
            connection.range,
            connection.name,
            connection.color
          );
        }

        // Add to active connections hashtable
        activeConnections[connection.id] = connection;
      }
    });

    // Clear 'disconnected' cursors
    Object.keys(cursorsModule.cursors).forEach(function(cursorId) {
      if (!activeConnections[cursorId]) {
        cursorsModule.removeCursor(cursorId);
      }
    });
  }

  quill.on('selection-change', function(range, oldRange, source) {
    sendCursorData(range);
  });

  document.addEventListener('cursors-update', function(e) {
    // Handle Removed Connections
    e.detail.removedConnections.forEach(function(connection) {
      if (cursorsModule.cursors[connection.id])
        cursorsModule.removeCursor(connection.id);
    });

    updateCursors(e.detail.source);
    updateUserList();
  });

  updateCursors(cursors.localConnection);
});

window.cursors = cursors;

var usernameInputEl = document.getElementById('username-input');
var usersListEl = document.getElementById('users-list');

function updateUserList() {
  // Wipe the slate clean
  usersListEl.innerHTML = null;

  cursors.connections.forEach(function(connection) {
    var userItemEl = document.createElement('li');
    var userNameEl = document.createElement('div');
    var userDataEl = document.createElement('div');

    userNameEl.innerHTML = '' + (connection.name || '(Waiting for username...)') + '';
    userNameEl.classList.add('user-name');

    if (connection.id == cursors.localConnection.id)
      userNameEl.innerHTML += ' (You)';

    if (connection.range) {

      if (connection.id == cursors.localConnection.id)
        connection.range = quill.getSelection();

      userDataEl.innerHTML = [
        '
',
        '
Index: ' + connection.range.index + '
',
        '
Length: ' + connection.range.length + '
',
        '
'
      ].join('');
    } else
      userDataEl.innerHTML = '(Not focusing on editor.)';

    userItemEl.appendChild(userNameEl);
    userItemEl.appendChild(userDataEl);

    userItemEl.style.backgroundColor = connection.color;
    usersListEl.appendChild(userItemEl);
  });
}

usernameInputEl.value = chance.name();
usernameInputEl.focus();
usernameInputEl.select();

document.getElementById('username-form').addEventListener('submit', function(event) {
  cursors.localConnection.name = usernameInputEl.value;
  cursors.update();
  quill.enable();
  document.getElementById('connect-panel').style.display = 'none';
  document.getElementById('users-panel').style.display = 'block';
  event.preventDefault();
  return false;
});
<commit_msg>Add ShareDB connection logging for debug<commit_after>var ShareDB = require('sharedb/lib/client');
var Quill = require('quill');
var QuillCursors = require('quill-cursors');
var ReconnectingWebSocket = require('reconnectingwebsocket');
var cursors = require('./cursors');

ShareDB.types.register(require('rich-text').type);

var shareDBSocket = new WebSocket(((location.protocol === 'https:') ? 'wss' : 'ws') + '://' + window.location.host + '/sharedb');

var shareDBConnection = new ShareDB.Connection(shareDBSocket);

var quill = window.quill = new Quill('#editor', {
  theme: 'snow',
  modules: {
    cursors: {
      autoRegisterListener: false
    }
  },
  readOnly: true
});

var doc = shareDBConnection.get('documents', 'foobar');

var cursorsModule = quill.getModule('cursors');

doc.subscribe(function(err) {

  if (err) throw err;

  if (!doc.type)
    doc.create([{
      insert: '\n'
    }], 'rich-text');

  // update editor contents
  quill.setContents(doc.data);

  // local -> server
  quill.on('text-change', function(delta, oldDelta, source) {
    if (source == 'user') {

      if (cursors.localConnection.range && cursors.localConnection.range.length) {
        cursors.localConnection.range.index += cursors.localConnection.range.length;
        cursors.localConnection.range.length = 0;
        cursors.update();
      }

      doc.submitOp(delta, {
        source: quill
      }, function(err) {
        if (err)
          console.error('Submit OP returned an error:', err);
      });

      updateUserList();
    }
  });

  cursorsModule.registerTextChangeListener();

  // server -> local
  doc.on('op', function(op, source) {
    if (source !== quill) {
      quill.updateContents(op);
      updateUserList();
    }
  });

  //
  function sendCursorData(range) {
    cursors.localConnection.range = range;
    cursors.update();
  }

  function updateCursors(source) {
    var activeConnections = {},
      updateAll = Object.keys(cursorsModule.cursors).length == 0;

    cursors.connections.forEach(function(connection) {
      if (connection.id != cursors.localConnection.id) {

        // Update cursor that sent the update, source (or update all if we're initting)
        if ((connection.id == source.id || updateAll) && connection.range) {
          cursorsModule.setCursor(
            connection.id,
            connection.range,
            connection.name,
            connection.color
          );
        }

        // Add to active connections hashtable
        activeConnections[connection.id] = connection;
      }
    });

    // Clear 'disconnected' cursors
    Object.keys(cursorsModule.cursors).forEach(function(cursorId) {
      if (!activeConnections[cursorId]) {
        cursorsModule.removeCursor(cursorId);
      }
    });
  }

  quill.on('selection-change', function(range, oldRange, source) {
    sendCursorData(range);
  });

  document.addEventListener('cursors-update', function(e) {
    // Handle Removed Connections
    e.detail.removedConnections.forEach(function(connection) {
      if (cursorsModule.cursors[connection.id])
        cursorsModule.removeCursor(connection.id);
    });

    updateCursors(e.detail.source);
    updateUserList();
  });

  updateCursors(cursors.localConnection);
});

window.cursors = cursors;

var usernameInputEl = document.getElementById('username-input');
var usersListEl = document.getElementById('users-list');

function updateUserList() {
  // Wipe the slate clean
  usersListEl.innerHTML = null;

  cursors.connections.forEach(function(connection) {
    var userItemEl = document.createElement('li');
    var userNameEl = document.createElement('div');
    var userDataEl = document.createElement('div');

    userNameEl.innerHTML = '' + (connection.name || '(Waiting for username...)') + '';
    userNameEl.classList.add('user-name');

    if (connection.id == cursors.localConnection.id)
      userNameEl.innerHTML += ' (You)';

    if (connection.range) {

      if (connection.id == cursors.localConnection.id)
        connection.range = quill.getSelection();

      userDataEl.innerHTML = [
        '
',
        '
Index: ' + connection.range.index + '
',
        '
Length: ' + connection.range.length + '
',
        '
'
      ].join('');
    } else
      userDataEl.innerHTML = '(Not focusing on editor.)';

    userItemEl.appendChild(userNameEl);
    userItemEl.appendChild(userDataEl);

    userItemEl.style.backgroundColor = connection.color;
    usersListEl.appendChild(userItemEl);
  });
}

usernameInputEl.value = chance.name();
usernameInputEl.focus();
usernameInputEl.select();

document.getElementById('username-form').addEventListener('submit', function(event) {
  cursors.localConnection.name = usernameInputEl.value;
  cursors.update();
  quill.enable();
  document.getElementById('connect-panel').style.display = 'none';
  document.getElementById('users-panel').style.display = 'block';
  event.preventDefault();
  return false;
});

// DEBUG

shareDBConnection.on('state', function (state, reason) {
  console.log('[sharedb connection] New state:' + event + ' Reason:' + reason);
});
<|endoftext|>


<commit_before>/**
 * L.Control.GeoSearch - search for an address and zoom to it's location
 * L.GeoSearch.Provider.Funda uses funda geocoding service
 * https://github.com/smeijer/L.GeoSearch
 */

var searchType = 0;

function isGuid(value) {
    var regex = /[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/i;
    var match = regex.exec(value);
    return match != null;
}

function descramble(scrambledGetal) {
    if (!scrambledGetal)
        return "";

    var scrambleKey = parseInt(scrambledGetal.charAt(0)); //scramble key is eerste cijfer

    //de rest van het getal gaan we descramble-en
    var strGetal = scrambledGetal.substring(1);
    var cijferArray = [];
    for (var i = 0; i < strGetal.length; i++) {
        cijferArray.push(parseInt(strGetal.charAt(i)));
    }

    //cijfer-shift terug
    for (i = 0; i < strGetal.length; i++) {
        var increment = parseInt((((i % 2) * 2 - 1) * (scrambleKey + i / 2)) % 10);
        cijferArray[i] = (cijferArray[i] - increment + 10) % 10;
    }

    return cijferArray.length === 0 ? 0 : cijferArray.join("");
}

L.GeoSearch.Provider.Funda = L.Class.extend({
    options: {},

    initialize: function(options) {
        options = L.Util.setOptions(this, options);
    },

    GetServiceUrl: function (qry) {
		if (isGuid(qry)) {
			searchType = 1;
			return 'https://crossorigin.me/http://partnerapi.funda.nl/feeds/Aanbod.svc/json/detail/5955322d-ba58-4b91-ae86-e40168d69998/koop/' + qry;
		} else if (/^\d+$/.test(qry)) {
			var globalId = descramble(qry);
			searchType = 2;
			return 'https://crossorigin.me/http://partnerapi.funda.nl/feeds/Aanbod.svc/detail/5955322d-ba58-4b91-ae86-e40168d69998/koop/globalid/' + globalId;
		} else {
			searchType = 0;
			var parameters = L.Util.extend({
				q: qry,
				format: 'json'
			}, this.options);

			return 'http://nominatim.openstreetmap.org/search' + L.Util.getParamString(parameters);
		}
    },

    ParseJSON: function (data) {
        var results = [];

		if(searchType === 1) {
			results.push(new L.GeoSearch.Result(
				data.WGS84_X,
				data.WGS84_Y,
				data.Adres,
				new L.LatLngBounds([
					data.WGS84_X,
					data.WGS84_Y
				]),
				data.Adres
			));
		} else if(searchType === 2) {
			var xmlDoc = new DOMParser().parseFromString(data,"text/xml");
			results.push(new L.GeoSearch.Result(
				xmlDoc.getElementsByTagName("WGS84_X")[0].childNodes[0].nodeValue,
				xmlDoc.getElementsByTagName("WGS84_Y")[0].childNodes[0].nodeValue,
				xmlDoc.getElementsByTagName("Adres")[0].childNodes[0].nodeValue,
				new L.LatLngBounds([
					parseFloat(xmlDoc.getElementsByTagName("WGS84_X")[0].childNodes[0].nodeValue),
					parseFloat(xmlDoc.getElementsByTagName("WGS84_Y")[0].childNodes[0].nodeValue)
				]),
				xmlDoc.getElementsByTagName("Adres")[0].childNodes[0].nodeValue
			));
		} else {
			for (var i = 0; i < data.length; i++) {
				var boundingBox = data[i].boundingbox,
					northEastLatLng = new L.LatLng( boundingBox[1], boundingBox[3] ),
					southWestLatLng = new L.LatLng( boundingBox[0], boundingBox[2] );

				if (data[i].address)
					data[i].address.type = data[i].type;

				results.push(new L.GeoSearch.Result(
					data[i].lon,
					data[i].lat,
					data[i].display_name,
					new L.LatLngBounds([
						northEastLatLng,
						southWestLatLng
					]),
					data[i].address
				));
			}
		}

        return results;
    }
});
<commit_msg>Get the right lat,lon when using tinyId search<commit_after>/**
 * L.Control.GeoSearch - search for an address and zoom to it's location
 * L.GeoSearch.Provider.Funda uses funda geocoding service
 * https://github.com/smeijer/L.GeoSearch
 */

var searchType = 0;

function isGuid(value) {
    var regex = /[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/i;
    var match = regex.exec(value);
    return match != null;
}

function descramble(scrambledGetal) {
    if (!scrambledGetal)
        return "";

    var scrambleKey = parseInt(scrambledGetal.charAt(0)); //scramble key is eerste cijfer

    //de rest van het getal gaan we descramble-en
    var strGetal = scrambledGetal.substring(1);
    var cijferArray = [];
    for (var i = 0; i < strGetal.length; i++) {
        cijferArray.push(parseInt(strGetal.charAt(i)));
    }

    //cijfer-shift terug
    for (i = 0; i < strGetal.length; i++) {
        var increment = parseInt((((i % 2) * 2 - 1) * (scrambleKey + i / 2)) % 10);
        cijferArray[i] = (cijferArray[i] - increment + 10) % 10;
    }

    return cijferArray.length === 0 ? 0 : cijferArray.join("");
}

L.GeoSearch.Provider.Funda = L.Class.extend({
    options: {},

    initialize: function(options) {
        options = L.Util.setOptions(this, options);
    },

    GetServiceUrl: function (qry) {
		if (isGuid(qry)) {
			searchType = 1;
			return 'https://crossorigin.me/http://partnerapi.funda.nl/feeds/Aanbod.svc/json/detail/5955322d-ba58-4b91-ae86-e40168d69998/koop/' + qry;
		} else if (/^\d+$/.test(qry)) {
			var globalId = descramble(qry);
			searchType = 2;
			return 'https://crossorigin.me/http://partnerapi.funda.nl/feeds/Aanbod.svc/detail/5955322d-ba58-4b91-ae86-e40168d69998/koop/globalid/' + globalId;
		} else {
			searchType = 0;
			var parameters = L.Util.extend({
				q: qry,
				format: 'json'
			}, this.options);

			return 'http://nominatim.openstreetmap.org/search' + L.Util.getParamString(parameters);
		}
    },

    ParseJSON: function (data) {
        var results = [];

		if(searchType === 1) {
			results.push(new L.GeoSearch.Result(
				data.WGS84_X,
				data.WGS84_Y,
				data.Adres,
				new L.LatLngBounds([
					data.WGS84_X,
					data.WGS84_Y
				]),
				data.Adres
			));
		} else if(searchType === 2) {
			var xmlDoc = new DOMParser().parseFromString(data,"text/xml");
			results.push(new L.GeoSearch.Result(
				xmlDoc.getElementsByTagName("WGS84_X")[xmlDoc.getElementsByTagName("WGS84_X").length - 1].childNodes[0].nodeValue,
				xmlDoc.getElementsByTagName("WGS84_Y")[xmlDoc.getElementsByTagName("WGS84_Y").length - 1].childNodes[0].nodeValue,
				xmlDoc.getElementsByTagName("Adres")[0].childNodes[0].nodeValue,
				new L.LatLngBounds([
					parseFloat(xmlDoc.getElementsByTagName("WGS84_X")[xmlDoc.getElementsByTagName("WGS84_X").length - 1].childNodes[0].nodeValue),
					parseFloat(xmlDoc.getElementsByTagName("WGS84_Y")[xmlDoc.getElementsByTagName("WGS84_Y").length - 1].childNodes[0].nodeValue)
				]),
				xmlDoc.getElementsByTagName("Adres")[0].childNodes[0].nodeValue
			));
		} else {
			for (var i = 0; i < data.length; i++) {
				var boundingBox = data[i].boundingbox,
					northEastLatLng = new L.LatLng( boundingBox[1], boundingBox[3] ),
					southWestLatLng = new L.LatLng( boundingBox[0], boundingBox[2] );

				if (data[i].address)
					data[i].address.type = data[i].type;

				results.push(new L.GeoSearch.Result(
					data[i].lon,
					data[i].lat,
					data[i].display_name,
					new L.LatLngBounds([
						northEastLatLng,
						southWestLatLng
					]),
					data[i].address
				));
			}
		}

        return results;
    }
});
<|endoftext|>