<commit_before>/*!
 * Copyright 2013 Sakai Foundation (SF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://www.osedu.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

define(['jquery'], function ($) {
    (function() {

        /**
         * Show or hide the list options when clicking the page title toggle
         */
        $(document).on('click', '.oae-list-options-toggle', function() {
            // Get the list container, so we don't end up changing state in other lists
            var $list = $(this).parents('.oae-list-options').parent();
            var $listOptionActions = $('.oae-list-options-actions', $list);
            // Hide the list options if they are currently showing. Show the list options
            // if they are currently hidden
            if ($listOptionActions.is(':visible')) {
                $listOptionActions.slideUp(200);
            } else {
                $listOptionActions.slideDown(200);
            }
            // Toggle the caret icon in the page title
            $(this).find('i').toggleClass('icon-caret-down icon-caret-up');
        });

        /**
         * Select or deselect all elements when clicking the select all checkbox in the
         * list options
         */
        $(document).on('change', '.oae-list-selectall', function() {
            // Get the list container, so we don't end up changing state in other lists
            var $list = $(this).parents('.oae-list-options').parent();
            // Check or uncheck all checkboxes in the corresponding list
            var checked = $(this).is(':checked');
            var $listCheckboxes = $('.oae-list input[type="checkbox"]', $list);
            $listCheckboxes.prop('checked', checked);
            // Enable or disable the list option action buttons. We only change the state
            // when there is at least 1 item in the list that can be checked.
            if ($listCheckboxes.length > 0) {
                $('.oae-list-options-actions > .btn', $list).prop('disabled', !checked);
            }
        });

        /**
         * Switch the view mode between grid view, details view and compact view
         */
        $(document).on('click', '.oae-list-options .btn-group button', function() {
            // Get the list container, so we don't end up changing state in other lists
            var $list = $(this).parents('.oae-list-options').parent();
            // Update the list view switch buttons
            $('.oae-list-options .btn-group button', $list).removeClass('active');
            $(this).addClass('active');
            // Change the view type in the list itself
            $('.oae-list', $list).removeClass('oae-list-grid oae-list-details oae-list-compact');
            $('.oae-list', $list).addClass($(this).attr('data-type'));
        });

        /**
         * When at least 1 checkbox inside of the list is checked, the list options are shown and
         * the list option action buttons are enabled. When no checkboxes are checked in the list,
         * the list options are hidden and the list option actions buttons are hidden
         */
        $(document).on('click', '.oae-list input[type="checkbox"]', function() {
            // Get the list container, so we don't end up changing state in other lists
            var $list = $(this).parents('.oae-list').parent();
            var $listOptionActions = $('.oae-list-options-actions', $list);

            // Hide the list options when no checkboxes are checked anymore. Show the list options
            // when at least 1 checkbox is checked
            var totalChecked = $('.oae-list input[type="checkbox"]:visible:checked', $list).length;
            if ((totalChecked > 0 && !$listOptionActions.is(':visible')) ||
                (totalChecked === 0 && $listOptionActions.is(':visible'))) {
                $('.oae-list-options-toggle', $list).click();
            }
            // Enable or disable the list option action buttons
            $('.oae-list-options-actions > .btn', $list).prop('disabled', (totalChecked === 0));
        });

    })();
});
<commit_msg>Fixed list checking across list views<commit_after>/*!
 * Copyright 2013 Sakai Foundation (SF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://www.osedu.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

define(['jquery'], function ($) {
    (function() {

        /**
         * Show or hide the list options when clicking the page title toggle
         */
        $(document).on('click', '.oae-list-options-toggle', function() {
            // Get the list container, so we don't end up changing state in other lists
            var $list = $(this).parents('.oae-list-options').parent();
            var $listOptionActions = $('.oae-list-options-actions', $list);
            // Hide the list options if they are currently showing. Show the list options
            // if they are currently hidden
            if ($listOptionActions.is(':visible')) {
                $listOptionActions.slideUp(200);
            } else {
                $listOptionActions.slideDown(200);
            }
            // Toggle the caret icon in the page title
            $(this).find('i').toggleClass('icon-caret-down icon-caret-up');
        });

        /**
         * Select or deselect all elements when clicking the select all checkbox in the
         * list options
         */
        $(document).on('change', '.oae-list-selectall', function() {
            // Get the list container, so we don't end up changing state in other lists
            var $list = $(this).parents('.oae-list-options').parent();
            // Check or uncheck all checkboxes in the corresponding list
            var checked = $(this).is(':checked');
            var $listCheckboxes = $('.oae-list input[type="checkbox"]', $list);
            $listCheckboxes.prop('checked', checked);
            // Enable or disable the list option action buttons. We only change the state
            // when there is at least 1 item in the list that can be checked.
            if ($listCheckboxes.length > 0) {
                $('.oae-list-options-actions > .btn', $list).prop('disabled', !checked);
            }
        });

        /**
         * Switch the view mode between grid view, details view and compact view
         */
        $(document).on('click', '.oae-list-options .btn-group button', function() {
            // Get the list container, so we don't end up changing state in other lists
            var $list = $(this).parents('.oae-list-options').parent();
            // Update the list view switch buttons
            $('.oae-list-options .btn-group button', $list).removeClass('active');
            $(this).addClass('active');
            // Change the view type in the list itself
            $('.oae-list', $list).removeClass('oae-list-grid oae-list-details oae-list-compact');
            $('.oae-list', $list).addClass($(this).attr('data-type'));
        });

        /**
         * When a checkbox is checked/unchecked, we make sure that its corresponding checkbox in the
         * other views are checked as well. When at least 1 list item is checked, the list options
         * are shown and the list option action buttons are enabled. When no checkboxes are checked
         * in the list, the list options are hidden and the list option actions buttons are disabled.
         */
        $(document).on('click', '.oae-list input[type="checkbox"]', function() {
            // Get the list item the checkbox corresponds to and make sure the other views have the
            // same checked status
            $listItem = $(this).parents('li');
            $('input[type="checkbox"]', $listItem).prop('checked', $(this).is(':checked'))

            // Get the list container, so we don't end up changing state in other lists
            var $list = $(this).parents('.oae-list').parent();
            var $listOptionActions = $('.oae-list-options-actions', $list);

            // Hide the list options when no checkboxes are checked anymore. Show the list options
            // when at least 1 checkbox is checked
            var totalChecked = $('.oae-list input[type="checkbox"]:visible:checked', $list).length;
            if ((totalChecked > 0 && !$listOptionActions.is(':visible')) ||
                (totalChecked === 0 && $listOptionActions.is(':visible'))) {
                $('.oae-list-options-toggle', $list).click();
            }
            // Enable or disable the list option action buttons
            $('.oae-list-options-actions > .btn', $list).prop('disabled', (totalChecked === 0));
        });

    })();
});
<|endoftext|>


<commit_before>const momentTZ = require('moment-timezone');
require('moment-duration-format');
// const {inspect} = require('util');
const Command = require('../base/Command');

class Shardtimes extends Command {
    constructor(client) {
        super(client, {
            name: 'shardtimes',
            aliases: ['shard', 'st', 'payout', 'po'],
            guildOnly: true,
            category: 'Misc'
        });
    }

