<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache 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.apache.org/licenses/LICENSE-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.
 */

var deviceModule;
deviceModule = function () {
    var log = new Log("/app/modules/device.js");

    var utility = require('/app/modules/utility.js').utility;
    var constants = require('/app/modules/constants.js');
    var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
    var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];

    var ArrayList = Packages.java.util.ArrayList;
    var Properties = Packages.java.util.Properties;
    var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
    var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
    var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
    var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
    var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;

    var publicMethods = {};
    var privateMethods = {};

    var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager";

    privateMethods.validateAndReturn = function (value) {
        return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
    };

    /*
     @Deprecated
     */
    publicMethods.listDevices = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try {
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var devices = deviceManagementService.getAllDevices();
            var deviceList = [];
            var i, device, propertiesList, deviceObject;
            for (i = 0; i < devices.size(); i++) {
                device = devices.get(i);
                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());

                deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] =
                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
                deviceObject[constants.DEVICE_NAME] =
                    privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
                deviceObject[constants.DEVICE_TYPE] =
                    privateMethods.validateAndReturn(device.getType());
                deviceObject[constants.DEVICE_PROPERTIES] = {};
                if (device.getType() == constants.PLATFORM_IOS) {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                } else {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
                }
                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));

                deviceList.push(deviceObject);
            }
            return deviceList;
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Deprecated
     */
    /*
     Get the supported features by the device type
     */
    publicMethods.getFeatures = function (deviceType) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try {
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
            var featuresConverted = {};
            if (features) {
                var i, feature, featureObject;
                for (i = 0; i < features.size(); i++) {
                    feature = features.get(i);
                    featureObject = {};
                    featureObject[constants.FEATURE_NAME] = feature.getName();
                    featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
                    featuresConverted[feature.getName()] = featureObject;
                }
            }
            return featuresConverted;
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Deprecated
     */
    publicMethods.performOperation = function (devices, operation) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try {
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var operationInstance;
            if (operation.type == "COMMAND") {
                operationInstance = new CommandOperation();
            } else if (operation.type == "CONFIG") {
                operationInstance = new ConfigOperation();
            } else {
                operationInstance = new SimpleOperation();
            }
            operationInstance.setCode(operation.featureName);
            var props = new Properties();
            var i, object;
            for (i = 0; i < operation.properties.length; i++) {
                object = properties[i];
                props.setProperty(object.key, object.value);
            }
            operationInstance.setProperties(props);
            var deviceList = new ArrayList();
            var j, device, deviceIdentifier;
            for (j = 0; j < devices.length; i++) {
                device = devices[j];
                deviceIdentifier = new DeviceIdentifier();
                deviceIdentifier.setId(device.id);
                deviceIdentifier.setType(device.type);
                deviceList.add(deviceIdentifier);
            }
            deviceManagementService.addOperation(operationInstance, deviceList);
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Deprecated
     */
    privateMethods.getDevice = function (type, deviceId) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/app/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try {
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var deviceIdentifier = new DeviceIdentifier();
            deviceIdentifier.setType(type);
            deviceIdentifier.setId(deviceId);
            return deviceManagementService.getDevice(deviceIdentifier);
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Updated
     */
    publicMethods.viewDevice = function (deviceType, deviceId) {
        var carbonUser = session.get(constants["USER_SESSION_KEY"]);
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
        var utility = require('/app/modules/utility.js')["utility"];
        try {
            utility.startTenantFlow(carbonUser);

            var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/view?type=" + deviceType + "&id=" + deviceId;
            return serviceInvokers.XMLHttp.get(
                    url, function (responsePayload) {
                        var device = responsePayload.responseContent;
                        if (device) {
                            var propertiesList = device["properties"];
                            var properties = {};
                            if (propertiesList){
                                for (var i = 0; i < propertiesList.length; i++) {
                                    properties[propertiesList[i]["name"]] = propertiesList[i]["value"];
                                }
                            }
                            var deviceObject = {};
                            deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"];
                            deviceObject[constants["DEVICE_NAME"]] = device["name"];
                            deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"];
                            deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"];
                            deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"];
                            deviceObject[constants["DEVICE_TYPE"]] = device["type"];
                            if (device["type"] == constants["PLATFORM_IOS"]) {
                                properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]];
                                delete properties[constants["DEVICE_PRODUCT"]];
                                properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"];
                            }
                            deviceObject[constants["DEVICE_PROPERTIES"]] = properties;
                            return deviceObject;
                        }
                    },
                    function (responsePayload) {
                        var response = {};
                        response["status"] = "error";
                        return response;
                    }
            );
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    // Refactored methods
    publicMethods.getDevicesCount = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        if (carbonUser) {
            var userModule = require("/app/modules/user.js").userModule;
            var uiPermissions = userModule.getUIPermissions();
            var url;
            if (uiPermissions.LIST_DEVICES) {
                url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/count";
            } else if (uiPermissions.LIST_OWN_DEVICES) {
                url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + carbonUser.username
                      + "/count";
            } else {
                log.error("Access denied for user: " + carbonUser.username);
                return -1;
            }
            return serviceInvokers.XMLHttp.get(
                    url, function (responsePayload) {
                        return responsePayload;
                    },
                    function (responsePayload) {
                        log.error(responsePayload);
                        return -1;
                    }
            );
        } else {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
    };

    publicMethods.getDeviceTypes = function () {
        var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types";
        return serviceInvokers.XMLHttp.get(
                url, function (responsePayload) {
                    return responsePayload;
                },
                function (responsePayload) {
                    log.error(responsePayload);
                    return -1;
                }
        );
    };

    //Old methods
    //TODO: make sure these methods are updated
    /*
     @Updated
     */
    publicMethods.getLicense = function (deviceType) {
        var url;
        var license;
        if (deviceType == "windows") {
            url = devicemgtProps["httpURL"] + "/mdm-windows-agent/services/device/license";
        } else if (deviceType == "ios") {
            url = devicemgtProps["httpsURL"] + "/ios-enrollment/license/";
        }

        if (url != null && url != undefined) {
            serviceInvokers.XMLHttp.get(url, function (responsePayload) {
                license = responsePayload.text;
            }, function (responsePayload) {
                return null;
            });
        }
        return license;
    };

    publicMethods.getDevices = function (userName) {
        var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + userName;
        return serviceInvokers.XMLHttp.get(
                url, function (responsePayload) {
                    for (var i = 0; i < responsePayload.length; i++) {
                        responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type);
                    }
                    return responsePayload;
                },
                function (responsePayload) {
                    log.error(responsePayload);
                    return -1;
                }
        );
    };
    return publicMethods;
}();
<commit_msg>Deprecating obsolete UI functions - device.js<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache 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.apache.org/licenses/LICENSE-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.
 */

var deviceModule;
deviceModule = function () {
    var log = new Log("/app/modules/device.js");

    var utility = require('/app/modules/utility.js').utility;
    var constants = require('/app/modules/constants.js');
    var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
    var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];

//    var ArrayList = Packages.java.util.ArrayList;
//    var Properties = Packages.java.util.Properties;
//    var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
//    var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
//    var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
//    var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
//    var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;

    var publicMethods = {};
    var privateMethods = {};

//    var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager";

    privateMethods.validateAndReturn = function (value) {
        return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
    };

    /*
     @Deprecated
     */
//    publicMethods.listDevices = function () {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var devices = deviceManagementService.getAllDevices();
//            var deviceList = [];
//            var i, device, propertiesList, deviceObject;
//            for (i = 0; i < devices.size(); i++) {
//                device = devices.get(i);
//                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
//
//                deviceObject = {};
//                deviceObject[constants.DEVICE_IDENTIFIER] =
//                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
//                deviceObject[constants.DEVICE_NAME] =
//                    privateMethods.validateAndReturn(device.getName());
//                deviceObject[constants.DEVICE_OWNERSHIP] =
//                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
//                deviceObject[constants.DEVICE_OWNER] =
//                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
//                deviceObject[constants.DEVICE_TYPE] =
//                    privateMethods.validateAndReturn(device.getType());
//                deviceObject[constants.DEVICE_PROPERTIES] = {};
//                if (device.getType() == constants.PLATFORM_IOS) {
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
//                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
//                } else {
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
//                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
//                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
//                }
//                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
//                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));
//
//                deviceList.push(deviceObject);
//            }
//            return deviceList;
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Deprecated
     */
    /*
     Get the supported features by the device type
     */
//    publicMethods.getFeatures = function (deviceType) {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
//            var featuresConverted = {};
//            if (features) {
//                var i, feature, featureObject;
//                for (i = 0; i < features.size(); i++) {
//                    feature = features.get(i);
//                    featureObject = {};
//                    featureObject[constants.FEATURE_NAME] = feature.getName();
//                    featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
//                    featuresConverted[feature.getName()] = featureObject;
//                }
//            }
//            return featuresConverted;
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Deprecated
     */
//    publicMethods.performOperation = function (devices, operation) {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var operationInstance;
//            if (operation.type == "COMMAND") {
//                operationInstance = new CommandOperation();
//            } else if (operation.type == "CONFIG") {
//                operationInstance = new ConfigOperation();
//            } else {
//                operationInstance = new SimpleOperation();
//            }
//            operationInstance.setCode(operation.featureName);
//            var props = new Properties();
//            var i, object;
//            for (i = 0; i < operation.properties.length; i++) {
//                object = properties[i];
//                props.setProperty(object.key, object.value);
//            }
//            operationInstance.setProperties(props);
//            var deviceList = new ArrayList();
//            var j, device, deviceIdentifier;
//            for (j = 0; j < devices.length; i++) {
//                device = devices[j];
//                deviceIdentifier = new DeviceIdentifier();
//                deviceIdentifier.setId(device.id);
//                deviceIdentifier.setType(device.type);
//                deviceList.add(deviceIdentifier);
//            }
//            deviceManagementService.addOperation(operationInstance, deviceList);
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Deprecated
     */
//    privateMethods.getDevice = function (type, deviceId) {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var deviceIdentifier = new DeviceIdentifier();
//            deviceIdentifier.setType(type);
//            deviceIdentifier.setId(deviceId);
//            return deviceManagementService.getDevice(deviceIdentifier);
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Updated
     */
    publicMethods.viewDevice = function (deviceType, deviceId) {
        var carbonUser = session.get(constants["USER_SESSION_KEY"]);
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
        var utility = require('/app/modules/utility.js')["utility"];
        try {
            utility.startTenantFlow(carbonUser);

            var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/view?type=" + deviceType + "&id=" + deviceId;
            return serviceInvokers.XMLHttp.get(
                url, function (responsePayload) {
                    var device = responsePayload.responseContent;
                    if (device) {
                        var propertiesList = device["properties"];
                        var properties = {};
                        if (propertiesList){
                            for (var i = 0; i < propertiesList.length; i++) {
                                properties[propertiesList[i]["name"]] = propertiesList[i]["value"];
                            }
                        }
                        var deviceObject = {};
                        deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"];
                        deviceObject[constants["DEVICE_NAME"]] = device["name"];
                        deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"];
                        deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"];
                        deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"];
                        deviceObject[constants["DEVICE_TYPE"]] = device["type"];
                        if (device["type"] == constants["PLATFORM_IOS"]) {
                            properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]];
                            delete properties[constants["DEVICE_PRODUCT"]];
                            properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"];
                        }
                        deviceObject[constants["DEVICE_PROPERTIES"]] = properties;
                        return deviceObject;
                    }
                },
                function (responsePayload) {
                    var response = {};
                    response["status"] = "error";
                    return response;
                }
            );
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    // Refactored methods
    publicMethods.getDevicesCount = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        if (carbonUser) {
            var userModule = require("/app/modules/user.js").userModule;
            var uiPermissions = userModule.getUIPermissions();
            var url;
            if (uiPermissions.LIST_DEVICES) {
                url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/count";
            } else if (uiPermissions.LIST_OWN_DEVICES) {
                url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + carbonUser.username
                    + "/count";
            } else {
                log.error("Access denied for user: " + carbonUser.username);
                return -1;
            }
            return serviceInvokers.XMLHttp.get(
                url, function (responsePayload) {
                    return responsePayload;
                },
                function (responsePayload) {
                    log.error(responsePayload);
                    return -1;
                }
            );
        } else {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
    };

    publicMethods.getDeviceTypes = function () {
        var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types";
        return serviceInvokers.XMLHttp.get(
            url, function (responsePayload) {
                return responsePayload;
            },
            function (responsePayload) {
                log.error(responsePayload);
                return -1;
            }
        );
    };

    //Old methods
    //TODO: make sure these methods are updated
    /*
     @Updated
     */
    publicMethods.getLicense = function (deviceType) {
        var url;
        var license;
        if (deviceType == "windows") {
            url = devicemgtProps["httpURL"] + "/mdm-windows-agent/services/device/license";
        } else if (deviceType == "ios") {
            url = devicemgtProps["httpsURL"] + "/ios-enrollment/license/";
        }

        if (url != null && url != undefined) {
            serviceInvokers.XMLHttp.get(url, function (responsePayload) {
                license = responsePayload.text;
            }, function (responsePayload) {
                return null;
            });
        }
        return license;
    };

    publicMethods.getDevices = function (userName) {
        var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + userName;
        return serviceInvokers.XMLHttp.get(
            url, function (responsePayload) {
                for (var i = 0; i < responsePayload.length; i++) {
                    responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type);
                }
                return responsePayload;
            },
            function (responsePayload) {
                log.error(responsePayload);
                return -1;
            }
        );
    };
    return publicMethods;
}();
<|endoftext|>