    async run(client, message, args, options) {
        const level = options.level;
        // Shard ID will be guild.id-channel.id
        const shardID = `${message.guild.id}-${message.channel.id}`;

        const exists = await client.database.models.shardtimes.findOne({where: {id: shardID}})
            .then(token => token != null)
            .then(isUnique => isUnique);

        let shardTimes = {};

        if (!exists) {
            await client.database.models.shardtimes.create({
                id: shardID,
                times: shardTimes
            });
        } else {
            const tempT = await client.database.models.shardtimes.findOne({where: {id: shardID}});
            shardTimes = tempT.dataValues.times;
        }

        let timeToAdd = 18;
        if (args.includes('-ship')) {
            args.splice(args.indexOf('-ship'), 1);
            timeToAdd = 19;
        }

        let [action, userID, timezone, ...flag] = args;  // eslint-disable-line prefer-const

        if (action === 'add') {
            // If it's an admin, let them register other users, else let em register themselves
            // To add someone ;shardinfo <me|@mention|discordID> <timezone> [flag/emoji]
            let type = 'id';
            if (userID !== message.author.id && userID !== message.author.username && level < 3) {
                return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_MISSING_PERMS'));
            }
            if (userID === 'me') {
                userID = message.author.id;
            } else if (userID.match(/\d{17,18}/)) {
                userID = userID.replace(/[^\d]*/g, '');
            } else {
                type = 'name';
            }

            if (!timezone) {
                // Grumble that they need a timezone, then give the wiki list
                return message.channel.send(message.language.get('COMMAND_SHARDTIMES_MISSING_TIMEZONE'));
            } else {
                if (!momentTZ.tz.zone(timezone)) { // Valid time zone?
                    // Grumble that it's an invalid tz
                    return message.channel.send(message.language.get('COMMAND_SHARDTIMES_INVALID_TIMEZONE'));
                }
            }
            if (flag.length > 0) {
                flag = flag[0];
                if (flag.match(/<:.+:\d+>/)) {
                    flag = flag.replace(/<:.*:/, '').replace(/>$/, '');
                }
            } else {
                flag = '';
            }
            let tempUser = null;
            if (exists && shardTimes[`${userID}`]) {
                tempUser = shardTimes[`${userID}`];
            }
            shardTimes[`${userID}`] = {
                "type": type,
                "timezone": timezone,
                "flag": flag
            };
            await client.database.models.shardtimes.update({times: shardTimes}, {where: {id: shardID}})
                .then(() => {
                    if (tempUser) {
                        return message.channel.send(message.language.get('COMMAND_SHARDTIMES_USER_MOVED', tempUser.timezone, shardTimes[`${userID}`].timezone));
                    }
                    return message.channel.send(message.language.get('COMMAND_SHARDTIMES_USER_ADDED'));
                })
                .catch(() => {
                    return message.channel.send(message.language.get('COMMAND_SHARDTIMES_USER_NOT_ADDED'));
                });
        } else if (action === 'remove' || action === 'rem') {
            // Get the json object, remove the user if available, then resave if it changed
            if (userID !== message.author.id && userID !== message.author.username && level < 3) {
                return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_MISSING_PERMS'));
            }
            if (userID === 'me') {
                userID = message.author.id;
            } else if (userID.match(/\d{17,18}/)) {
                // If they are trying to remove someone else and they don't have the right perms, stop em
                userID = userID.replace(/[\\|<|@|!]*(\d{17,18})[>]*/g,'$1');
            }
            if (shardTimes.hasOwnProperty(userID)) {
                delete shardTimes[userID];
                await client.database.models.shardtimes.update({times: shardTimes}, {where: {id: shardID}})
                    .then(() => {
                        return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_SUCCESS'));
                    })
                    .catch(() => {
                        return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_FAIL'));
                    });
            } else {
                return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_MISSING'));
            }
        } else {
            // View the shard table
            const shardOut = {};
            Object.keys(shardTimes).forEach(user => {
                const diff = timeTil(shardTimes[user].timezone, timeToAdd);
                if (shardOut.hasOwnProperty(diff)) {
                    shardOut[diff].push(user);
                } else {
                    shardOut[diff] = [user];
                }
            });

            const sortedShardTimes = Object.keys(shardOut).sort((a, b) => momentTZ(a, 'HH:mm').diff(momentTZ(b, 'HH:mm')));

            const fields = [];
            sortedShardTimes.forEach(time => {
                const times = [];
                shardOut[time].forEach(user => {
                    let userFlag = client.emojis.get(shardTimes[user].flag);
                    if (!userFlag) {
                        userFlag = shardTimes[user].flag;
                    }
                    const maxLen = 20;
                    let uName = 'Unknown';
                    if (!shardTimes[user].type || shardTimes[user].type === 'id') {
                        const thisUser = message.guild.members.get(user);
                        const userName = thisUser ? `${thisUser.displayName}` : `${client.users.get(user) ? client.users.get(user).username : 'Unknown'}`;
                        uName = '**' + (userName.length > maxLen ? userName.substring(0, maxLen) : userName) + '**';
                    } else {
                        // Type is name, don't try looking it up
                        const userName = user;
                        uName = userName.length > maxLen ? userName.substring(0, maxLen) : userName;
                    }
                    times.push(`${shardTimes[user].flag != '' ? userFlag : ""}${uName}`);
                });
                fields.push({
                    "name": time,
                    value: times.join('\n'),
                    "inline": true
                });
            });
            return message.channel.send({
                embed: {
                    "author": {
                        "name": message.language.get('COMMAND_SHARDTIMES_SHARD_HEADER')
                    },
                    "fields": fields
                }
            });
        }

        function timeTil(zone, timeToAdd) {
            let targetTime;
            if (momentTZ.tz(zone).unix() < momentTZ.tz(zone).startOf("day").add(timeToAdd, 'h').unix()) {
                // If it's later today
                targetTime = momentTZ.tz(zone).startOf("day").add(timeToAdd, 'h');
            } else {
                // If it's already passed for the day
                targetTime = momentTZ.tz(zone).startOf("day").add(1, 'd').add(timeToAdd, 'h');
            }
            return momentTZ.duration(targetTime.diff(momentTZ.tz(zone))).format('HH:mm', { trim: false });
        }
    }
}

module.exports = Shardtimes;

<commit_msg>Bug fix with shards command<commit_after>const momentTZ = require('moment-timezone');
require('moment-duration-format');
// const {inspect} = require('util');
const Command = require('../base/Command');

class Shardtimes extends Command {
    constructor(client) {
        super(client, {
            name: 'shardtimes',
            aliases: ['shard', 'st', 'payout', 'po'],
            guildOnly: true,
            category: 'Misc'
        });
    }

    async run(client, message, args, options) {
        const level = options.level;
        // Shard ID will be guild.id-channel.id
        const shardID = `${message.guild.id}-${message.channel.id}`;

        const exists = await client.database.models.shardtimes.findOne({where: {id: shardID}})
            .then(token => token != null)
            .then(isUnique => isUnique);

        let shardTimes = {};

        if (!exists) {
            await client.database.models.shardtimes.create({
                id: shardID,
                times: shardTimes
            });
        } else {
            const tempT = await client.database.models.shardtimes.findOne({where: {id: shardID}});
            shardTimes = tempT.dataValues.times;
        }

        let timeToAdd = 18;
        if (args.includes('-ship')) {
            args.splice(args.indexOf('-ship'), 1);
            timeToAdd = 19;
        }

        let [action, userID, timezone, ...flag] = args;  // eslint-disable-line prefer-const

        if (action === 'add') {
            // If it's an admin, let them register other users, else let em register themselves
            // To add someone ;shardinfo <me|@mention|discordID> <timezone> [flag/emoji]
            let type = 'id';
            if (userID === 'me') {
                userID = message.author.id;
            } else if (userID.match(/\d{17,18}/)) {
                userID = userID.replace(/[^\d]*/g, '');
            } else {
                type = 'name';
            }
            if (userID !== message.author.id && userID !== message.author.username && level < 3) {
                return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_MISSING_PERMS'));
            }

            if (!timezone) {
                // Grumble that they need a timezone, then give the wiki list
                return message.channel.send(message.language.get('COMMAND_SHARDTIMES_MISSING_TIMEZONE'));
            } else {
                if (!momentTZ.tz.zone(timezone)) { // Valid time zone?
                    // Grumble that it's an invalid tz
                    return message.channel.send(message.language.get('COMMAND_SHARDTIMES_INVALID_TIMEZONE'));
                }
            }
            if (flag.length > 0) {
                flag = flag[0];
                if (flag.match(/<:.+:\d+>/)) {
                    flag = flag.replace(/<:.*:/, '').replace(/>$/, '');
                }
            } else {
                flag = '';
            }
            let tempUser = null;
            if (exists && shardTimes[`${userID}`]) {
                tempUser = shardTimes[`${userID}`];
            }
            shardTimes[`${userID}`] = {
                "type": type,
                "timezone": timezone,
                "flag": flag
            };
            await client.database.models.shardtimes.update({times: shardTimes}, {where: {id: shardID}})
                .then(() => {
                    if (tempUser) {
                        return message.channel.send(message.language.get('COMMAND_SHARDTIMES_USER_MOVED', tempUser.timezone, shardTimes[`${userID}`].timezone));
                    }
                    return message.channel.send(message.language.get('COMMAND_SHARDTIMES_USER_ADDED'));
                })
                .catch(() => {
                    return message.channel.send(message.language.get('COMMAND_SHARDTIMES_USER_NOT_ADDED'));
                });
        } else if (action === 'remove' || action === 'rem') {
            // Get the json object, remove the user if available, then resave if it changed
            if (userID !== message.author.id && userID !== message.author.username && level < 3) {
                return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_MISSING_PERMS'));
            }
            if (userID === 'me') {
                userID = message.author.id;
            } else if (userID.match(/\d{17,18}/)) {
                // If they are trying to remove someone else and they don't have the right perms, stop em
                userID = userID.replace(/[\\|<|@|!]*(\d{17,18})[>]*/g,'$1');
            }
            if (shardTimes.hasOwnProperty(userID)) {
                delete shardTimes[userID];
                await client.database.models.shardtimes.update({times: shardTimes}, {where: {id: shardID}})
                    .then(() => {
                        return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_SUCCESS'));
                    })
                    .catch(() => {
                        return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_FAIL'));
                    });
            } else {
                return message.channel.send(message.language.get('COMMAND_SHARDTIMES_REM_MISSING'));
            }
        } else {
            // View the shard table
            const shardOut = {};
            Object.keys(shardTimes).forEach(user => {
                const diff = timeTil(shardTimes[user].timezone, timeToAdd);
                if (shardOut.hasOwnProperty(diff)) {
                    shardOut[diff].push(user);
                } else {
                    shardOut[diff] = [user];
                }
            });

            const sortedShardTimes = Object.keys(shardOut).sort((a, b) => momentTZ(a, 'HH:mm').diff(momentTZ(b, 'HH:mm')));

            const fields = [];
            sortedShardTimes.forEach(time => {
                const times = [];
                shardOut[time].forEach(user => {
                    let userFlag = client.emojis.get(shardTimes[user].flag);
                    if (!userFlag) {
                        userFlag = shardTimes[user].flag;
                    }
                    const maxLen = 20;
                    let uName = 'Unknown';
                    if (!shardTimes[user].type || shardTimes[user].type === 'id') {
                        const thisUser = message.guild.members.get(user);
                        const userName = thisUser ? `${thisUser.displayName}` : `${client.users.get(user) ? client.users.get(user).username : 'Unknown'}`;
                        uName = '**' + (userName.length > maxLen ? userName.substring(0, maxLen) : userName) + '**';
                    } else {
                        // Type is name, don't try looking it up
                        const userName = user;
                        uName = userName.length > maxLen ? userName.substring(0, maxLen) : userName;
                    }
                    times.push(`${shardTimes[user].flag != '' ? userFlag : ""}${uName}`);
                });
                fields.push({
                    "name": time,
                    value: times.join('\n'),
                    "inline": true
                });
            });
            return message.channel.send({
                embed: {
                    "author": {
                        "name": message.language.get('COMMAND_SHARDTIMES_SHARD_HEADER')
                    },
                    "fields": fields
                }
            });
        }

        function timeTil(zone, timeToAdd) {
            let targetTime;
            if (momentTZ.tz(zone).unix() < momentTZ.tz(zone).startOf("day").add(timeToAdd, 'h').unix()) {
                // If it's later today
                targetTime = momentTZ.tz(zone).startOf("day").add(timeToAdd, 'h');
            } else {
                // If it's already passed for the day
                targetTime = momentTZ.tz(zone).startOf("day").add(1, 'd').add(timeToAdd, 'h');
            }
            return momentTZ.duration(targetTime.diff(momentTZ.tz(zone))).format('HH:mm', { trim: false });
        }
    }
}