<commit_before>'use strict';

/**
 * Requirements
 * @ignore
 */
const Parser = require('./Parser.js').Parser;
const File = require('../model/file/File.js').File;
const ContentType = require('../model/ContentType.js');
const ContentKind = require('../model/ContentKind.js');
const glob = require('../utils/glob.js');
const co = require('co');

/**
 * Reads files based on glob patterns
 */
class FileParser extends Parser
{
    /**
     * @param {object|undefined} options
     */
    constructor(options)
    {
        super();

        // Assign options
        const opts = options || {};
        this._parser = opts.parser || undefined;
        this._glob = opts.glob || [];
        this._fileType = opts.fileType || ContentType.ANY;
        this._fileKind = opts.fileKind || ContentKind.UNKNOWN;
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': ['parser/FileParser.options'] };
    }

    /**
     * @inheritDoc
     */
    static get className()
    {
        return 'parser/FileParser';
    }

    /**
     * @property {Array}
     */
    get glob()
    {
        return this._glob;
    }

    /**
     * @property {Array}
     */
    get fileType()
    {
        return this._fileType;
    }

    /**
     * @property {Array}
     */
    get fileKind()
    {
        return this._fileKind;
    }

    /**
     * Parses a file
     *
     * @protected
     * @param {model.file.File} file
     * @returns {Promise.<Array>}
     */
    parseFile(file)
    {
        if (!this._parser)
        {
            return Promise.resolve(false);
        }

        const scope = this;
        const promise = co(function*()
        {
            // Parse
            let result = yield scope._parser.parse(file.contents);
            if (!Array.isArray(result))
            {
                result = [result];
            }

            // Add file
            for (const documentation of result)
            {
                documentation.file = file;
                if (!documentation.name)
                {
                    documentation.name = file.basename;
                }
            }

            return result;
        });

        return promise;
    }

    /**
     * @inheritDocs
     */
    parse(content, options)
    {
        const scope = this;
        const result =
        {
            files: [],
            items: []
        };
        const promise = co(function*()
        {
            // Options
            const opts = options || {};

            // Get files
            const root = content || '/';
            const fileType = opts.fileType || scope.fileType;
            const fileKind = opts.fileKind || scope.fileKind;
            const globs = opts.glob || scope.glob || [];
            const files = yield glob(globs, { root: root });
            if (!files || !files.length)
            {
                return result;
            }

            // Read & parse
            for (const filename of files)
            {
                const file = new File(filename, fileType, fileKind);
                result.files.push(file);
                if (file.contents)
                {
                    const items = yield scope.parseFile(file);
                    if (items)
                    {
                        Array.prototype.push.apply(result.items, items);
                    }
                }
            }

            return result;
        })
        .catch(function(error)
        {
            throw new Error('FileParser - ' + error);
        });
        return promise;
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.FileParser = FileParser;
<commit_msg>enhance(parser): adds better error message when parsing fails<commit_after>'use strict';

/**
 * Requirements
 * @ignore
 */
const Parser = require('./Parser.js').Parser;
const File = require('../model/file/File.js').File;
const ContentType = require('../model/ContentType.js');
const ContentKind = require('../model/ContentKind.js');
const glob = require('../utils/glob.js');
const co = require('co');

/**
 * Reads files based on glob patterns
 */
class FileParser extends Parser
{
    /**
     * @param {object|undefined} options
     */
    constructor(options)
    {
        super();

        // Assign options
        const opts = options || {};
        this._parser = opts.parser || undefined;
        this._glob = opts.glob || [];
        this._fileType = opts.fileType || ContentType.ANY;
        this._fileKind = opts.fileKind || ContentKind.UNKNOWN;
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': ['parser/FileParser.options'] };
    }

    /**
     * @inheritDoc
     */
    static get className()
    {
        return 'parser/FileParser';
    }

    /**
     * @property {Array}
     */
    get glob()
    {
        return this._glob;
    }

    /**
     * @property {Array}
     */
    get fileType()
    {
        return this._fileType;
    }

    /**
     * @property {Array}
     */
    get fileKind()
    {
        return this._fileKind;
    }

    /**
     * Parses a file
     *
     * @protected
     * @param {model.file.File} file
     * @returns {Promise.<Array>}
     */
    parseFile(file)
    {
        if (!this._parser)
        {
            return Promise.resolve(false);
        }

        const scope = this;
        const promise = co(function*()
        {
            // Parse
            let result = yield scope._parser.parse(file.contents);
            if (!Array.isArray(result))
            {
                result = [result];
            }

            // Add file
            for (const documentation of result)
            {
                documentation.file = file;
                if (!documentation.name)
                {
                    documentation.name = file.basename;
                }
            }

            return result;
        });

        return promise;
    }

    /**
     * @inheritDocs
     */
    parse(content, options)
    {
        const scope = this;
        const result =
        {
            files: [],
            items: []
        };
        const promise = co(function*()
        {
            // Options
            const opts = options || {};

            // Get files
            const root = content || '/';
            const fileType = opts.fileType || scope.fileType;
            const fileKind = opts.fileKind || scope.fileKind;
            const globs = opts.glob || scope.glob || [];
            const files = yield glob(globs, { root: root });
            if (!files || !files.length)
            {
                return result;
            }

            // Read & parse
            for (const filename of files)
            {
                const file = new File(filename, fileType, fileKind);
                result.files.push(file);
                if (file.contents)
                {
                    const items = yield scope.parseFile(file);
                    if (items)
                    {
                        Array.prototype.push.apply(result.items, items);
                    }
                }
            }

            return result;
        })
        .catch(function(error)
        {
            throw new Error('FileParser (filename: ' + content + ') - ' + error);
        });
        return promise;
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.FileParser = FileParser;
<|endoftext|>


<commit_before>totNumQuest = 1;

var names = ["Scott", "Fred", "Elizabeth", "Kumar", "Harold", "Jensa", "Maria", "Beth", "Steve", "Harry", "Lucy", "Teneala", "Henrietta", "Bernadette", "Delphinia", "Renea", "Paz", "Stephanie", "Sara", "Sarah", "Larry", "Jerry", "Garry", "Gary"];

function = randomElementOf(theArray) {
  return theArray[Math.floor(Math.random() * theArray.length)];
}

function loadQuestion(qn) {
  if (qn == 1) {
    sides = [4,6,8,12,20]
    side = randomElementOf(sides);
    name1 = randomElementOf(names);
    rollN = Math.floor(Math.random() * 8) + 2;
    rolls =[];
    owside = Math.floor(Math.random()*side)+1;

    question = name1 + " rolls a fair " + side + "-sided die. " + name1 + " rolls the dice " + rollN + " times. ";
    question += "The rolls were: ";
    for (i = 0; i< rollN; i++) {
      rolls.push(Math.floor(Math.random()*side)+1);
      question += rolls[i] + ", ";
    }
    question += ". What is the probability of rolling a " + owside + "?";
    question += "

Enter your answer as a fraction using the '/' symbol. i.e. 1/2.";
    answer = "1/" + side;
    kurl = "https://www.khanacademy.org/math/precalculus/prob-comb/basic-prob-precalc/e/probability_1";
  }
  document.getElementById("question").innerHTML = question;
  document.getElementById("Khan").innerHTML = 'For more practice, visit ' + kurl + '';
}

newQuestion() {
  Qn = Math.floor(Math.random()*totNumQuest)+1;
  loadQuestion(Qn);
}

  newQuestion();
<commit_msg>Update praxis.js<commit_after>totNumQuest = 1;

var names = ["Scott", "Fred", "Elizabeth", "Kumar", "Harold", "Jensa", "Maria", "Beth", "Steve", "Harry", "Lucy",
             "Teneala", "Henrietta", "Bernadette", "Delphinia", "Renea", "Paz", "Stephanie", "Sara", "Sarah", "Larry",
             "Jerry", "Garry", "Gary"];

function = randomElementOf(theArray) {
  return theArray[Math.floor(Math.random() * theArray.length)];
}

function loadQuestion(qn) {
  if (qn == 1) {
    sides = [4,6,8,12,20]
    side = randomElementOf(sides);
    name1 = randomElementOf(names);
    rollN = Math.floor(Math.random() * 8) + 2;
    rolls =[];
    owside = Math.floor(Math.random()*side)+1;

    question = name1 + " rolls a fair " + side + "-sided die. " + name1 + " rolls the dice " + rollN + " times. ";
    question += "The rolls were: ";
    for (i = 0; i< rollN; i++) {
      rolls.push(Math.floor(Math.random()*side)+1);
      question += rolls[i] + ", ";
    }
    question += ". What is the probability of rolling a " + owside + "?";
    question += "

Enter your answer as a fraction using the '/' symbol. i.e. 1/2.";
    answer = "1/" + side;
    kurl = "https://www.khanacademy.org/math/precalculus/prob-comb/basic-prob-precalc/e/probability_1";
  }
  document.getElementById("question").innerHTML = question;
  document.getElementById("Khan").innerHTML = 'For more practice, visit ' + kurl + '';
}

newQuestion() {
  Qn = Math.floor(Math.random()*totNumQuest)+1;
  loadQuestion(Qn);
}

newQuestion();
<|endoftext|>


<commit_before>'use strict';

const { addOauthHeader } = require('@clevercloud/client/cjs/oauth.node.js');
const { prefixUrl } = require('@clevercloud/client/cjs/prefix-url.js');
const { request } = require('@clevercloud/client/cjs/request.superagent.js');
const { conf, loadOAuthConf } = require('../models/configuration.js');

async function loadTokens () {
  const tokens = await loadOAuthConf().toPromise();
  return {
    OAUTH_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY,
    OAUTH_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET,
    API_OAUTH_TOKEN: tokens.token,
    API_OAUTH_TOKEN_SECRET: tokens.secret,
  };
}

async function sendToApi (requestParams) {
  const tokens = await loadTokens();
  return Promise.resolve(requestParams)
    .then(prefixUrl(conf.API_HOST))
    .then(addOauthHeader(tokens))
    .then(request);
}

async function getHostAndTokens () {
  const tokens = await loadTokens();
  return {
    apiHost: conf.API_HOST,
    tokens,
  };
}

module.exports = { sendToApi, getHostAndTokens };
<commit_msg>Use new retry option on superagent.request<commit_after>'use strict';

const { addOauthHeader } = require('@clevercloud/client/cjs/oauth.node.js');
const { prefixUrl } = require('@clevercloud/client/cjs/prefix-url.js');
const { request } = require('@clevercloud/client/cjs/request.superagent.js');
const { conf, loadOAuthConf } = require('../models/configuration.js');

async function loadTokens () {
  const tokens = await loadOAuthConf().toPromise();
  return {
    OAUTH_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY,
    OAUTH_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET,
    API_OAUTH_TOKEN: tokens.token,
    API_OAUTH_TOKEN_SECRET: tokens.secret,
  };
}

async function sendToApi (requestParams) {
  const tokens = await loadTokens();
  return Promise.resolve(requestParams)
    .then(prefixUrl(conf.API_HOST))
    .then(addOauthHeader(tokens))
    .then((requestParams) => request(requestParams, { retry: 1 }));
}

async function getHostAndTokens () {
  const tokens = await loadTokens();
  return {
    apiHost: conf.API_HOST,
    tokens,
  };
}

module.exports = { sendToApi, getHostAndTokens };
<|endoftext|>


<commit_before>function inView(elem) {
	var $elem = $(elem);
	var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
	var viewportTop = $(scrollElem).scrollTop();
	var viewportBottom = viewportTop + $(window).height();
	var elemTop = Math.round( $elem.offset().top );
	var elemBottom = elemTop + $elem.height();
	return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
};

// Scrolls to the selected menu item on the page
$(function() {
	$('a').click(function() {
		if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
			var target = $(this.hash);
			target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
			if (target.length) {
				$('html,body').animate({
					scrollTop: target.offset().top
				}, 1000);
				return false;
			}
		}
	});
});
/* ANIMATE IN VIEW */
$(document).ready(function(){
	/* SCROLLING PAGE ANIMATIONS */
	if(inView($(".name"))){
		$(this).addClass("fadeInDown");
	};
	$(window).scroll(function(){
		/* CUSTOM SCROLL SPY */
		if(inView($(".home"))){
			$(".homenav").addClass("active");
			$(".aboutnav").removeClass("active");
			$(".programmingnav").removeClass("active");
			$(".interestsnav").removeClass("active");
			$(".contactnav").removeClass("active");
		};
		if(inView($(".about"))){
			$(".homenav").removeClass("active");
			$(".aboutnav").addClass("active");
			$(".programmingnav").removeClass("active");
			$(".interestsnav").removeClass("active");
			$(".contactnav").removeClass("active");
		};
		if(inView($(".icon-ruby"))){
			$(".homenav").removeClass("active");
			$(".aboutnav").removeClass("active");
			$(".programmingnav").addClass("active");
			$(".interestsnav").removeClass("active");
			$(".contactnav").removeClass("active");
		};
		if(inView($(".crossfit"))){
			$(".homenav").removeClass("active");
			$(".aboutnav").removeClass("active");
			$(".programmingnav").removeClass("active");
			$(".interestsnav").addClass("active");
			$(".contactnav").removeClass("active");
		};
		if(inView($(".footerz"))){
			$(".homenav").removeClass("active");
			$(".aboutnav").removeClass("active");
			$(".programmingnav").removeClass("active");
			$(".interestsnav").removeClass("active");
			$(".contactnav").addClass("active");
		};
		/* Custom Animations *//*
		if(inView($(".about"))){
			$(".about1").removeClass("hidden");
			$(".about1").addClass("fadeInDown");
		};
		if(inView($(".programming"))){
			$(".programming1").removeClass("hidden");
			$(".programming1").addClass("fadeInDown");
		};
		if(inView($(".interests"))){
			$(".interests1").removeClass("hidden");
			$(".interests1").addClass("fadeInDown");
		};

		if(inView($(".footerz"))){
			$(".contact1").removeClass("hidden");
			$(".contact2").removeClass("hidden");
			$(".contact1").addClass("fadeInLeft");
			$(".contact2").addClass("fadeInRight");
		};*/
		/* BOUNCING SOCIAL BUTTONS *//*
		if(inView($(".footerz"))){
			dance();
        	}; */
	});
});

/*function dance() {
	$(".social1").delay(500).queue(function(){
		$(this).addClass("bounce");
		$(this).dequeue();
	});
	$(".social2").delay(1000).queue(function(){
		$(this).addClass("bounce");
		$(this).dequeue();
	});
	$(".social3").delay(1500).queue(function(){
		$(this).addClass("bounce");
		$(this).dequeue();
	});
}*/

/* NAVBAR HAMBURGER/X ANIMATION */
$(".navbar-toggle").on("click", function () {
	$(this).toggleClass("active");
});

/*---- NAVBAR COLLAPSE ON SCROLL ----*/
$('.navbar-collapse ul li a, .navbar-brand').click(function() {
	$('.navbar-toggle:visible').click();
});

/*---- SQUISHY NAVBAR ----*/
$(window).scroll(function(){
	if ($(".navbar").offset().top > 50) {
  		$(".navbar-fixed-top").addClass("top-nav-collapse");
	}else{
  		$(".navbar-fixed-top").removeClass("top-nav-collapse");
	}
});
<commit_msg>Update script.js<commit_after>function inView(elem) {
	var $elem = $(elem);
	var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
	var viewportTop = $(scrollElem).scrollTop();
	var viewportBottom = viewportTop + $(window).height();
	var elemTop = Math.round( $elem.offset().top );
	var elemBottom = elemTop + $elem.height();
	return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
};

// Scrolls to the selected menu item on the page
$(function() {
	$('a').click(function() {
		if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
			var target = $(this.hash);
			target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
			if (target.length) {
				$('html,body').animate({
					scrollTop: target.offset().top
				}, 1000);
				return false;
			}
		}
	});
});
/* ANIMATE IN VIEW */
$(document).ready(function(){
	/* SCROLLING PAGE ANIMATIONS */
	if(inView($(".name"))){
		$('.name').addClass("fadeInDown");
	};
	$(window).scroll(function(){
		/* CUSTOM SCROLL SPY */
		if(inView($(".home"))){
			$(".homenav").addClass("active");
			$(".aboutnav").removeClass("active");
			$(".programmingnav").removeClass("active");
			$(".interestsnav").removeClass("active");
			$(".contactnav").removeClass("active");
		};
		if(inView($(".about"))){
			$(".homenav").removeClass("active");
			$(".aboutnav").addClass("active");
			$(".programmingnav").removeClass("active");
			$(".interestsnav").removeClass("active");
			$(".contactnav").removeClass("active");
		};
		if(inView($(".icon-ruby"))){
			$(".homenav").removeClass("active");
			$(".aboutnav").removeClass("active");
			$(".programmingnav").addClass("active");
			$(".interestsnav").removeClass("active");
			$(".contactnav").removeClass("active");
		};
		if(inView($(".crossfit"))){
			$(".homenav").removeClass("active");
			$(".aboutnav").removeClass("active");
			$(".programmingnav").removeClass("active");
			$(".interestsnav").addClass("active");
			$(".contactnav").removeClass("active");
		};
		if(inView($(".footerz"))){
			$(".homenav").removeClass("active");
			$(".aboutnav").removeClass("active");
			$(".programmingnav").removeClass("active");
			$(".interestsnav").removeClass("active");
			$(".contactnav").addClass("active");
		};
		/* Custom Animations *//*
		if(inView($(".about"))){
			$(".about1").removeClass("hidden");
			$(".about1").addClass("fadeInDown");
		};
		if(inView($(".programming"))){
			$(".programming1").removeClass("hidden");
			$(".programming1").addClass("fadeInDown");
		};
		if(inView($(".interests"))){
			$(".interests1").removeClass("hidden");
			$(".interests1").addClass("fadeInDown");
		};

		if(inView($(".footerz"))){
			$(".contact1").removeClass("hidden");
			$(".contact2").removeClass("hidden");
			$(".contact1").addClass("fadeInLeft");
			$(".contact2").addClass("fadeInRight");
		};*/
		/* BOUNCING SOCIAL BUTTONS *//*
		if(inView($(".footerz"))){
			dance();
        	}; */
	});
});

/*function dance() {
	$(".social1").delay(500).queue(function(){
		$(this).addClass("bounce");
		$(this).dequeue();
	});
	$(".social2").delay(1000).queue(function(){
		$(this).addClass("bounce");
		$(this).dequeue();
	});
	$(".social3").delay(1500).queue(function(){
		$(this).addClass("bounce");
		$(this).dequeue();
	});
}*/

/* NAVBAR HAMBURGER/X ANIMATION */
$(".navbar-toggle").on("click", function () {
	$(this).toggleClass("active");
});

/*---- NAVBAR COLLAPSE ON SCROLL ----*/
$('.navbar-collapse ul li a, .navbar-brand').click(function() {
	$('.navbar-toggle:visible').click();
});

/*---- SQUISHY NAVBAR ----*/
$(window).scroll(function(){
	if ($(".navbar").offset().top > 50) {
  		$(".navbar-fixed-top").addClass("top-nav-collapse");
	}else{
  		$(".navbar-fixed-top").removeClass("top-nav-collapse");
	}
});
<|endoftext|>


<commit_before>// See: https://developers.soundcloud.com/docs/api/reference
(function(hello) {

	function formatUser(o) {
		if (o.id) {
			o.picture = o.avatar_url;
			o.thumbnail = o.avatar_url;
			o.name = o.username || o.full_name;
		}
	}

	// See: http://developers.soundcloud.com/docs/api/reference#activities
	function paging(res) {
		if ('next_href' in res) {
			res.paging = {
				next: res.next_href
			};
		}
	}

	hello.init({

		soundcloud: {
			name: 'SoundCloud',

			oauth: {
				version: 2,
				auth: 'https://soundcloud.com/connect',
				grant: 'https://soundcloud.com/oauth2/token'
			},

			// Request path translated
			base: 'https://api.soundcloud.com/',
			get: {
				me: 'me.json',

				// http://developers.soundcloud.com/docs/api/reference#me
				'me/friends': 'me/followings.json',
				'me/followers': 'me/followers.json',
				'me/following': 'me/followings.json',

				// See: http://developers.soundcloud.com/docs/api/reference#activities
				default: function(p, callback) {
					// include '.json at the end of each request'
					callback(p.path + '.json');
				}
			},

			// Response handlers
			wrap: {
				me: function(o) {
					formatUser(o);
					return o;
				},

				default: function(o) {
					if (o instanceof Array) {
						o = {
							data: o
						};
						for (var i = 0; i < o.data.length; i++) {
							formatUser(o.data[i]);
						}
					}

					paging(o);
					return o;
				}
			},

			xhr: formatRequest,
			jsonp: formatRequest
		}
	});

	function formatRequest(p, qs) {
		// Alter the querystring
		var token = qs.access_token;
		delete qs.access_token;
		qs.oauth_token = token;
		qs['_status_code_map[302]'] = 200;
		return true;
	}

})(hello);
<commit_msg>JSCS soundcloud module<commit_after>// See: https://developers.soundcloud.com/docs/api/reference
(function(hello) {

	function formatUser(o) {
		if (o.id) {
			o.picture = o.avatar_url;
			o.thumbnail = o.avatar_url;
			o.name = o.username || o.full_name;
		}
	}

	// See: http://developers.soundcloud.com/docs/api/reference#activities
	function paging(res) {
		if ('next_href' in res) {
			res.paging = {
				next: res.next_href
			};
		}
	}

	hello.init({

		soundcloud: {
			name: 'SoundCloud',

			oauth: {
				version: 2,
				auth: 'https://soundcloud.com/connect',
				grant: 'https://soundcloud.com/oauth2/token'
			},

			// Request path translated
			base: 'https://api.soundcloud.com/',
			get: {
				me: 'me.json',

				// http://developers.soundcloud.com/docs/api/reference#me
				'me/friends': 'me/followings.json',
				'me/followers': 'me/followers.json',
				'me/following': 'me/followings.json',

				// See: http://developers.soundcloud.com/docs/api/reference#activities
				default: function(p, callback) {

					// Include '.json at the end of each request'
					callback(p.path + '.json');
				}
			},

			// Response handlers
			wrap: {
				me: function(o) {
					formatUser(o);
					return o;
				},

				default: function(o) {
					if (o instanceof Array) {
						o = {
							data: o
						};
						for (var i = 0; i < o.data.length; i++) {
							formatUser(o.data[i]);
						}
					}

					paging(o);
					return o;
				}
			},

			xhr: formatRequest,
			jsonp: formatRequest
		}
	});

	function formatRequest(p, qs) {
		// Alter the querystring
		var token = qs.access_token;
		delete qs.access_token;
		qs.oauth_token = token;
		qs['_status_code_map[302]'] = 200;
		return true;
	}

})(hello);
<|endoftext|>


<commit_before>class Board {
    // Creates a new board object
    // This is the stuff that should be coming from the view
    constructor(width, height, gameWidth, gameHeight, inputs, outputs, pieces){
        this.layout = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.layout[i] = new Array(gameHeight);
        }
        this.wireStyle = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.wireStyle[i] = new Array(gameHeight);
        }
        this.inputs = inputs;
        this.outputs = outputs;
        this.pieces = pieces;
        this.width = width;
        this.height = height;
    }