module.exports = Shardtimes;

<|endoftext|>


<commit_before>module.exports = Cmds.addCommand({
    cmds: [';mute ', ';mutehammer ', ';arrest '],

    requires: {
        guild: true,
        loud: false,
    },

    desc: 'Mute a user (in all guild channels) and add the mute to their record',

    args: '([user_resolvable]) (OPTIONAL: [mute_length]) (OPTIONAL: [mute_length_format]) (OPTIONAL: [reason])',

    example: 'vae 2 minutes being weird',

    // /////////////////////////////////////////////////////////////////////////////////////////

    func: async (cmd, args, msgObj, speaker, channel, guild) => {
        args = args.trim();

        const data = Util.getDataFromString(
            args,
            [
                [
                    function (str) {
                        return Util.getMemberByMixed(str, guild) || Util.isId(str);
                    },
                ],
                [
                    function (str) {
                        return Util.matchWholeNumber(str);
                    },
                ],
                [
                    function (str) {
                        let timeMult;
                        str = str.toLowerCase();
                        if (str.substr(str.length - 1, 1) == 's' && str.length > 2) str = str.substr(0, str.length - 1);
                        if (str == 'millisecond' || str == 'ms') timeMult = 1 / 60 / 60 / 1000;
                        if (str == 'second' || str == 's' || str == 'sec') timeMult = 1 / 60 / 60;
                        if (str == 'minute' || str == 'm' || str == 'min') timeMult = 1 / 60;
                        if (str == 'hour' || str == 'h') timeMult = 1;
                        if (str == 'day' || str == 'd') timeMult = 24;
                        if (str == 'week' || str == 'w') timeMult = 24 * 7;
                        if (str == 'month' || str == 'mo') timeMult = 24 * 30.42;
                        if (str == 'year' || str == 'y') timeMult = 24 * 365.2422;
                        return timeMult;
                    },
                ],
            ],
            true,
        );

        if (!data) {
            return Util.sendEmbed(channel, 'Mute Failed', 'User not found', Util.makeEmbedFooter(speaker), null, colGreen, null);
        }

        Util.log(`Change Arg Data: ${data}`);

        const member = data[0];
        const mult = data[2] || 1 / 60;
        const time = data[1] ? data[1] * 1000 * 60 * 60 * mult : null;
        const reason = data[3];

        let success;

        /* if (speaker.id == '119203482598244356') {
            member = speaker;
            speaker = speaker.displayName;
        } */

        if (Admin.checkMuted(guild, member.id)) {
            Util.print(
                channel,
                `<@${
                    speaker.id
                }> Are you sure you want to re-mute that guy instead of using \`;changemute\`...?\n\n You only need to re-mute if it's a separate offense.`,
            );

            const isResponse = msgObjTemp => msgObjTemp.author.id == speaker.id;

            channel
                .awaitMessages(isResponse, { max: 1, time: 1000 * 25, errors: ['time'] })
                .then(async (collected) => {
                    const response = collected.first();
                    const responseMsg = response.content;

                    if (/y[aeiouy]+?[shp]|y[aeiy]+?\b|\by\b/.test(responseMsg.toLowerCase())) {
                        Util.print(channel, 'Well okay then, your will is my command...');
                        success = await Admin.addMute(guild, channel, member, speaker, { time, reason });
                    } else {
                        Util.print(channel, 'Guess you made a mistake eh... Well fine, your request has been cancelled.');
                    }
                })
                .catch(() => {
                    Util.print(
                        channel,
                        `What a drag, I've been waiting far too long for an answer <@${speaker.id}>, snails get stitches...`,
                    );
                    Admin.addMute(guild, channel, speaker, 'System', { time: 1000 * 60 * 1.5, reason: 'Snails get stitches' });
                });
        } else {
            success = await Admin.addMute(guild, channel, member, speaker, { time, reason });
        }

        if (time === null && success === true) {
            Util.print(
                channel,
                `This user was muted for his default mute time (based on his mute history), do you want to change it <@${
                    speaker.id
                }>? If you do, just tell me the new time now...`,
            );

            const isResponse = msgObjTemp => msgObjTemp.author.id == speaker.id;

            channel
                .awaitMessages(isResponse, { max: 1, time: 1000 * 25, errors: ['time'] })
                .then((collected) => {
                    const response = collected.first();
                    let responseMsg = response.content;

                    responseMsg = responseMsg
                        .replace(/<@.?\d+?>\s*/g, '')
                        .replace(/[^\sa-z0-9]+/gi, '')
                        .trim();

                    if (/\bno|no\b|\bcancel|\bkeep|\bdont|^n$/i.test(responseMsg)) {
                        Util.print(channel, 'Got it!');
                        return;
                    }

                    const data2 = Util.getDataFromString(
                        responseMsg,
                        [
                            [
                                function (str) {
                                    return Util.matchWholeNumber(str);
                                },
                            ],
                            [
                                function (str) {
                                    let timeMult;
                                    str = str.toLowerCase();
                                    if (str.substr(str.length - 1, 1) == 's' && str.length > 2) str = str.substr(0, str.length - 1);
                                    if (str == 'millisecond' || str == 'ms') timeMult = 1 / 60 / 60 / 1000;
                                    if (str == 'second' || str == 's' || str == 'sec') timeMult = 1 / 60 / 60;
                                    if (str == 'minute' || str == 'm' || str == 'min') timeMult = 1 / 60;
                                    if (str == 'hour' || str == 'h') timeMult = 1;
                                    if (str == 'day' || str == 'd') timeMult = 24;
                                    if (str == 'week' || str == 'w') timeMult = 24 * 7;
                                    if (str == 'month' || str == 'mo') timeMult = 24 * 30.42;
                                    if (str == 'year' || str == 'y') timeMult = 24 * 365.2422;
                                    return timeMult;
                                },
                            ],
                        ],
                        true,
                    );

                    if (!data2) return;

                    Util.log(`Change Arg Data New: ${data2}`);

                    const mult2 = data2[1] || 1 / 60;
                    const time2 = data2[0] ? data2[0] * 1000 * 60 * 60 * mult2 : null;

                    if (time2 == null) return;

                    Admin.changeMute(guild, channel, member, speaker, { time: time2 });
                })
                .catch(console.log);
        }

        return true;
    },
});
<commit_msg>Pronoun<commit_after>module.exports = Cmds.addCommand({
    cmds: [';mute ', ';mutehammer ', ';arrest '],

    requires: {
        guild: true,
        loud: false,
    },

    desc: 'Mute a user (in all guild channels) and add the mute to their record',

    args: '([user_resolvable]) (OPTIONAL: [mute_length]) (OPTIONAL: [mute_length_format]) (OPTIONAL: [reason])',

    example: 'vae 2 minutes being weird',

    // /////////////////////////////////////////////////////////////////////////////////////////

    func: async (cmd, args, msgObj, speaker, channel, guild) => {
        args = args.trim();

        const data = Util.getDataFromString(
            args,
            [
                [
                    function (str) {
                        return Util.getMemberByMixed(str, guild) || Util.isId(str);
                    },
                ],
                [
                    function (str) {
                        return Util.matchWholeNumber(str);
                    },
                ],
                [
                    function (str) {
                        let timeMult;
                        str = str.toLowerCase();
                        if (str.substr(str.length - 1, 1) == 's' && str.length > 2) str = str.substr(0, str.length - 1);
                        if (str == 'millisecond' || str == 'ms') timeMult = 1 / 60 / 60 / 1000;
                        if (str == 'second' || str == 's' || str == 'sec') timeMult = 1 / 60 / 60;
                        if (str == 'minute' || str == 'm' || str == 'min') timeMult = 1 / 60;
                        if (str == 'hour' || str == 'h') timeMult = 1;
                        if (str == 'day' || str == 'd') timeMult = 24;
                        if (str == 'week' || str == 'w') timeMult = 24 * 7;
                        if (str == 'month' || str == 'mo') timeMult = 24 * 30.42;
                        if (str == 'year' || str == 'y') timeMult = 24 * 365.2422;
                        return timeMult;
                    },
                ],
            ],
            true,
        );

        if (!data) {
            return Util.sendEmbed(channel, 'Mute Failed', 'User not found', Util.makeEmbedFooter(speaker), null, colGreen, null);
        }

        Util.log(`Change Arg Data: ${data}`);

        const member = data[0];
        const mult = data[2] || 1 / 60;
        const time = data[1] ? data[1] * 1000 * 60 * 60 * mult : null;
        const reason = data[3];

        let success;

        /* if (speaker.id == '119203482598244356') {
            member = speaker;
            speaker = speaker.displayName;
        } */

        if (Admin.checkMuted(guild, member.id)) {
            Util.print(
                channel,
                `<@${
                    speaker.id
                }> Are you sure you want to re-mute that guy instead of using \`;changemute\`...?\n\n You only need to re-mute if it's a separate offense.`,
            );

            const isResponse = msgObjTemp => msgObjTemp.author.id == speaker.id;

            channel
                .awaitMessages(isResponse, { max: 1, time: 1000 * 25, errors: ['time'] })
                .then(async (collected) => {
                    const response = collected.first();
                    const responseMsg = response.content;

                    if (/y[aeiouy]+?[shp]|y[aeiy]+?\b|\by\b/.test(responseMsg.toLowerCase())) {
                        Util.print(channel, 'Well okay then, your will is my command...');
                        success = await Admin.addMute(guild, channel, member, speaker, { time, reason });
                    } else {
                        Util.print(channel, 'Guess you made a mistake eh... Well fine, your request has been cancelled.');
                    }
                })
                .catch(() => {
                    Util.print(
                        channel,
                        `What a drag, I've been waiting far too long for an answer <@${speaker.id}>, snails get stitches...`,
                    );
                    Admin.addMute(guild, channel, speaker, 'System', { time: 1000 * 60 * 1.5, reason: 'Snails get stitches' });
                });
        } else {
            success = await Admin.addMute(guild, channel, member, speaker, { time, reason });
        }

        if (time === null && success === true) {
            Util.print(
                channel,
                `This user was muted for their default mute time (based on their mute history), do you want to change it <@${
                    speaker.id
                }>? If you do, just tell me the new time now...`,
            );

            const isResponse = msgObjTemp => msgObjTemp.author.id == speaker.id;

            channel
                .awaitMessages(isResponse, { max: 1, time: 1000 * 25, errors: ['time'] })
                .then((collected) => {
                    const response = collected.first();
                    let responseMsg = response.content;

                    responseMsg = responseMsg
                        .replace(/<@.?\d+?>\s*/g, '')
                        .replace(/[^\sa-z0-9]+/gi, '')
                        .trim();

                    if (/\bno|no\b|\bcancel|\bkeep|\bdont|^n$/i.test(responseMsg)) {
                        Util.print(channel, 'Got it!');
                        return;
                    }

                    const data2 = Util.getDataFromString(
                        responseMsg,
                        [
                            [
                                function (str) {
                                    return Util.matchWholeNumber(str);
                                },
                            ],
                            [
                                function (str) {
                                    let timeMult;
                                    str = str.toLowerCase();
                                    if (str.substr(str.length - 1, 1) == 's' && str.length > 2) str = str.substr(0, str.length - 1);
                                    if (str == 'millisecond' || str == 'ms') timeMult = 1 / 60 / 60 / 1000;
                                    if (str == 'second' || str == 's' || str == 'sec') timeMult = 1 / 60 / 60;
                                    if (str == 'minute' || str == 'm' || str == 'min') timeMult = 1 / 60;
                                    if (str == 'hour' || str == 'h') timeMult = 1;
                                    if (str == 'day' || str == 'd') timeMult = 24;
                                    if (str == 'week' || str == 'w') timeMult = 24 * 7;
                                    if (str == 'month' || str == 'mo') timeMult = 24 * 30.42;
                                    if (str == 'year' || str == 'y') timeMult = 24 * 365.2422;
                                    return timeMult;
                                },
                            ],
                        ],
                        true,
                    );

                    if (!data2) return;

                    Util.log(`Change Arg Data New: ${data2}`);

                    const mult2 = data2[1] || 1 / 60;
                    const time2 = data2[0] ? data2[0] * 1000 * 60 * 60 * mult2 : null;

                    if (time2 == null) return;

                    Admin.changeMute(guild, channel, member, speaker, { time: time2 });
                })
                .catch(console.log);
        }

        return true;
    },
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 raznara
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

var cuestionarioView = function (strClase) {
    this.clase = strClase;
};
cuestionarioView.prototype = new view('cuestionario');
cuestionarioView.prototype.getClassNameCuestionario = function () {
    return this.getClassName() + "Vista";
};
var oCuestionarioView = new cuestionarioView('cuestionario');
cuestionarioView.prototype.loadButtons = function (id) {
//
    var botonera = "";
    botonera += '

';
    botonera += '';
    botonera += '';
    botonera += '';
    botonera += '

';
    return botonera;
};
cuestionarioView.prototype.getBodyPageTable = function (page, fieldNames, visibleFields, tdbuttons) {
    var thisObject = this;
    var tabla = "";
    $.each(page, function (index, value) {
        tabla += '
';
        var numField = 0;
        var id;
        var strClaveAjena;
        $.each(fieldNames, function (index, valor) {
            if ("id" == valor) {
                id = value[valor];
            }
            ;
            numField++;
            if (numField <= visibleFields) {
                tabla += '';
                if ("tipo" == valor) {
                    tabla += '';
                    tabla += thisObject.printValue(value, valor, true);
                    tabla += "";
                } else {
                    tabla += thisObject.printValue(value, valor, true);
                }
                tabla += '	';
            }
        });
        tabla += '';
        tabla += tdbuttons(id);
        tabla += '	';
        tabla += '
';
    });
    return tabla;
};<commit_msg>Boton de hacer formulario parte 1<commit_after>/*
 * Copyright (C) 2014 raznara
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

var cuestionarioView = function (strClase) {
    this.clase = strClase;
};
cuestionarioView.prototype = new view('cuestionario');
cuestionarioView.prototype.getClassNameCuestionario = function () {
    return this.getClassName() + "Vista";
};
var oCuestionarioView = new cuestionarioView('cuestionario');
cuestionarioView.prototype.loadButtons = function (id) {
//
    var botonera = "";
    botonera += '

';
    botonera += '';
    botonera += '';
    botonera += '';
    botonera += '';
    botonera += '

';
    return botonera;
};
cuestionarioView.prototype.getBodyPageTable = function (page, fieldNames, visibleFields, tdbuttons) {
    var thisObject = this;
    var tabla = "";
    $.each(page, function (index, value) {
        tabla += '
';
        var numField = 0;
        var id;
        var strClaveAjena;
        $.each(fieldNames, function (index, valor) {
            if ("id" == valor) {
                id = value[valor];
            }
            ;
            numField++;
            if (numField <= visibleFields) {
                tabla += '';
                if ("tipo" == valor) {
                    tabla += '';
                    tabla += thisObject.printValue(value, valor, true);
                    tabla += "";
                } else {
                    tabla += thisObject.printValue(value, valor, true);
                }
                tabla += '	';
            }
        });
        tabla += '';
        tabla += tdbuttons(id);
        tabla += '	';
        tabla += '
';
    });
    return tabla;
};<|endoftext|>


<commit_before>define('app/views/log_list_item', ['app/views/list_item'],
    //
    //  Log List Item View
    //
    //  @returns Class
    //
    function (ListItemComponent) {

        'use strict';

        return App.LogListItemComponent = ListItemComponent.extend({

            //
            //  Properties
            //

            layoutName: 'log_list_item',
            log: null,
            tagName: 'li',
            isCollapsed: true,

            //
            //  Computed Properties
            //

            details: function () {
                var details = [];
                forIn(this.log, function (value, property) {
                    if (property == 'time')
                        return;
                    if (value !== undefined && value !== null)
                        details.push({
                            key: property,
                            value: value instanceof Object ? JSON.stringify(value) : value
                        });
                })
                return details.sort(function (a, b) {
                    if (a.key > b.key)
                        return 1;
                    if (a.key < b.key)
                        return -1;
                    return 0;
                });
            }.property('log'),

            collapsedClass: function () {
                return this.get('isCollapsed') ? '' : 'open';
            }.property('isCollapsed'),

            prettyTime: function () {
                return this.get('log').get('date') && this.get('log').get('date').getTimeFromNow();
            }.property('log.time'),

            fullPrettyTime: function () {
                return this.get('log').get('date') && this.get('log').get('date').getPrettyDateTime();
            }.property('log.time'),

            formatedAction: function () {
                return this.get('log').get('action').split('_').map(function (word) {
                    return word.capitalize();
                }).join(' ');
            }.property('log.action'),

            filteredEmail: function () {
                var email = this.get('log').get('email');
                return email !== 'None' ? email : '';
            }.property('log.email'),

            isIncident: function () {
                return this.get('log').get('type') == 'incident';
            }.property('log.type'),

            backendTitle: function () {
                var log = this.get('log');
                var backendId = log.get('backend_id');
                if (Mist.backendsController && Mist.backendsController.backendExists(backendId))
                    return Mist.backendsController.getBackend(backendId).title;
                return false;
            }.property('log.backend_id'),

            machineLink: function () {
                var log = this.get('log');
                var backendId = log.get('backend_id');
                var machineId = log.get('machine_id');
                return Mist.backendsController && Mist.backendsController.getMachine(machineId, backendId);
            }.property('log.machine_id'),

            showEmail: function () {
                return Mist.logs.namespace == 'manage_logs';
            }.property(),

            scriptLink: function () {
                var log = this.get('log');
                var scriptId = log.get('script_id');
                return Mist.scriptsController && Mist.scriptsController.getScript(scriptId);
            }.property('log.script_id'),

            //
            //  Actions
            //

            actions: {
                toggleCollapse: function () {
                    this.propertyDidChange('machineLink');
                    if (this.get('isCollapsed')) {
                        this.set('isCollapsed', false);
                        Ember.run.next(this, function () {
                            this.$('.details').slideDown();
                        });
                    } else {
                        var that = this;
                        Ember.run.next(this, function(){
                            this.$('.details').slideUp(function () {
                               that.set('isCollapsed', true);
                            });
                        });
                    }
                },

                userClicked: function (user) {
                    Mist.__container__.lookup('router:main').transitionTo('user',
                        Mist.usersController.getUser(
                            this.get('log').get('email')
                        )
                    );
                }
            }
        });
    }
);
<commit_msg>Removed unneeded wrapper stuff from script logs and sorted important stuff to appear first<commit_after>define('app/views/log_list_item', ['app/views/list_item'],
    //
    //  Log List Item View
    //
    //  @returns Class
    //
    function (ListItemComponent) {

        'use strict';

        return App.LogListItemComponent = ListItemComponent.extend({

            //
            //  Properties
            //

            layoutName: 'log_list_item',
            log: null,
            tagName: 'li',
            isCollapsed: true,

            //
            //  Computed Properties
            //

            details: function () {
                var pinnedDetails = [ "params" , "stdout" , "extra_output" ]
                var pinned = []
                // TODO fix incoming data for script actions not to
                // include wrapper unneeded properties
                var rejectProps = []
                if ( !DEBUG_LOGS ){
                    var rejectProps = ["command","wrapper_stdout"]
                }
                var details = [];
                forIn(this.log, function (value, property) {
                    if (property == 'time' || (rejectProps.indexOf(property) != -1))
                        return;
                    if (value !== undefined && value !== null)
                      if(pinnedDetails.indexOf(property)!=-1){
                            pinned[pinnedDetails.indexOf(property)]={
                                key: property,
                                value: value instanceof Object ? JSON.stringify(value) : value
                            }
                        }else{
                            details.push({
                                key: property,
                                value: value instanceof Object ? JSON.stringify(value) : value
                            });
                        }
                })
                return pinned.concat(details.sort(function (a, b) {
                    if (a.key > b.key)
                        return 1;
                    if (a.key < b.key)
                        return -1;
                    return 0;
                }));
            }.property('log'),

            collapsedClass: function () {
                return this.get('isCollapsed') ? '' : 'open';
            }.property('isCollapsed'),

            prettyTime: function () {
                return this.get('log').get('date') && this.get('log').get('date').getTimeFromNow();
            }.property('log.time'),

            fullPrettyTime: function () {
                return this.get('log').get('date') && this.get('log').get('date').getPrettyDateTime();
            }.property('log.time'),

            formatedAction: function () {
                return this.get('log').get('action').split('_').map(function (word) {
                    return word.capitalize();
                }).join(' ');
            }.property('log.action'),

            filteredEmail: function () {
                var email = this.get('log').get('email');
                return email !== 'None' ? email : '';
            }.property('log.email'),

            isIncident: function () {
                return this.get('log').get('type') == 'incident';
            }.property('log.type'),

            backendTitle: function () {
                var log = this.get('log');
                var backendId = log.get('backend_id');
                if (Mist.backendsController && Mist.backendsController.backendExists(backendId))
                    return Mist.backendsController.getBackend(backendId).title;
                return false;
            }.property('log.backend_id'),

            machineLink: function () {
                var log = this.get('log');
                var backendId = log.get('backend_id');
                var machineId = log.get('machine_id');
                return Mist.backendsController && Mist.backendsController.getMachine(machineId, backendId);
            }.property('log.machine_id'),

            showEmail: function () {
                return Mist.logs.namespace == 'manage_logs';
            }.property(),

            scriptLink: function () {
                var log = this.get('log');
                var scriptId = log.get('script_id');
                return Mist.scriptsController && Mist.scriptsController.getScript(scriptId);
            }.property('log.script_id'),

            //
            //  Actions
            //

            actions: {
                toggleCollapse: function () {
                    this.propertyDidChange('machineLink');
                    if (this.get('isCollapsed')) {
                        this.set('isCollapsed', false);
                        Ember.run.next(this, function () {
                            this.$('.details').slideDown();
                        });
                    } else {
                        var that = this;
                        Ember.run.next(this, function(){
                            this.$('.details').slideUp(function () {
                               that.set('isCollapsed', true);
                            });
                        });
                    }
                },

                userClicked: function (user) {
                    Mist.__container__.lookup('router:main').transitionTo('user',
                        Mist.usersController.getUser(
                            this.get('log').get('email')
                        )
                    );
                }
            }
        });
    }
);
<|endoftext|>


<commit_before>
/*
 *	Socket controller
 */
var myIO;

module.exports.init = function(httpServer){

	var io = require('socket.io').listen(httpServer);
	myIO = io;

	// Test variables
	var X = 0;
	var Y = 0;

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

		var self = false;
		console.log('New user');

	});
};