    // Uses "private" vars so we also calc dim unit size
    set width(width) {
        this._width = width;
        this.updateBoardDim();
    }
    get width() {
        return this._width;
    }
    set height(height) {
        this._height = height;
        this.updateBoardDim();
    }
    get height() {
        return this._height;
    }

    // Dinamicaly set the unit scale of pieces based on the new width and height
    updateBoardDim() {
        // Find a scale unit on the board
        // This is the number of pixels a square takes up
        var unitWidth = Math.trunc((this.width - 20) / this.gameWidth);
        var unitHeight = Math.trunc((this.height - 30) / (this.gameHeight + 1));
        if (unitWidth < unitHeight) {
            this._unit = unitWidth;
        } else {
            this._unit = unitHeight;
        }
        this._inputLocations = new Array(this.inputs.length);
        var seperation = Math.trunc(this.gameHeight / this.inputs.length);
        var start = Math.trunc(seperation / 2);
        this._inputLocations[0] = start;
        for (var i = 1; i < this.inputs.length; i++) {
            this._inputLocations[i] = start + (i * seperation);
        }
        this._outputLocations = new Array(this.inputs.length);
        seperation = Math.trunc(this.gameHeight / this.outputs.length);
        start = Math.trunc(seperation / 2);
        this._outputLocations[0] = start;
        for (var i = 1; i < this.outputs.length; i++) {
            this._outputLocations[i] = start + (i * seperation);
        }
    }

    // Returns the private unit calculation
    get unit() {
        return this._unit;
    }

    // Commom values that are needed in a lot of places so can be got
    // as if they were variables themselves
    get gameWidth() { return this.layout.length; }
    get gameHeight() { return this.layout[0].length; }
    get boardWidth() { return this.unit * this.gameWidth; }
    get boardHeight() { return this.unit * this.gameHeight; }
    get boardX() { return Math.trunc((this.width - this.boardWidth) / 2); }
    get boardY() { return Math.trunc((this.height - this.boardHeight - this.unit) / 2) - 5; }
    get inputLocations() { return this._inputLocations }
    get outputLocations() { return this._outputLocations }

    // These are common calculations that require extra bits of info such as x and y cords
    getBoardX(x) { return Math.trunc((x - this.boardX) / this.unit); }
    getBoardY(y) { return Math.trunc((y - this.boardY) / this.unit); }
    onBoard(x, y) { return 0 <= y && 0 <= x && y < this.gameHeight && x < this.gameWidth}

    /**
     * Returns a piece from the board and removes it from the board
     * based on x and y cordanate location
     *
     * @param x corordanate on the canvas that was drawn to
     * @param y corordanate on the canvas that was drawn to
     * @return game piece
     */
    getPiece(x, y) {
        // Start by seeing if the piece is in the y height of the dock
        var tmp = (y - this.boardY - this.boardHeight - 10);
        if (tmp > 0 && tmp < this.unit) {
            // Then check to see if there is a piece there for it
            tmp = this.getBoardX(x);
            if (0 <= tmp && tmp < this.pieces.length){
                // If there is remove the piece from the list and return it
                return this.pieces.splice(tmp, 1)[0];
            }
        } else {
            // Start by seing if the x, y is on the board
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            if (this.onBoard(cx, cy)) {
                // If it is remove it and return it
                tmp = this.layout[cx][cy];
                this.layout[cx][cy] = undefined;
                this._updateWire(cx, cy);
                return tmp;
            }
        }
        return null;
    }

    /**
     * This sets a piece on the board based on screen cords to a piece id that is passed in
     *
     * @param x corodanate on the canvas that is drawn to
     * @param y corodanate on the canvas that is drawn to
     * @param p an id identifying what piece to place
     */
    setPiece(x, y, p) {
        // Make sure there is a piece and its not wire
        if (![0, null, undefined].includes(p)) {
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            // Check to see if the location is on the board and the board doesn't already have a piece there
            if (this.onBoard(cx, cy) && [0, null, undefined].includes(this.layout[cx][cy])) {
                // If its good add it to the locaiton
                this.layout[cx][cy] = p;
                this._updateWire(cx, cy);
            } else {
                // The spot was invalid so we should add it to the end of the palate so we don't loose it
                this.pieces.push(p);
            }
        }
    }

    /**
     * This is for the drawing of wires on the board
     *
     * @param x corodanate on the canvas that is drawn to
     * @param y corodanate on the canvas that is drawn to
     * @param p an id identifying what piece was last clicked on
     */
    toogleWire(x, y, piece) {
        // If the piece that was given is a wire or nothing
        if ([0, null, undefined].includes(piece)) {
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            // If the spot was on the board and not a piece
            if (this.onBoard(cx, cy) && [0, null, undefined].includes(this.layout[cx][cy])) {
                // Then set it to the oposite of the piece given
                this.layout[cx][cy] = (piece == 0) ? undefined : 0;
                this._updateWire(cx, cy);
            }
        }
    }

    // Only update the wires around the new one
    _updateWire(x, y) {
        this._setWire(x, y);
        if (x > 0) this._setWire(x - 1, y);
        if (x < this.gameWidth - 1) this._setWire(x + 1,  y);
        if (y > 0) this._setWire(x, y - 1);
        if (y < this.gameHeight - 1) this._setWire(x,  y + 1);
    }
    _setWire(x , y) {
        // console.log(x + " " + y);
        if(this.layout[x][y] != null) {
            var sides = new Array(4);
            // Left
            sides[0] = [0, 3].includes(this.layout[x][y])
                && ((x == 0 && this.inputLocations.includes(y))
                || (x > 0 && [0, 1, 2, 3].includes(this.layout[x - 1][y])));
            // Right
            sides[1] = (x == (this.gameWidth - 1) && this.outputLocations.includes(y))
                || (x < this.gameWidth - 1 && [0, 3].includes(this.layout[x + 1][y]));
            // Top
            if (this.layout[x][y] != 3) {
                sides[2] = (y > 0 && [0, 1, 2].includes(this.layout[x][y - 1]));
                // Bottom
                sides[3] = (y < this.gameHeight - 1 && [0, 1, 2].includes(this.layout[x][y + 1]));
            } else {
                sides[2] = sides[3] = false;
            }

            var num = 0
            sides.forEach(function(element, index, array){
                if (element) num = num | Math.pow(2, array.length - 1 - index);
            });
            this.wireStyle[x][y] = num;
        } else {
            this.wireStyle[x][y] = null;
        }
        // console.log(this.wireStyle);
    }
}
<commit_msg>Started calc<commit_after>class Board {
    // Creates a new board object
    // This is the stuff that should be coming from the view
    constructor(width, height, gameWidth, gameHeight, inputs, outputs, pieces){
        this.layout = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.layout[i] = new Array(gameHeight);
        }
        this.wireStyle = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.wireStyle[i] = new Array(gameHeight);
        }
        this.answer = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.answer[i] = new Array(gameHeight);
        }
        this.inputs = inputs;
        this.outputs = outputs;
        this.pieces = pieces;
        this.width = width;
        this.height = height;
        this.state = 0;
    }

    // Uses "private" vars so we also calc dim unit size
    set width(width) {
        this._width = width;
        this.updateBoardDim();
    }
    get width() {
        return this._width;
    }
    set height(height) {
        this._height = height;
        this.updateBoardDim();
    }
    get height() {
        return this._height;
    }

    // Dinamicaly set the unit scale of pieces based on the new width and height
    updateBoardDim() {
        // Find a scale unit on the board
        // This is the number of pixels a square takes up
        var unitWidth = Math.trunc((this.width - 20) / this.gameWidth);
        var unitHeight = Math.trunc((this.height - 30) / (this.gameHeight + 1));
        if (unitWidth < unitHeight) {
            this._unit = unitWidth;
        } else {
            this._unit = unitHeight;
        }
        this._inputLocations = new Array(this.inputs.length);
        var seperation = Math.trunc(this.gameHeight / this.inputs.length);
        var start = Math.trunc(seperation / 2);
        this._inputLocations[0] = start;
        for (var i = 1; i < this.inputs.length; i++) {
            this._inputLocations[i] = start + (i * seperation);
        }
        this._outputLocations = new Array(this.inputs.length);
        seperation = Math.trunc(this.gameHeight / this.outputs.length);
        start = Math.trunc(seperation / 2);
        this._outputLocations[0] = start;
        for (var i = 1; i < this.outputs.length; i++) {
            this._outputLocations[i] = start + (i * seperation);
        }
    }

    // Returns the private unit calculation
    get unit() {
        return this._unit;
    }

    // Commom values that are needed in a lot of places so can be got
    // as if they were variables themselves
    get gameWidth() { return this.layout.length; }
    get gameHeight() { return this.layout[0].length; }
    get boardWidth() { return this.unit * this.gameWidth; }
    get boardHeight() { return this.unit * this.gameHeight; }
    get boardX() { return Math.trunc((this.width - this.boardWidth) / 2); }
    get boardY() { return Math.trunc((this.height - this.boardHeight - this.unit) / 2) - 5; }
    get inputLocations() { return this._inputLocations }
    get outputLocations() { return this._outputLocations }

    // These are common calculations that require extra bits of info such as x and y cords
    getBoardX(x) { return Math.trunc((x - this.boardX) / this.unit); }
    getBoardY(y) { return Math.trunc((y - this.boardY) / this.unit); }
    onBoard(x, y) { return 0 <= y && 0 <= x && y < this.gameHeight && x < this.gameWidth}

    /**
     * Returns a piece from the board and removes it from the board
     * based on x and y cordanate location
     *
     * @param x corordanate on the canvas that was drawn to
     * @param y corordanate on the canvas that was drawn to
     * @return game piece
     */
    getPiece(x, y) {
        // Start by seeing if the piece is in the y height of the dock
        var tmp = (y - this.boardY - this.boardHeight - 10);
        if (tmp > 0 && tmp < this.unit) {
            // Then check to see if there is a piece there for it
            tmp = this.getBoardX(x);
            if (0 <= tmp && tmp < this.pieces.length){
                // If there is remove the piece from the list and return it
                return this.pieces.splice(tmp, 1)[0];
            }
        } else {
            // Start by seing if the x, y is on the board
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            if (this.onBoard(cx, cy)) {
                // If it is remove it and return it
                tmp = this.layout[cx][cy];
                this.layout[cx][cy] = undefined;
                this._updateWire(cx, cy);
                return tmp;
            }
        }
        return null;
    }

    /**
     * This sets a piece on the board based on screen cords to a piece id that is passed in
     *
     * @param x corodanate on the canvas that is drawn to
     * @param y corodanate on the canvas that is drawn to
     * @param p an id identifying what piece to place
     */
    setPiece(x, y, p) {
        // Make sure there is a piece and its not wire
        if (![0, null, undefined].includes(p)) {
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            // Check to see if the location is on the board and the board doesn't already have a piece there
            if (this.onBoard(cx, cy) && [0, null, undefined].includes(this.layout[cx][cy])) {
                // If its good add it to the locaiton
                this.layout[cx][cy] = p;
                this._updateWire(cx, cy);
            } else {
                // The spot was invalid so we should add it to the end of the palate so we don't loose it
                this.pieces.push(p);
            }
        }
    }

    /**
     * This is for the drawing of wires on the board
     *
     * @param x corodanate on the canvas that is drawn to
     * @param y corodanate on the canvas that is drawn to
     * @param p an id identifying what piece was last clicked on
     */
    toogleWire(x, y, piece) {
        // If the piece that was given is a wire or nothing
        if ([0, null, undefined].includes(piece)) {
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            // If the spot was on the board and not a piece
            if (this.onBoard(cx, cy) && [0, null, undefined].includes(this.layout[cx][cy])) {
                // Then set it to the oposite of the piece given
                this.layout[cx][cy] = (piece == 0) ? undefined : 0;
                this._updateWire(cx, cy);
            }
        }
    }

    // Only update the wires around the new one
    _updateWire(x, y) {
        this._setWire(x, y);
        if (x > 0) this._setWire(x - 1, y);
        if (x < this.gameWidth - 1) this._setWire(x + 1,  y);
        if (y > 0) this._setWire(x, y - 1);
        if (y < this.gameHeight - 1) this._setWire(x,  y + 1);
    }
    _setWire(x , y) {
        // console.log(x + " " + y);
        if(this.layout[x][y] != null) {
            var sides = new Array(4);
            // Left
            sides[0] = [0, 3].includes(this.layout[x][y])
                && ((x == 0 && this.inputLocations.includes(y))
                || (x > 0 && [0, 1, 2, 3].includes(this.layout[x - 1][y])));
            // Right
            sides[1] = (x == (this.gameWidth - 1) && this.outputLocations.includes(y))
                || (x < this.gameWidth - 1 && [0, 3].includes(this.layout[x + 1][y]));
            // Top
            if (this.layout[x][y] != 3) {
                sides[2] = (y > 0 && [0, 1, 2].includes(this.layout[x][y - 1]));
                // Bottom
                sides[3] = (y < this.gameHeight - 1 && [0, 1, 2].includes(this.layout[x][y + 1]));
            } else {
                sides[2] = sides[3] = false;
            }

            var num = 0
            sides.forEach(function(element, index, array){
                if (element) num = num | Math.pow(2, array.length - 1 - index);
            });
            this.wireStyle[x][y] = num;
        } else {
            this.wireStyle[x][y] = null;
        }
        // console.log(this.wireStyle);
    }

    calculate() {
        this.answer = new Array(this.gameWidth);
        for(var i = 0; i < this.gameWidth; i++){
            this.answer[i] = new Array(this.gameHeight);
        }
        // Create new queue
        var queue = [];
        // Add the starts to it
        queue.push(this.inputLocations);

        // Set the starts to the input states
        board.inputLocations.forEach(
            function(element, index){
               this.answers[0][element] = board.inputs[index][this.state]
            }
        );
        this.visited = new Array(this.gameWidth);
        for(var i = 0; i < this.gameWidth; i++){
            this.visited[i] = new Array(this.gameHeight);
        }
    }
}
<|endoftext|>


<commit_before>var csso = require('gulp-csso');
var filter = require('gulp-filter');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var minifyHtml = require('gulp-minify-html');
var path = require('path');
var pngquant = require('imagemin-pngquant');
var rev = require('gulp-rev');
var revReplace = require('gulp-rev-replace');
var svgmin = require('gulp-svgmin');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');

var assets = [
  'frontend/index.html',
  'frontend/svgdefs.svg',
  'frontend/bundle.js',
  'frontend/favicons/*.png',
  'frontend/robots.txt'
];
// there's no css because they will be concatenated by gulp-useref

var assetsFilter = filter([
  '*.svg', 'bundle.css', 'bundle.js', 'favicons/*.png'
]);

var indexFilter = filter('index.html');
var userefAssets = useref.assets();