module.exports.emitter = function(data) {
	if (myIO) {

		var write = isWritingEnabled(data);

		if(write && data.writing == 'True'){
			myIO.sockets.emit('updateDataPoints', {
				x: data.xValue,
				y: data.yValue,
			});
			myIO.sockets.emit('toggleWriting', true);
		}else{
			myIO.sockets.emit('toggleWriting', false);
		}
	}
}

function isWritingEnabled(data){
	var initZ = parseFloat(data.initZ);
	var realZ = parseFloat(data.zValue);

	return (Math.abs(initZ-realZ) < 0.12)
}

<commit_msg>changed everything, yolo<commit_after>
/*
 *	Socket controller
 */
var myIO;

module.exports.init = function(httpServer){

	var io = require('socket.io').listen(httpServer);
	myIO = io;

	// Test variables
	var X = 0;
	var Y = 0;

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

		var self = false;
		console.log('New user');

	});
};

module.exports.emitter = function(data) {
	if (myIO) {

		var write = isWritingEnabled(data);

		if(write && data.writing == 'True'){
			myIO.sockets.emit('updateDataPoints', {
				x: data.xValue,
				y: data.yValue,
			});
			myIO.sockets.emit('toggleWriting', true);
		}else{
			myIO.sockets.emit('toggleWriting', false);
		}
	}
}