gulp
  .src(['frontend/index.html'].concat(assets), {
    base: path.join(__dirname, '..', 'frontend')
  })
  // let's work on the index page to
  // concatenate needed assets
  .pipe(indexFilter)
  // this is how gulp-useref is used, no mistake
  .pipe(userefAssets)
  .pipe(userefAssets.restore())
  .pipe(useref())
  // now minify the index page
  .pipe(gulpif(/index\.html$/, minifyHtml()))
  .pipe(indexFilter.restore())
  // let's work on assets
  .pipe(assetsFilter)
  // minify them
  .pipe(gulpif(/bundle\.css$/, csso()))
  .pipe(gulpif(/bundle\.js$/, uglify()))
  .pipe(gulpif(/svgdefs\.svg$/, svgmin({
    plugins: [{
      cleanupIDs: false
    }]
  })))
  .pipe(gulpif(/\.png$/, pngquant({
    speed: 1,
    quality: '65-80'
  })()))
  // rev them (md5)
  .pipe(rev())
  .pipe(assetsFilter.restore())
  // replace revs everywhere, inside css, js, html
  .pipe(revReplace())
  .pipe(gulp.dest('public'));
<commit_msg>simplify filters in build<commit_after>var csso = require('gulp-csso');
var filter = require('gulp-filter');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var minifyHtml = require('gulp-minify-html');
var path = require('path');
var pngquant = require('imagemin-pngquant');
var rev = require('gulp-rev');
var revReplace = require('gulp-rev-replace');
var svgmin = require('gulp-svgmin');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');

var sources = [
  'frontend/index.html',
  'frontend/svgdefs.svg',
  'frontend/bundle.js',
  'frontend/favicons/*.png',
  'frontend/robots.txt'
];
// there's no css because they will be concatenated by gulp-useref

var assetsFilter = filter([
  '**/*', '!index.html', '!robots.txt'
]);

var indexFilter = filter('index.html');
var userefAssets = useref.assets();

gulp
  .src(sources, {
    base: path.join(__dirname, '..', 'frontend')
  })
  // let's work on the index page to
  // concatenate needed assets
  .pipe(indexFilter)
  // this is how gulp-useref is used, no mistake
  // it finds builds blocks and then concatenate them
  // we could also use https://github.com/klei/gulp-inject
  .pipe(userefAssets)
  .pipe(userefAssets.restore())
  .pipe(useref())
  // now minify the index page
  .pipe(gulpif(/index\.html$/, minifyHtml()))
  .pipe(indexFilter.restore())
  // let's work on assets
  .pipe(assetsFilter)
  // minify them
  .pipe(gulpif(/bundle\.css$/, csso()))
  .pipe(gulpif(/bundle\.js$/, uglify()))
  .pipe(gulpif(/svgdefs\.svg$/, svgmin({
    plugins: [{
      cleanupIDs: false
    }]
  })))
  .pipe(gulpif(/\.png$/, pngquant({
    speed: 1,
    quality: '65-80'
  })()))
  // rev them (md5)
  .pipe(rev())
  .pipe(assetsFilter.restore())
  // replace revs everywhere, inside css, js, html
  .pipe(revReplace())
  .pipe(gulp.dest('public'));
<|endoftext|>


<commit_before>var fs = require('fs');
var os = require('os');
var sh = require('child_process').execSync;
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var path = require('path');

var ROOT = process.cwd();
var NODEJS = '.';
var SYNC = false;

if (os.platform() == 'win32') {
  process.chdir(path.resolve(ROOT, '..'));
  ROOT = process.cwd();
  NODEJS = path.resolve(process.env['USERPROFILE'], '.node-gyp', process.version.substring(1));
} else {
  NODEJS = path.resolve(process.env['HOME'], '.node-gyp', process.version.substring(1));
}

if (fs.existsSync(ROOT + path.sep + 'nodejs.gypi')) {
  fs.unlinkSync(ROOT + path.sep + 'nodejs.gypi');
}

if (!fs.existsSync(ROOT + path.sep + 'build' + path.sep + 'config.gypi')) {
  throw new Error('Run node-gyp rebuild instead of node build.js');
}

if (os.platform() == 'linux') {
  if (fs.existsSync('/usr/include/node/common.gypi')) {
    fs.linkSync('/usr/include/node/common.gypi', ROOT + path.sep + 'nodejs.gypi');
  }
} else {
  fs.linkSync(NODEJS + path.sep + 'common.gypi', ROOT + path.sep + 'nodejs.gypi');
}

var CONFIG = 'Release';

if (fs.existsSync(ROOT + path.sep + 'build' + path.sep + 'Debug')) {
  CONFIG = 'Debug';
}

var THIRD_PARTY = path.resolve(ROOT, 'third_party');
var DEPOT_TOOLS_REPO = 'https://chromium.googlesource.com/chromium/tools/depot_tools.git';
var DEPOT_TOOLS = path.resolve(THIRD_PARTY, 'depot_tools');
var WEBRTC = path.resolve(THIRD_PARTY, 'webrtc');
var WEBRTC_SRC = path.resolve(WEBRTC, 'src');
var WEBRTC_OUT = path.resolve(WEBRTC_SRC, 'out', CONFIG);
var FETCH = path.resolve(DEPOT_TOOLS, (os.platform() == 'win32') ? 'fetch.bat' : 'fetch');
var GCLIENT = path.resolve(DEPOT_TOOLS, (os.platform() == 'win32') ? 'gclient.bat' : 'gclient');

if (os.platform() == 'win32' && process.arch == 'x64') {
  WEBRTC_OUT = path.resolve(WEBRTC_SRC, 'out', CONFIG + '_x64');
}

function build() {
  if (fs.existsSync(WEBRTC_SRC)) {
    sh('python ' + WEBRTC_SRC + path.sep + 'webrtc' + path.sep + 'build' + path.sep + 'gyp_webrtc src' + path.sep + 'webrtc.gyp', {
      cwd: ROOT,
      env: process.env,
      stdio: 'inherit',
    });

    sh('ninja -C ' + WEBRTC_OUT, {
      cwd: WEBRTC_SRC,
      env: process.env,
      stdio: 'inherit',
    });

    fs.linkSync(WEBRTC_OUT + path.sep + 'webrtc-native.node', ROOT + path.sep + 'build' + path.sep + CONFIG + path.sep + 'webrtc-native.node');
    console.log('Done! :)');
  }
}

function sync() {
  if (!SYNC) {
    if (fs.existsSync(THIRD_PARTY + path.sep + 'webrtc_sync')) {
      var stat = fs.statSync(THIRD_PARTY + path.sep + 'webrtc_sync');

      if (((new Date().getTime()) - stat.mtime.getTime()) > 86400000) {
        SYNC = true;
      }
    } else {
      SYNC = true;
    }
  }

  if (!SYNC) {
    return build();
  }

  var res = spawn(GCLIENT, ['sync'], {
    cwd: WEBRTC,
    env: process.env,
    stdio: 'inherit',
  });

  res.on('close', function (code) {
    if (!code) {
      fs.closeSync(fs.openSync(THIRD_PARTY + path.sep + 'webrtc_sync', 'w'));
      return build();
    }

    process.exit(1);
  });
}

function configure() {
  process.env['GYP_DEFINES'] += ' third_party=' + THIRD_PARTY;
  process.env['GYP_DEFINES'] += ' target_arch=' + process.arch;
  process.env['GYP_DEFINES'] += ' host_arch=' + process.arch;
  process.env['GYP_DEFINES'] += ' nodedir=' + NODEJS;
  process.env['GYP_DEFINES'] += ' configuration=' + CONFIG;
  process.env['GYP_DEFINES'] += ' build_with_chromium=0';
  process.env['GYP_DEFINES'] += ' include_tests=0';
  process.env['GYP_DEFINES'] += ' uv_library=static_library';

  switch (os.platform()) {
    case 'darwin':
      process.env['GYP_DEFINES'] += ' clang=1';

      break;
    case 'win32':
      process.env['DEPOT_TOOLS_WIN_TOOLCHAIN'] = 0;

      break;
    case 'linux':
      process.env['GYP_DEFINES'] += ' clang=0';

      if (!process.env['JAVA_HOME']) {
        if (fs.existsSync('/usr/lib/jvm/java')) {
          process.env['JAVA_HOME'] = '/usr/lib/jvm/java';
        } else {
          process.env['JAVA_HOME'] = '/usr/lib/jvm/default-java';
        }
      }

      break;
    default:
      break;
  }

  console.log('target_arch =', process.arch);
  console.log('host_arch =', process.arch);
  console.log('configuration =', CONFIG);

  sync();
}

function fetch(rerun) {
  if (!fs.existsSync(WEBRTC) || !fs.existsSync(WEBRTC_SRC)) {
    if (!fs.existsSync(WEBRTC)) {
      fs.mkdirSync(WEBRTC);
    }

    var res = spawn(FETCH, ['--nohooks', 'webrtc'], {
      cwd: WEBRTC,
      env: process.env,
      stdio: 'inherit',
    });

    res.on('close', function (code) {
      if (!code) {
        return configure();
      }

      if (os.platform() == 'win32' && !rerun) {
        return fetch(true);
      }

      process.exit(1);
    });
  } else {
    configure();
  }
}

function prep() {
  process.env['GYP_DEFINES'] = process.env['GYP_DEFINES'] ? process.env['GYP_DEFINES'] : '';

  if (!fs.existsSync(THIRD_PARTY)) {
    fs.mkdirSync(THIRD_PARTY);
  }

  if (!fs.existsSync(DEPOT_TOOLS)) {
    sh('git clone ' + DEPOT_TOOLS_REPO, {
      cwd: THIRD_PARTY,
      env: process.env,
      stdio: 'inherit',
    });
  }

  process.env['PATH'] = process.env['PATH'] + path.delimiter + DEPOT_TOOLS;
  fetch(false);
}

// TODO(): apt-get install

prep();
<commit_msg>Fix link<commit_after>var fs = require('fs');
var os = require('os');
var sh = require('child_process').execSync;
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var path = require('path');

var ROOT = process.cwd();
var NODEJS = '.';
var SYNC = false;

if (os.platform() == 'win32') {
  process.chdir(path.resolve(ROOT, '..'));
  ROOT = process.cwd();
  NODEJS = path.resolve(process.env['USERPROFILE'], '.node-gyp', process.version.substring(1));
} else {
  NODEJS = path.resolve(process.env['HOME'], '.node-gyp', process.version.substring(1));
}

if (fs.existsSync(ROOT + path.sep + 'nodejs.gypi')) {
  fs.unlinkSync(ROOT + path.sep + 'nodejs.gypi');
}

if (!fs.existsSync(ROOT + path.sep + 'build' + path.sep + 'config.gypi')) {
  throw new Error('Run node-gyp rebuild instead of node build.js');
}

if (os.platform() == 'linux') {
  if (fs.existsSync('/usr/include/node/common.gypi')) {
    fs.createReadStream('/usr/include/node/common.gypi').pipe(fs.createWriteStream(ROOT + path.sep + 'nodejs.gypi'));
  }
} else {
  fs.linkSync(NODEJS + path.sep + 'common.gypi', ROOT + path.sep + 'nodejs.gypi');
}

var CONFIG = 'Release';

if (fs.existsSync(ROOT + path.sep + 'build' + path.sep + 'Debug')) {
  CONFIG = 'Debug';
}

var THIRD_PARTY = path.resolve(ROOT, 'third_party');
var DEPOT_TOOLS_REPO = 'https://chromium.googlesource.com/chromium/tools/depot_tools.git';
var DEPOT_TOOLS = path.resolve(THIRD_PARTY, 'depot_tools');
var WEBRTC = path.resolve(THIRD_PARTY, 'webrtc');
var WEBRTC_SRC = path.resolve(WEBRTC, 'src');
var WEBRTC_OUT = path.resolve(WEBRTC_SRC, 'out', CONFIG);
var FETCH = path.resolve(DEPOT_TOOLS, (os.platform() == 'win32') ? 'fetch.bat' : 'fetch');
var GCLIENT = path.resolve(DEPOT_TOOLS, (os.platform() == 'win32') ? 'gclient.bat' : 'gclient');

if (os.platform() == 'win32' && process.arch == 'x64') {
  WEBRTC_OUT = path.resolve(WEBRTC_SRC, 'out', CONFIG + '_x64');
}

function build() {
  if (fs.existsSync(WEBRTC_SRC)) {
    sh('python ' + WEBRTC_SRC + path.sep + 'webrtc' + path.sep + 'build' + path.sep + 'gyp_webrtc src' + path.sep + 'webrtc.gyp', {
      cwd: ROOT,
      env: process.env,
      stdio: 'inherit',
    });

    sh('ninja -C ' + WEBRTC_OUT, {
      cwd: WEBRTC_SRC,
      env: process.env,
      stdio: 'inherit',
    });

    fs.linkSync(WEBRTC_OUT + path.sep + 'webrtc-native.node', ROOT + path.sep + 'build' + path.sep + CONFIG + path.sep + 'webrtc-native.node');
    console.log('Done! :)');
  }
}

function sync() {
  if (!SYNC) {
    if (fs.existsSync(THIRD_PARTY + path.sep + 'webrtc_sync')) {
      var stat = fs.statSync(THIRD_PARTY + path.sep + 'webrtc_sync');

      if (((new Date().getTime()) - stat.mtime.getTime()) > 86400000) {
        SYNC = true;
      }
    } else {
      SYNC = true;
    }
  }

  if (!SYNC) {
    return build();
  }

  var res = spawn(GCLIENT, ['sync'], {
    cwd: WEBRTC,
    env: process.env,
    stdio: 'inherit',
  });

  res.on('close', function (code) {
    if (!code) {
      fs.closeSync(fs.openSync(THIRD_PARTY + path.sep + 'webrtc_sync', 'w'));
      return build();
    }

    process.exit(1);
  });
}

function configure() {
  process.env['GYP_DEFINES'] += ' third_party=' + THIRD_PARTY;
  process.env['GYP_DEFINES'] += ' target_arch=' + process.arch;
  process.env['GYP_DEFINES'] += ' host_arch=' + process.arch;
  process.env['GYP_DEFINES'] += ' nodedir=' + NODEJS;
  process.env['GYP_DEFINES'] += ' configuration=' + CONFIG;
  process.env['GYP_DEFINES'] += ' build_with_chromium=0';
  process.env['GYP_DEFINES'] += ' include_tests=0';
  process.env['GYP_DEFINES'] += ' uv_library=static_library';

  switch (os.platform()) {
    case 'darwin':
      process.env['GYP_DEFINES'] += ' clang=1';

      break;
    case 'win32':
      process.env['DEPOT_TOOLS_WIN_TOOLCHAIN'] = 0;

      break;
    case 'linux':
      process.env['GYP_DEFINES'] += ' clang=0';

      if (!process.env['JAVA_HOME']) {
        if (fs.existsSync('/usr/lib/jvm/java')) {
          process.env['JAVA_HOME'] = '/usr/lib/jvm/java';
        } else {
          process.env['JAVA_HOME'] = '/usr/lib/jvm/default-java';
        }
      }

      break;
    default:
      break;
  }

  console.log('target_arch =', process.arch);
  console.log('host_arch =', process.arch);
  console.log('configuration =', CONFIG);

  sync();
}

function fetch(rerun) {
  if (!fs.existsSync(WEBRTC) || !fs.existsSync(WEBRTC_SRC)) {
    if (!fs.existsSync(WEBRTC)) {
      fs.mkdirSync(WEBRTC);
    }

    var res = spawn(FETCH, ['--nohooks', 'webrtc'], {
      cwd: WEBRTC,
      env: process.env,
      stdio: 'inherit',
    });

    res.on('close', function (code) {
      if (!code) {
        return configure();
      }

      if (os.platform() == 'win32' && !rerun) {
        return fetch(true);
      }

      process.exit(1);
    });
  } else {
    configure();
  }
}

function prep() {
  process.env['GYP_DEFINES'] = process.env['GYP_DEFINES'] ? process.env['GYP_DEFINES'] : '';

  if (!fs.existsSync(THIRD_PARTY)) {
    fs.mkdirSync(THIRD_PARTY);
  }

  if (!fs.existsSync(DEPOT_TOOLS)) {
    sh('git clone ' + DEPOT_TOOLS_REPO, {
      cwd: THIRD_PARTY,
      env: process.env,
      stdio: 'inherit',
    });
  }

  process.env['PATH'] = process.env['PATH'] + path.delimiter + DEPOT_TOOLS;
  fetch(false);
}

// TODO(): apt-get install

prep();
<|endoftext|>


<commit_before>import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'

function buildDistFile(filename) {
  return new Promise((resolve, reject) => {
    console.log(`Processing ./${filename}.css...`)

    fs.readFile(`./${filename}.css`, (err, css) => {
      if (err) throw err

      return postcss([tailwind(), require('autoprefixer')])
        .process(css, {
          from: `./${filename}.css`,
          to: `./dist/${filename}.css`,
        })
        .then(result => {
          fs.writeFileSync(`./dist/${filename}.css`, result.css)
          return result
        })
        .then(result => {
          const minified = new CleanCSS().minify(result.css)
          fs.writeFileSync(`./dist/${filename}.min.css`, minified.styles)
        })
        .then(resolve)
        .catch(error => {
          console.log(error)
          reject()
        })
    })
  })
}

console.info('Building Tailwind!')

Promise.all([
  buildDistFile('base'),
  buildDistFile('components'),
  buildDistFile('utilities'),
  buildDistFile('tailwind'),
]).then(() => {
  console.log('Finished Building Tailwind!')
})
<commit_msg>Generate experimental build for CDN<commit_after>import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'

function buildDistFile(filename, config = {}, outFilename = filename) {
  return new Promise((resolve, reject) => {
    console.log(`Processing ./${filename}.css...`)

    fs.readFile(`./${filename}.css`, (err, css) => {
      if (err) throw err

      return postcss([tailwind(config), require('autoprefixer')])
        .process(css, {
          from: `./${filename}.css`,
          to: `./dist/${outFilename}.css`,
        })
        .then(result => {
          fs.writeFileSync(`./dist/${outFilename}.css`, result.css)
          return result
        })
        .then(result => {
          const minified = new CleanCSS().minify(result.css)
          fs.writeFileSync(`./dist/${outFilename}.min.css`, minified.styles)
        })
        .then(resolve)
        .catch(error => {
          console.log(error)
          reject()
        })
    })
  })
}

console.info('Building Tailwind!')

Promise.all([
  buildDistFile('base'),
  buildDistFile('components'),
  buildDistFile('utilities'),
  buildDistFile('tailwind'),
  buildDistFile('tailwind', { future: 'all', experimental: 'all' }, 'tailwind-experimental'),
]).then(() => {
  console.log('Finished Building Tailwind!')
})
<|endoftext|>