function isWritingEnabled(data){
	var initZ = parseFloat(data.initZ);
	var realZ = parseFloat(data.zValue);

	console.log("initZ - 0.04", initZ-0.04);
	console.log("initZ + 0.07", initZ+0.07);
	console.log("realZ", realZ);

	if(realZ > initZ+0.06)
		return false;
	else
		return true;
}

<|endoftext|>


<commit_before>var keystone = require('keystone');
var operation = keystone.list('Operation');

exports = module.exports = function (req, res) {
  var view = new keystone.View(req, res),
    locals = res.locals;

  // locals.section is used to set the currently selected
  // item in the header navigation.
  locals.section = 'dbExamples';

  operation.model.find()
    .where('title', 'Blindtarmsinflammation')
    .exec(function (err, data) {
      if (err) {
        console.log('DB error');
        console.log(err);
        return;
      }
      console.log(data);
      if (data.length) {
        operation.model
          .where('_id', data[0]._id)
          .remove(function (err, data) {
            console.log(data);
            if (!err) {
              console.log('Operationen är borttagen.');
            }
          });
      }

      //Skapa ny operation
      var newOperation = new operation.model({
        title: 'Blindtarmsinflammation',
        tags: 'appendix',
        template: false
      }).save(function (err) {
          if (err) {
            console.log('Operationen kunde inte skapas.!');
            return;
          }
          console.log('Operation skapad!');
        });

    });

  operation.model.search('ACI Ar', function (err, data) { //search är en funktion som jag skapat i modellen Operation
    if (err) {
      console.log('DB error');
      return;
    }
    console.log(data);
    locals.db = data.toString();
    view.render('dbExamples');
  });
};
<commit_msg>Förtydligade kommentarer<commit_after>var keystone = require('keystone');
var operation = keystone.list('Operation');

exports = module.exports = function (req, res) {
  var view = new keystone.View(req, res),
    locals = res.locals;

  // locals.section is used to set the currently selected
  // item in the header navigation.
  locals.section = 'dbExamples';

  operation.model.find()
    .where('title', 'Blindtarmsinflammation')
    .exec(function (err, data) {
      if (err) {
        console.log('DB error');
        console.log(err);
        return;
      }

      console.log(data);
      //Tar bort operationen ifall den finns för att inte få dubletter
      if (data.length) {
        operation.model
          .where('_id', data[0]._id)
          .remove(function (err, data) {
            console.log(data);
            if (!err) {
              console.log('Operationen är borttagen.');
            }
          });
      }

      //Skapar en ny operation
      var newOperation = new operation.model({
        title: 'Blindtarmsinflammation',
        tags: 'appendix',
        template: false
      }).save(function (err) {
          if (err) {
            console.log('Operationen kunde inte skapas.!');
            return;
          }
          console.log('Operation skapad!');
        });

    });

  //Söker efter operation med hjälp av den statiska sökfunkitonen som jag skapat i modellen. Söker i både taggar och titeln
  operation.model.search('ACI Ar', function (err, data) {
    if (err) {
      console.log('DB error');
      return;
    }
    console.log(data);
    locals.db = data.toString();
    view.render('dbExamples');
  });
};
<|endoftext|>


<commit_before>// Copyright (c) 2017, Frappe Technologies and contributors
// For license information, please see license.txt