<commit_before>function Entry(data)
{
  this.portal = data.portal ? data.portal : r.portal.data;
  this.message = data.message;
  this.timestamp = data.timestamp;
  this.dat = data.dat;
  this.id = data.id;
  this.editstamp = data.editstamp;
  this.media = data.media;
  this.target = data.target;
  this.seed = data.seed;

  this.to_json = function()
  {
    return {message:this.message,timestamp:this.timestamp,editstamp:this.editstamp,media:this.media,target:this.target};
  }

  this.to_html = function()
  {
    var html = "";

    html += "";

    html += "<t class='portal'>"+(this.seed ? "@" : "~")+this.portal+""+(this.target ? " > "+("@"+r.operator.name_pattern.exec(this.message)[1])+"" : "")+"</t>";

    if(this.portal == r.portal.data.name){
      html += this.editstamp ? "<c class='editstamp' data-operation='"+('edit:'+this.id+' '+this.message.replace("'",""))+"'>edited "+timeSince(this.editstamp)+" ago</c>" : "<c class='timestamp' data-operation='edit:"+this.id+" "+this.message.replace("'","")+"'>"+timeSince(this.timestamp)+" ago</c>";
    }
    else{
      html += this.editstamp ? "<c class='editstamp' data-operation='"+this.portal+": '>edited "+timeSince(this.editstamp)+" ago</c>" : "<c class='timestamp' data-operation='"+this.portal+": '>"+timeSince(this.timestamp)+" ago</c>";
    }
    html += "
";
    html += "<t class='message' dir='auto'>"+(this.formatter(this.message))+"</t>
";

    if(this.media){
      var parts = this.media.split(".")
      if (parts.length === 1) { this.media += ".jpg" } // support og media uploads
      html += "";
    }
    return "
"+html+"

";
  }

  this.formatter = function(message)
  {
    var m = message;

    m = this.escape_html(m);
    m = this.format_links(m);
    m = this.highlight_portal(m);
    m = this.link_portals(m);
    m = this.format_style(m);

    return m;
  }

  this.escape_html = function(m)
  {
    return m
      .replace(/&/g, "&")
      .replace(/</g, "<")
      .replace(/>/g, ">")
      .replace(/"/g, """)
      .replace(/'/g, "'");
  }

  this.format_links = function(m)
  {
    var words = m.split(" ");
    var n = [];
    for(id in words){
      var word = words[id];
      if(word.substr(0,6) == "dat://"){
        var compressed = word.substr(0,12)+".."+word.substr(word.length-3,2);
        n.push(""+compressed+"");
      }
      else if(word.substr(0,1) == "#"){
        n.push("<c class='hashtag' data-operation='filter "+word+"'>"+word+"</c>");
      }
      else if (word.search(/^https?:\/\//) != -1) {
        try {
          var url = new URL(word)
          var compressed = word.substr(word.indexOf("://")+3,url.hostname.length + 15)+"..";
          n.push(""+compressed+"");
        } catch(e) {
          console.error("Error when parsing url:", word, e);
          n.push(word);
        }
      }
      else{
        n.push(word)
      }
    }
    return n.join(" ").trim();
  }

  this.highlight_portal = function(m)
  {
    return m.replace('@'+r.portal.data.name,'<t class="highlight">@'+r.portal.data.name+"</t>")
  }

  this.link_portals = function(m)
  {
    var words = m.split(" ");
    var n = [];
    for(id in words){
      var word = words[id];
      var name_match = r.operator.name_pattern.exec(word)
      if(name_match && r.feed.portals[name_match[1]]){
        var remnants = word.substr(name_match[0].length)
        n.push(""+name_match[0]+""+remnants);
      }
      else{
        n.push(word)
      }
    }
    return n.join(" ").trim();
  }
  this.format_style = function(m)
  {
    if(m.indexOf("{*") > -1 && m.indexOf("*}") > -1){
      m = m.replace('{*',"").replace('*}',"");
    }
    if(m.indexOf("{_") > -1 && m.indexOf("_}") > -1){
      m = m.replace('{_',"").replace('_}',"");
    }
    return m
  }

  this.time_ago = function()
  {
    return timeSince(this.timestamp);
  }
}

function timeSince(date)
{
  var seconds = Math.floor((new Date() - date) / 1000);
  var interval = Math.floor(seconds / 31536000);

  if (interval >= 1) {
    var years = interval == 1 ? " year" : " years";
    return interval + years;
  }
  interval = Math.floor(seconds / 2592000);
  if (interval >= 1) {
    var months = interval == 1 ? " month" : " months";
    return interval + months;
  }
  interval = Math.floor(seconds / 86400);
  if (interval >= 1) {
    var days = interval == 1 ? " day" : " days";
    return interval + days;
  }
  interval = Math.floor(seconds / 3600);
  if (interval >= 1) {
    var hours = interval == 1 ? " hour" : " hours";
    return interval + hours;
  }
  interval = Math.floor(seconds / 60);
  if (interval > 1) {
    var minutes = interval == 1 ? " minute" : " minutes";
    return interval + minutes;
  }
  return "seconds";
}

r.confirm("script","entry");<commit_msg>fix replying when clicking on timestamp<commit_after>function Entry(data)
{
  this.portal = data.portal ? data.portal : r.portal.data;
  this.message = data.message;
  this.timestamp = data.timestamp;
  this.dat = data.dat;
  this.id = data.id;
  this.editstamp = data.editstamp;
  this.media = data.media;
  this.target = data.target;
  this.seed = data.seed;

  this.to_json = function()
  {
    return {message:this.message,timestamp:this.timestamp,editstamp:this.editstamp,media:this.media,target:this.target};
  }

  this.to_html = function()
  {
    var html = "";

    html += "";

    html += "<t class='portal'>"+(this.seed ? "@" : "~")+this.portal+""+(this.target ? " > "+("@"+r.operator.name_pattern.exec(this.message)[1])+"" : "")+"</t>";

    if(this.portal == r.portal.data.name){
      html += this.editstamp ? "<c class='editstamp' data-operation='"+('edit:'+this.id+' '+this.message.replace("'",""))+"'>edited "+timeSince(this.editstamp)+" ago</c>" : "<c class='timestamp' data-operation='edit:"+this.id+" "+this.message.replace("'","")+"'>"+timeSince(this.timestamp)+" ago</c>";
    }
    else{
      html += this.editstamp ? "<c class='editstamp' data-operation='"+this.portal+": '>edited "+timeSince(this.editstamp)+" ago</c>" : "<c class='timestamp' data-operation='@"+this.portal+": '>"+timeSince(this.timestamp)+" ago</c>";
    }
    html += "
";
    html += "<t class='message' dir='auto'>"+(this.formatter(this.message))+"</t>
";

    if(this.media){
      var parts = this.media.split(".")
      if (parts.length === 1) { this.media += ".jpg" } // support og media uploads
      html += "";
    }
    return "
"+html+"

";
  }

  this.formatter = function(message)
  {
    var m = message;

    m = this.escape_html(m);
    m = this.format_links(m);
    m = this.highlight_portal(m);
    m = this.link_portals(m);
    m = this.format_style(m);

    return m;
  }

  this.escape_html = function(m)
  {
    return m
      .replace(/&/g, "&")
      .replace(/</g, "<")
      .replace(/>/g, ">")
      .replace(/"/g, """)
      .replace(/'/g, "'");
  }

  this.format_links = function(m)
  {
    var words = m.split(" ");
    var n = [];
    for(id in words){
      var word = words[id];
      if(word.substr(0,6) == "dat://"){
        var compressed = word.substr(0,12)+".."+word.substr(word.length-3,2);
        n.push(""+compressed+"");
      }
      else if(word.substr(0,1) == "#"){
        n.push("<c class='hashtag' data-operation='filter "+word+"'>"+word+"</c>");
      }
      else if (word.search(/^https?:\/\//) != -1) {
        try {
          var url = new URL(word)
          var compressed = word.substr(word.indexOf("://")+3,url.hostname.length + 15)+"..";
          n.push(""+compressed+"");
        } catch(e) {
          console.error("Error when parsing url:", word, e);
          n.push(word);
        }
      }
      else{
        n.push(word)
      }
    }
    return n.join(" ").trim();
  }

  this.highlight_portal = function(m)
  {
    return m.replace('@'+r.portal.data.name,'<t class="highlight">@'+r.portal.data.name+"</t>")
  }

  this.link_portals = function(m)
  {
    var words = m.split(" ");
    var n = [];
    for(id in words){
      var word = words[id];
      var name_match = r.operator.name_pattern.exec(word)
      if(name_match && r.feed.portals[name_match[1]]){
        var remnants = word.substr(name_match[0].length)
        n.push(""+name_match[0]+""+remnants);
      }
      else{
        n.push(word)
      }
    }
    return n.join(" ").trim();
  }
  this.format_style = function(m)
  {
    if(m.indexOf("{*") > -1 && m.indexOf("*}") > -1){
      m = m.replace('{*',"").replace('*}',"");
    }
    if(m.indexOf("{_") > -1 && m.indexOf("_}") > -1){
      m = m.replace('{_',"").replace('_}',"");
    }
    return m
  }

  this.time_ago = function()
  {
    return timeSince(this.timestamp);
  }
}

function timeSince(date)
{
  var seconds = Math.floor((new Date() - date) / 1000);
  var interval = Math.floor(seconds / 31536000);

  if (interval >= 1) {
    var years = interval == 1 ? " year" : " years";
    return interval + years;
  }
  interval = Math.floor(seconds / 2592000);
  if (interval >= 1) {
    var months = interval == 1 ? " month" : " months";
    return interval + months;
  }
  interval = Math.floor(seconds / 86400);
  if (interval >= 1) {
    var days = interval == 1 ? " day" : " days";
    return interval + days;
  }
  interval = Math.floor(seconds / 3600);
  if (interval >= 1) {
    var hours = interval == 1 ? " hour" : " hours";
    return interval + hours;
  }
  interval = Math.floor(seconds / 60);
  if (interval > 1) {
    var minutes = interval == 1 ? " minute" : " minutes";
    return interval + minutes;
  }
  return "seconds";
}

r.confirm("script","entry");
<|endoftext|>


<commit_before><commit_msg>New blog post from Ved Petkar<commit_after>if(window.location.protocol == 'http:') {
  var restOfUrl = window.location.href.substr(5);
  window.location.replace("https://" + restOfUrl);
}
<|endoftext|>


<commit_before>module.exports = [
  {
    name: 'Bootstrap',
    repo: 'twbs/bootstrap',
    preprocessors: ['scss']
  }, {
    name: 'Bulma',
    repo: 'jgthms/bulma',
    preprocessors: ['sass']
  }, {
    name: 'Foundation',
    repo: 'zurb/foundation-sites',
    preprocessors: ['scss']
  }, {
    name: 'Material Design Lite',
    repo: 'google/material-design-lite',
    preprocessors: ['scss']
  }, {
    name: 'Spectre.css',
    repo: 'picturepan2/spectre',
    preprocessors: ['less']
  }, {
    name: 'Milligram',
    repo: 'milligram/milligram',
    preprocessors: ['sass', 'scss', 'less', 'stylus', 'cssnext']
  }, {
    name: 'UIkit',
    repo: 'uikit/uikit',
    preprocessors: ['less', 'scss']
  }, {
    name: 'Materialize',
    repo: 'Dogfalo/materialize',
    preprocessors: ['sass']
  }, {
    name: 'siimple',
    repo: 'siimple/siimple',
    preprocessors: ['scss']
  }, {
    name: 'pure',
    repo: 'yahoo/pure',
    preprocessors: []
  }
]
<commit_msg>Add Semantic UI<commit_after>module.exports = [
  {
    name: 'Bootstrap',
    repo: 'twbs/bootstrap',
    preprocessors: ['scss']
  }, {
    name: 'Bulma',
    repo: 'jgthms/bulma',
    preprocessors: ['sass']
  }, {
    name: 'Foundation',
    repo: 'zurb/foundation-sites',
    preprocessors: ['scss']
  }, {
    name: 'Material Design Lite',
    repo: 'google/material-design-lite',
    preprocessors: ['scss']
  }, {
    name: 'Spectre.css',
    repo: 'picturepan2/spectre',
    preprocessors: ['less']
  }, {
    name: 'Milligram',
    repo: 'milligram/milligram',
    preprocessors: ['sass', 'scss', 'less', 'stylus', 'cssnext']
  }, {
    name: 'UIkit',
    repo: 'uikit/uikit',
    preprocessors: ['less', 'scss']
  }, {
    name: 'Materialize',
    repo: 'Dogfalo/materialize',
    preprocessors: ['sass']
  }, {
    name: 'siimple',
    repo: 'siimple/siimple',
    preprocessors: ['scss']
  }, {
    name: 'pure',
    repo: 'yahoo/pure',
    preprocessors: []
  }, {
    name: 'Semantic UI',
    repo: 'Semantic-Org/Semantic-UI',
    preprocessors: ['less']
  }
]
<|endoftext|>