frappe.ui.form.on('User Permission', {
	refresh: function(frm) {
		frm.add_custom_button(__('View Permitted Documents'),
			() => frappe.set_route('query-report', 'Permitted Documents For User',
				{user: frm.doc.user}));
	}
});
<commit_msg>Don't show single and child table doctype in User Permission's allowed doctypes (#3973)<commit_after>// Copyright (c) 2017, Frappe Technologies and contributors
// For license information, please see license.txt

frappe.ui.form.on('User Permission', {
	setup: function(frm) {
		frm.set_query("allow", function() {
			return {
				"filters": {
					issingle: 0,
					istable: 0
				}
			};
		});
	},

	refresh: function(frm) {
		frm.add_custom_button(__('View Permitted Documents'),
			() => frappe.set_route('query-report', 'Permitted Documents For User',
				{user: frm.doc.user}));
	}
});
<|endoftext|>


<commit_before>(function () {
    'use strict';

    /**
     * @param {typeof Num} Num
     * @param {app.utils} utils
     * @param {Waves} waves
     * @return {Asset}
     */
    const factory = function (Num, utils, waves) {

        class Asset extends Num {

            constructor(params) {
                super(params);

                /**
                 * @type {string}
                 */
                this.assetId = this.$attrs.assetId;
                if (!this.assetId) {
                    throw new Error('Has no asset id attribute for asset validator');
                }

                this.onReady()
                    .then((asset) => {
                        /**
                         * @type {IAsset}
                         */
                        this.asset = asset;

                        this.registerValidator('asset-input', (modelValue, viewValue) => {
                            const parts = String(viewValue || 0)
                                .replace(',', '')
                                .split('.');
                            if (!modelValue) {
                                return 'required' in this.$attrs;
                            }
                            return (!parts[1] || parts[1].length <= asset.precision);
                        });

                        if (this.$attrs.maxBalance) {
                            let balance;

                            this.registerValidator('asset-max', (modelValue) => {
                                if (!balance) {
                                    return true;
                                } else {
                                    return modelValue && modelValue.lte(balance.getTokens());
                                }
                            });

                            this.$scope.$watch(this.$attrs.maxBalance, (value) => {
                                balance = value;
                                this.validateByName('asset-max');
                            });
                        }
                    });
            }

            getFormatter() {
                return (value) => {
                    if (new BigNumber(value).eq(utils.parseNiceNumber(this.$input.val()))) {
                        return this.$input.val();
                    } else {
                        return value;
                    }
                };
            }

            onReady() {
                return super.onReady()
                    .then(() => waves.node.assets.info(this.assetId));
            }

        }

        return Asset;
    };

    factory.$inject = ['Num', 'utils', 'waves'];

    angular.module('app.utils')
        .factory('Asset', factory);
})();
<commit_msg>CLIENT-116: add todo<commit_after>(function () {
    'use strict';

    /**
     * @param {typeof Num} Num
     * @param {app.utils} utils
     * @param {Waves} waves
     * @return {Asset}
     */
    const factory = function (Num, utils, waves) {

        class Asset extends Num {

            constructor(params) {
                super(params);

                /**
                 * @type {string}
                 */
                this.assetId = this.$attrs.assetId;
                if (!this.assetId) {
                    throw new Error('Has no asset id attribute for asset validator');
                }

                this.onReady()
                    .then((asset) => {
                        /**
                         * @type {IAsset}
                         */
                        this.asset = asset;

                        this.registerValidator('asset-input', (modelValue, viewValue) => {
                            const parts = String(viewValue || 0)
                                .replace(',', '')
                                .split('.');
                            if (!modelValue) {
                                return 'required' in this.$attrs;
                            }
                            return (!parts[1] || parts[1].length <= asset.precision);
                        });

                        if (this.$attrs.maxBalance) {
                            let balance;

                            this.registerValidator('asset-max', (modelValue) => {
                                if (!balance) {
                                    return true;
                                } else {
                                    return modelValue && modelValue.lte(balance.getTokens());
                                }
                            });

                            this.$scope.$watch(this.$attrs.maxBalance, (value) => {
                                balance = value;
                                this.validateByName('asset-max');
                            });
                        }
                    });
            }

            getFormatter() {
                // TODO refactor
                return (value) => {
                    if (new BigNumber(value).eq(utils.parseNiceNumber(this.$input.val()))) {
                        return this.$input.val();
                    } else {
                        return value;
                    }
                };
            }

            onReady() {
                return super.onReady()
                    .then(() => waves.node.assets.info(this.assetId));
            }

        }

        return Asset;
    };

    factory.$inject = ['Num', 'utils', 'waves'];

    angular.module('app.utils')
        .factory('Asset', factory);
})();
<|endoftext|>


<commit_before>const test     = require('ava')
    , sinon    = require('sinon')
    , { pipe } = require('../dist/redash')

test('properly reports its arity (is variadic)', (t) => {
  t.is(pipe.length, 0)
})

test('returns a function', (t) => {
  t.is(typeof pipe(() => {}), 'function')
})

test('correctly reports its arity to match the leftmost function', (t) => {
  const unary   = (a0) => {}
      , binary  = (a0, a1) => {}
      , ternary = (a0, a1, a2) => {}

  t.is(pipe(unary, binary, ternary).length, 1)
  t.is(pipe(binary, unary, ternary).length, 2)
  t.is(pipe(ternary, unary, binary).length, 3)
})

test('invokes the functions from left to right and returns the result of the last function', (t) => {
  const s1  = sinon.spy(x => x * 2)
      , s2  = sinon.spy(x => x + 2)
      , s3  = sinon.spy(x => x / 2)
      , res = pipe(s1, s2, s3)(4)

  t.true(s1.calledWithExactly(4))
  t.true(s1.calledBefore(s2))
  t.true(s2.calledWithExactly(8))
  t.true(s2.calledBefore(s3))
  t.true(s3.calledWithExactly(10))
  t.is(res, 5)
})

test('throws early if a non-function is passed', (t) => {
  t.throws(
    () => pipe(() => {}, undefined),
    'Invalid argument supplied to `pipe`. The argument at index [1] was not a function; ' +
    'what was received was of type: Nil.')
 })
<commit_msg>chore(lint): fix indentation error in pipe spec<commit_after>const test     = require('ava')
    , sinon    = require('sinon')
    , { pipe } = require('../dist/redash')

test('properly reports its arity (is variadic)', (t) => {
  t.is(pipe.length, 0)
})

test('returns a function', (t) => {
  t.is(typeof pipe(() => {}), 'function')
})

test('correctly reports its arity to match the leftmost function', (t) => {
  const unary   = (a0) => {}
      , binary  = (a0, a1) => {}
      , ternary = (a0, a1, a2) => {}

  t.is(pipe(unary, binary, ternary).length, 1)
  t.is(pipe(binary, unary, ternary).length, 2)
  t.is(pipe(ternary, unary, binary).length, 3)
})

test('invokes the functions from left to right and returns the result of the last function', (t) => {
  const s1  = sinon.spy(x => x * 2)
      , s2  = sinon.spy(x => x + 2)
      , s3  = sinon.spy(x => x / 2)
      , res = pipe(s1, s2, s3)(4)

  t.true(s1.calledWithExactly(4))
  t.true(s1.calledBefore(s2))
  t.true(s2.calledWithExactly(8))
  t.true(s2.calledBefore(s3))
  t.true(s3.calledWithExactly(10))
  t.is(res, 5)
})

test('throws early if a non-function is passed', (t) => {
  t.throws(
    () => pipe(() => {}, undefined),
    'Invalid argument supplied to `pipe`. The argument at index [1] was not a function; ' +
    'what was received was of type: Nil.')
})

<|endoftext|>


<commit_before>angular.module('mwUI.Utils')

  .directive('mwLeaveConfirmation', function ($window, $rootScope, LeaveConfirmationModal) {
    return {
      scope: {
        alertBeforeLeave: '=mwLeaveConfirmation',
        text: '@'
      },
      link: function (scope) {

        var confirmationModal = new LeaveConfirmationModal();

        // Prevent the original event so the routing will not be completed
        // Save the url where it should be navigated to in a temp variable
        var showConfirmModal = function (nextUrl) {
          confirmationModal.setScopeAttributes({
            nextUrl: nextUrl,
            text: scope.text,
            leaveCallback: function () {
              scope.changeLocationOff();
            },
            stayCallback: function () {

            }
          });
          confirmationModal.show();
        };

        //In case that just a hashchange event was triggered
        scope.changeLocationOff = $rootScope.$on('$locationChangeStart', function (ev, nextUrl) {
          if (scope.alertBeforeLeave) {
            ev.preventDefault();
            showConfirmModal(nextUrl);
          }
        });

        //In case that the user clicks the refresh/back button or makes a hard url change
        $window.onbeforeunload = function () {
          if (scope.alertBeforeLeave) {
            return scope.text;
          }
        };

        if (!angular.isDefined(scope.text)) {
          throw new Error('Please specify a text in the text attribute');
        }

        scope.$on('$destroy', scope.changeLocationOff);
      }
    };
  });
<commit_msg>Only show modal when new url not the same as the current one<commit_after>angular.module('mwUI.Utils')

  .directive('mwLeaveConfirmation', function ($window, $rootScope, LeaveConfirmationModal) {
    return {
      scope: {
        alertBeforeLeave: '=mwLeaveConfirmation',
        text: '@'
      },
      link: function (scope) {

        var confirmationModal = new LeaveConfirmationModal();

        // Prevent the original event so the routing will not be completed
        // Save the url where it should be navigated to in a temp variable
        var showConfirmModal = function (nextUrl) {
          confirmationModal.setScopeAttributes({
            nextUrl: nextUrl,
            text: scope.text,
            leaveCallback: function () {
              scope.changeLocationOff();
            },
            stayCallback: function () {

            }
          });
          confirmationModal.show();
        };
        //In case that just a hashchange event was triggered
        scope.changeLocationOff = $rootScope.$on('$locationChangeStart', function (ev, nextUrl, prevUrl) {
          if (scope.alertBeforeLeave && prevUrl && nextUrl !== prevUrl) {
            ev.preventDefault();
            showConfirmModal(nextUrl);
          }
        });

        //In case that the user clicks the refresh/back button or makes a hard url change
        $window.onbeforeunload = function () {
          if (scope.alertBeforeLeave) {
            return scope.text;
          }
        };

        if (!angular.isDefined(scope.text)) {
          throw new Error('Please specify a text in the text attribute');
        }

        scope.$on('$destroy', scope.changeLocationOff);
      }
    };
  });
<|endoftext|>


<commit_before>/* @flow */

import React from 'react';
import {
  TextInput,
  StyleSheet,
} from 'react-native';

// TODO: ../forms/stylesと共通化？
const styles = StyleSheet.create({
  textInput: {
    height: 26,
    borderWidth: 0.5,
    borderColor: '#0f0f0f',
    flex: 1,
    fontSize: 13,
    padding: 4,
  },
});

export default ({
  filter,
  onFilterChange,
}: {
  filter: string,
  onFilterChange: (newFilter: string) => void,
}) => (
  <TextInput
    style={styles.textInput}
    value={filter}
    onChangeText={(text) => onFilterChange(text)}
  />
);
<commit_msg>(refs #271) Set proper style to native <PatientListFilter /><commit_after>/* @flow */

import React from 'react';
import {
  TextInput,
  StyleSheet,
} from 'react-native';

// TODO: ../forms/stylesと共通化？
const styles = StyleSheet.create({
  textInput: {
    height: 26,
    borderWidth: 0.5,
    borderColor: '#0f0f0f',
    fontSize: 13,
    padding: 4,
  },
});

export default ({
  filter,
  onFilterChange,
}: {
  filter: string,
  onFilterChange: (newFilter: string) => void,
}) => (
  <TextInput
    style={styles.textInput}
    value={filter}
    onChangeText={(text) => onFilterChange(text)}
  />
);
<|endoftext|>


<commit_before>// Redis related
var redis;   =

if (process.env.REDISTOGO_URL) {
    // TODO: redistogo connection
	// inside if statement
	var rtg   = require("url").parse(process.env.REDISTOGO_URL);
	var redis = require("redis").createClient(rtg.port, rtg.hostname);

	redis.auth(rtg.auth.split(":")[1]);

} else {
    redis = require("redis");
}

var redisClient = redis.createClient();
var Rx = require('Rx');

// Returns an observable for a redis value for a given key
function valueForKey(key){
	return Rx.Observable.create(function(observer){
		redisClient.get(key, function(err, reply){
			if (err)
				observer.error(err);
			else {
				var jsonReply = JSON.parse(reply)
				observer.onNext(jsonReply);
				observer.onCompleted();
			}
		})
	})
}

// Returns an observable that retuns the value once it's been set in redis
function setValueForKey(key, value){
	return Rx.Observable.create(function(observer){
		var jsonValue = JSON.stringify(value);
		redisClient.set(key, jsonValue, function(error){
			if (error)
				observer.error(error)
			else {
				observer.onNext(value);
				observer.onCompleted();
			}

		});
	})
}

module.exports.valueForKey = valueForKey;
module.exports.setValueForKey = setValueForKey;<commit_msg>Fixing misc typo in rxredis<commit_after>// Redis related
var redis;

if (process.env.REDISTOGO_URL) {
    // TODO: redistogo connection
	// inside if statement
	var rtg   = require("url").parse(process.env.REDISTOGO_URL);
	var redis = require("redis").createClient(rtg.port, rtg.hostname);

	redis.auth(rtg.auth.split(":")[1]);

} else {
    redis = require("redis");
}

var redisClient = redis.createClient();
var Rx = require('Rx');

// Returns an observable for a redis value for a given key
function valueForKey(key){
	return Rx.Observable.create(function(observer){
		redisClient.get(key, function(err, reply){
			if (err)
				observer.error(err);
			else {
				var jsonReply = JSON.parse(reply)
				observer.onNext(jsonReply);
				observer.onCompleted();
			}
		})
	})
}

// Returns an observable that retuns the value once it's been set in redis
function setValueForKey(key, value){
	return Rx.Observable.create(function(observer){
		var jsonValue = JSON.stringify(value);
		redisClient.set(key, jsonValue, function(error){
			if (error)
				observer.error(error)
			else {
				observer.onNext(value);
				observer.onCompleted();
			}

		});
	})
}

module.exports.valueForKey = valueForKey;
module.exports.setValueForKey = setValueForKey;<|endoftext|>


<commit_before>var m = require('mithril');
var $osf = require('js/osfHelpers');
var waterbutler =  require('js/waterbutler');

require('css/quick-project-search-plugin.css');
require('loaders.css/loaders.min.css');
var Dropzone = require('dropzone');

var xhrconfig = function(xhr) {
    xhr.withCredentials = true;
};

var ShareWindowDropzone = {

  controller: function() {
    var shareWindowId;
    var url = $osf.apiV2Url('users/me/nodes/', { query : { 'filter[category]' : 'share window'}});
    var promise = m.request({method: 'GET', url : url, config : xhrconfig, background: true});
    promise.then(function(result) {
        shareWindowId = result.data[0].id;
    });

      Dropzone.options.shareWindowDropzone = {

             accept: function(file, done) {
                this.options.url = waterbutler.buildUploadUrl(false,'osfstorage',shareWindowId, file,{});
                done();
            }
    };

    $('#shareWindowDropzone').dropzone({
                               withCredentials: true,
                               url:'placeholder',
                               method:'put',
                               previewTemplate: '
 is uploaded to to Share Window
'

                               });

  },
  view: function(ctrl, args) {
          return  m('.m-v-xs.node-styling',  m('.row', m('div',
                  [
                      m('.m-v-xl', m('#shareWindowDropzone',  m('h1.text-center',  'Dropzone'))),
                  ]
              )));
  }
};

module.exports = ShareWindowDropzone;
<commit_msg>Don't show dropped content if user drags outside dropzone<commit_after>var m = require('mithril');
var $osf = require('js/osfHelpers');
var waterbutler =  require('js/waterbutler');

require('css/quick-project-search-plugin.css');
require('loaders.css/loaders.min.css');
var Dropzone = require('dropzone');

// Don't show dropped content if user drags outside dropzone
window.ondragover = function(e) { e.preventDefault(); };
window.ondrop = function(e) { e.preventDefault(); };

var xhrconfig = function(xhr) {
    xhr.withCredentials = true;
};

var ShareWindowDropzone = {

  controller: function() {
    var shareWindowId;
    var url = $osf.apiV2Url('users/me/nodes/', { query : { 'filter[category]' : 'share window'}});
    var promise = m.request({method: 'GET', url : url, config : xhrconfig, background: true});
    promise.then(function(result) {
        shareWindowId = result.data[0].id;
    });

      Dropzone.options.shareWindowDropzone = {

             accept: function(file, done) {
                this.options.url = waterbutler.buildUploadUrl(false,'osfstorage',shareWindowId, file,{});
                done();
            }
    };

    $('#shareWindowDropzone').dropzone({
                               withCredentials: true,
                               url:'placeholder',
                               method:'put',
                               previewTemplate: '
 is uploaded to to Share Window
'

                               });

  },
  view: function(ctrl, args) {
          return  m('.m-v-xs.node-styling',  m('.row', m('div',
                  [
                      m('.m-v-xl', m('#shareWindowDropzone',  m('h1.text-center',  'Dropzone'))),
                  ]
              )));
  }
};

module.exports = ShareWindowDropzone;
<|endoftext|>


<commit_before>var locastyle = locastyle || {};

locastyle.toggleText = (function() {
  'use strict';

  var config = {
    trigger: '[data-ls-module=toggleText]',
    triggerChange: 'toggleText:change'
  };

  function eventHandler(el, target, text) {
    el.trigger(config.triggerChange, [target, text]);
  }

  function bindToggle(el) {
    var $target      = el.data('target-text') ? $(el.data('target-text')) : el;
    var textChange   = el.data('toggle-text');
    var textOriginal = $target.text();

    el.data('toggle-text', textOriginal);
    $target.text(textChange);

    eventHandler(el, $target, textChange);
  }

  function bindEventOnClick() {
    $(config.trigger).on('click.ls', function(event) {
      event.preventDefault();
      bindToggle($(this));
      event.stopPropagation();
    });
  }

  function unbind() {
    $(config.trigger).off('click.ls');
  }

  function init() {
    unbind();
    bindEventOnClick();
  }

  return {
    init: init
  };

}());
<commit_msg>Remove stop propagation from toggle text module<commit_after>var locastyle = locastyle || {};

locastyle.toggleText = (function() {
  'use strict';

  var config = {
    trigger: '[data-ls-module=toggleText]',
    triggerChange: 'toggleText:change'
  };

  function eventHandler(el, target, text) {
    el.trigger(config.triggerChange, [target, text]);
  }

  function bindToggle(el) {
    var $target      = el.data('target-text') ? $(el.data('target-text')) : el;
    var textChange   = el.data('toggle-text');
    var textOriginal = $target.text();

    el.data('toggle-text', textOriginal);
    $target.text(textChange);

    eventHandler(el, $target, textChange);
  }

  function bindEventOnClick() {
    $(config.trigger).on('click.ls', function(event) {
      event.preventDefault();
      bindToggle($(this));
    });
  }

  function unbind() {
    $(config.trigger).off('click.ls');
  }

  function init() {
    unbind();
    bindEventOnClick();
  }

  return {
    init: init
  };

}());
<|endoftext|>


<commit_before>/**
 * @flow
 */

import BorderPropTypes from '../../modules/BorderPropTypes';
import ColorPropType from '../ColorPropType';
import ImageResizeMode from './ImageResizeMode';
import LayoutPropTypes from '../../modules/LayoutPropTypes';
import ShadowPropTypes from '../../modules/ShadowPropTypes';
import TransformPropTypes from '../../modules/TransformPropTypes';
import { number, oneOf, string } from 'prop-types';

const ImageStylePropTypes = {
  ...BorderPropTypes,
  ...LayoutPropTypes,
  ...ShadowPropTypes,
  ...TransformPropTypes,
  backgroundColor: ColorPropType,
  opacity: number,
  resizeMode: oneOf(Object.keys(ImageResizeMode)),
  /**
   * @platform unsupported
   */
  overlayColor: string,
  tintColor: ColorPropType,
  /**
   * @platform web
   */
  boxShadow: string
};

export default ImageStylePropTypes;
<commit_msg>[add] Image style support for animations, interactions, and filters<commit_after>/**
 * @flow
 */

import AnimationPropTypes from '../../modules/AnimationPropTypes';
import BorderPropTypes from '../../modules/BorderPropTypes';
import ColorPropType from '../ColorPropType';
import ImageResizeMode from './ImageResizeMode';
import InteractionPropTypes from '../../modules/InteractionPropTypes';
import LayoutPropTypes from '../../modules/LayoutPropTypes';
import ShadowPropTypes from '../../modules/ShadowPropTypes';
import TransformPropTypes from '../../modules/TransformPropTypes';
import { number, oneOf, string } from 'prop-types';

const ImageStylePropTypes = {
  ...AnimationPropTypes,
  ...BorderPropTypes,
  ...InteractionPropTypes,
  ...LayoutPropTypes,
  ...ShadowPropTypes,
  ...TransformPropTypes,
  backgroundColor: ColorPropType,
  opacity: number,
  resizeMode: oneOf(Object.keys(ImageResizeMode)),
  /**
   * @platform unsupported
   */
  overlayColor: string,
  tintColor: ColorPropType,
  /**
   * @platform web
   */
  boxShadow: string,
  filter: string
};

export default ImageStylePropTypes;
<|endoftext|>


<commit_before>const whitelist = {
  accessibilityComponentType: true,
  accessibilityLabel: true,
  accessibilityLiveRegion: true,
  accessibilityRole: true,
  accessibilityTraits: true,
  accessible: true,
  children: true,
  disabled: true,
  importantForAccessibility: true,
  onBlur: true,
  onContextMenu: true,
  onFocus: true,
  onMoveShouldSetResponder: true,
  onMoveShouldSetResponderCapture: true,
  onResponderEnd: true,
  onResponderGrant: true,
  onResponderMove: true,
  onResponderReject: true,
  onResponderRelease: true,
  onResponderStart: true,
  onResponderTerminate: true,
  onResponderTerminationRequest: true,
  onScrollShouldSetResponder: true,
  onScrollShouldSetResponderCapture: true,
  onSelectionChangeShouldSetResponder: true,
  onSelectionChangeShouldSetResponderCapture: true,
  onStartShouldSetResponder: true,
  onStartShouldSetResponderCapture: true,
  onTouchCancel: true,
  onTouchCancelCapture: true,
  onTouchEnd: true,
  onTouchEndCapture: true,
  onTouchMove: true,
  onTouchMoveCapture: true,
  onTouchStart: true,
  onTouchStartCapture: true,
  pointerEvents: true,
  style: true,
  testID: true,
  // escape-hatches for ScrollView
  onScroll: true,
  onWheel: true,
  // escape-hatches for Touchable keyboard support
  onKeyDown: true,
  onKeyPress: true,
  onKeyUp: true,
  // escape-hatches for creating hover effects
  onMouseEnter: true,
  onMouseLeave: true,
  onMouseMove: true,
  onMouseOver: true,
  onMouseOut: true,
  // unstable escape-hatches for web
  className: true,
  href: true,
  onClick: true,
  onClickCapture: true,
  rel: true,
  target: true
};

const filterSupportedProps = props => {
  const safeProps = {};
  for (const prop in props) {
    if (props.hasOwnProperty(prop)) {
      if (whitelist[prop] || prop.indexOf('aria-') === 0 || prop.indexOf('data-') === 0) {
        safeProps[prop] = props[prop];
      }
    }
  }
  return safeProps;
};

export default filterSupportedProps;
<commit_msg>[fix] add mousedown and mouseup to supported View props<commit_after>const whitelist = {
  accessibilityComponentType: true,
  accessibilityLabel: true,
  accessibilityLiveRegion: true,
  accessibilityRole: true,
  accessibilityTraits: true,
  accessible: true,
  children: true,
  disabled: true,
  importantForAccessibility: true,
  onBlur: true,
  onContextMenu: true,
  onFocus: true,
  onMoveShouldSetResponder: true,
  onMoveShouldSetResponderCapture: true,
  onResponderEnd: true,
  onResponderGrant: true,
  onResponderMove: true,
  onResponderReject: true,
  onResponderRelease: true,
  onResponderStart: true,
  onResponderTerminate: true,
  onResponderTerminationRequest: true,
  onScrollShouldSetResponder: true,
  onScrollShouldSetResponderCapture: true,
  onSelectionChangeShouldSetResponder: true,
  onSelectionChangeShouldSetResponderCapture: true,
  onStartShouldSetResponder: true,
  onStartShouldSetResponderCapture: true,
  onTouchCancel: true,
  onTouchCancelCapture: true,
  onTouchEnd: true,
  onTouchEndCapture: true,
  onTouchMove: true,
  onTouchMoveCapture: true,
  onTouchStart: true,
  onTouchStartCapture: true,
  pointerEvents: true,
  style: true,
  testID: true,
  /* @platform web */
  onScroll: true,
  onWheel: true,
  // keyboard events
  onKeyDown: true,
  onKeyPress: true,
  onKeyUp: true,
  // mouse events (e.g, hover effects)
  onMouseDown: true,
  onMouseEnter: true,
  onMouseLeave: true,
  onMouseMove: true,
  onMouseOver: true,
  onMouseOut: true,
  onMouseUp: true,
  // unstable escape-hatches for web
  className: true,
  href: true,
  onClick: true,
  onClickCapture: true,
  rel: true,
  target: true
};

const filterSupportedProps = props => {
  const safeProps = {};
  for (const prop in props) {
    if (props.hasOwnProperty(prop)) {
      if (whitelist[prop] || prop.indexOf('aria-') === 0 || prop.indexOf('data-') === 0) {
        safeProps[prop] = props[prop];
      }
    }
  }
  return safeProps;
};

export default filterSupportedProps;
<|endoftext|>


<commit_before>RocketChat.ChannelSettings = new class {
	constructor() {
		this.options = new ReactiveVar({});
	}

/*
	 * Adds an option in Channel Settings
	 * @config (object)
	 *   id: option id (required)
	 *   template (string): template name to render (required)
	 *   validation (function): if option should be displayed
 */
	addOption(config) {
		if (config == null || config.id == null) {
			return false;
		}
		return Tracker.nonreactive(() => {
			const opts = this.options.get();
			opts[config.id] = config;
			return this.options.set(opts);
		});
	}

	getOptions(currentData, group) {
		const allOptions = _.toArray(this.options.get());
		const allowedOptions = _.compact(_.map(allOptions, function(option) {
			if (option.validation == null || option.validation()) {
				option.data = Object.assign({}, option.data, currentData);
				return option;
			}
		})).filter(function(option) {
			return !group || !option.group || option.group.includes(group);
		});
		return _.sortBy(allowedOptions, 'order');
	}
};
<commit_msg>fix adminroom default option<commit_after>RocketChat.ChannelSettings = new class {
	constructor() {
		this.options = new ReactiveVar({});
	}

/*
	 * Adds an option in Channel Settings
	 * @config (object)
	 *   id: option id (required)
	 *   template (string): template name to render (required)
	 *   validation (function): if option should be displayed
 */
	addOption(config) {
		if (config == null || config.id == null) {
			return false;
		}
		return Tracker.nonreactive(() => {
			const opts = this.options.get();
			opts[config.id] = config;
			return this.options.set(opts);
		});
	}

	getOptions(currentData, group) {
		const allOptions = _.toArray(this.options.get());
		const allowedOptions = _.compact(_.map(allOptions, function(option) {
			if (option.validation == null || option.validation()) {
				option.data = Object.assign({}, typeof option.data === 'function' ? option.data() : option.data, currentData);
				return option;
			}
		})).filter(function(option) {
			return !group || !option.group || option.group.includes(group);
		});
		return _.sortBy(allowedOptions, 'order');
	}
};
<|endoftext|>