<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3Scale control")
description("This will return the 3Scale control")
base_component_id("rh3scale_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "width",
            name:       "Width",
            default:    80,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    80,
            type:       "Number"
        }
        ,
        {
            id:         "port",
            name:       "Port",
            default:    1234,
            type:       "Number"
        }
        ,
        {
            id:      "host",
            name:    "Host",
            default: "http://3scale.API",
            type:    "String"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "is3ScaleAvailable",
            name:       "Is 3 Scale Available?",
            type:       "Select",
            default:    "False",
            values:     [
                            {display: "True",   value: "True"},
                            {display: "False",  value: "False"}
                        ]
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:      "serviceToken",
            name:    "Service Token",
            default: "78643278346874236846873248",
            type:    "String"
        }
        ,
        {
            id:      "apiKey",
            name:    "API key",
            default: "",
            type:    "String"
        }
        ,
        {
            id:         "check3ScaleAvailable",
            pre_snippet:    `await `,
            snippet:    `check3ScaleAvailable()`,
            name:       "Check 3Scale Available",
            type:       "Action"
        }
        ,
        {
            id:         "getApplicationPlans",
            pre_snippet:    `await `,
            snippet:    `getApplicationPlans()`,
            name:       "Get app plans",
            type:       "Action"
        }
        ,
        {
            id:         "getProxyConfigList",
            pre_snippet:    `await `,
            snippet:    `getProxyConfigList()`,
            name:       "Get proxy configs",
            type:       "Action"
        }
        ,
        {
            id:         "applicationPlans",
            name:       "App plans",
            default:    [],
            hidden:     true,
            type:       "Array"
        }
        ,
        {
            id:         "proxyConfigList",
            name:       "proxy config list",
            default:    [],
            hidden:     true,
            type:       "Array"
        }
    ]
)//properties

logo_url("/driver_icons/rh3scale.png")
*/

    Vue.component("rh3scale_control",{

        props: ["meta", "args","design_mode","refresh", "children"]

        ,

        template:

`

        </src>

Red Hat 3Scale connector

        The Red Hat 3Scale Connector can be used to query 3Scale, or send
        API requests through the 3Scale gateway

            3Scale Admin Host
            <input v-model="args.host" size=60 @change="changeHost()"></input>

            API Key
            <input v-model="args.serviceToken" size=60 @change="changeAPIToken()"></input>

            {{(args.is3ScaleAvailable=="True"?"Available":"Not available" )}}

 0)'
                v-bind:style='"padding:10px;"'>

            Available APIs

                {{appPlan.name}}

 0))'
                v-bind:style='"padding:10px;"'>

                No APIs available

`

        ,

        data: function() {
            return {
                msg: "..."
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

            var x = await this.check3ScaleAvailable()
            this.args.is3ScaleAvailable = x?"True":"False"
            if (this.design_mode) {
                this.updatePlans()
            }
        }
        ,

        methods: {
            readFromDocker: async function() {
                var result = await callFunction(
                {
                    driver_name: "serverDockerStuff",
                    method_name: "serverDockerStuff"
                }
                ,
                {
                    host: this.args.host ,
                    port: this.args.port
                })

                //alert(JSON.stringify(result,null,2))
                if (result) {
                    return result
                }
                return null
            }
            ,

            updatePlans: async function() {
                if (this.args.is3ScaleAvailable) {
                    this.getApplicationPlans()
                    this.getProxyConfigList()
                }
                this.refresh++

            }
            ,

            changeAPIToken: async function() {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
                this.updatePlans()
            }

            ,
            changeHost: async function() {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
                this.updatePlans()
            }
            ,
            check3ScaleAvailable: async function() {
                try {
                    var result = await callFunction(
                    {
                        driver_name: "rest_call_service_v2",
                        method_name: "rest_call_service_v2"
                    }
                    ,
                    {
                        URL:     this.args.host +
                                "/admin/api/application_plans.xml?access_token=" +
                                 this.args.serviceToken,
                        filter: null,
                        root:   ""
                    })

                    if (result && result.plans) {
                        return true
                    }

                } catch (e) {
                    return false
                } finally {

                }
                return false

            }
            ,
            getUrlFor: function(extraURL) {
                return this.args.host +
                        extraURL + "?" +
                        "&access_token=" + this.args.serviceToken
            }
            ,

            getApplicationPlans: async function() {
                var useURL = this.getUrlFor("/admin/api/application_plans.xml")

                 var result = await callFunction(
                 {
                     driver_name: "rest_call_service_v2",
                     method_name: "rest_call_service_v2"
                 }
                 ,
                 {
                     URL:    useURL,
                     filter: {"plans":true,"plans.plan":true,"plans.plan.[]":true,"plans.plan.[].$":false,"plans.plan.[].$.custom":false,"plans.plan.[].$.default":false,"plans.plan.[].id":true,"plans.plan.[].name":true,"plans.plan.[].type":true,"plans.plan.[].state":true,"plans.plan.[].approval_required":true,"plans.plan.[].setup_fee":true,"plans.plan.[].cost_per_month":true,"plans.plan.[].trial_period_days":true,"plans.plan.[].cancellation_period":true,"plans.plan.[].service_id":true,"plans.plan.[].end_user_required":true},
                     root:   "plans.plan"
                     //,returnDetails: true
                 })

                 this.args.applicationPlans = JSON.parse(JSON.stringify(result))

                return result
            }

            ,
            getProxyConfigList: async function() {
                var useURL = this.getUrlFor("/admin/api/services/2555417843495/proxy/configs/sandbox.json")

                 var result = await callFunction(
                 {
                     driver_name: "rest_call_service_v2",
                     method_name: "rest_call_service_v2"
                 }
                 ,
                 {
                     URL:    useURL,
                     filter: null,
                     root:   null
                     //,returnDetails: true
                 })

                 var pl = result.proxy_configs
                 var pl2=[]
                 for (var i=0;i<pl.length;i++) {
                     var rtt= pl[i].proxy_config
                     var rtt2={
                         environment: rtt.environment,
                         id: rtt.content.id,
                         account_id: rtt.content.account_id,
                         name: rtt.content.name,
                         description: rtt.content.description,
                         service_id: rtt.content.proxy.service_id,
                         auth_user_key: rtt.content.proxy.auth_user_key,
                         api_test_path: rtt.content.proxy.api_test_path,
                         sandbox_endpoint: rtt.content.proxy.sandbox_endpoint,
                         endpoint: rtt.content.proxy.endpoint
                     }
                     pl2.push(rtt2)
                 }
                 this.args.proxyConfigList = JSON.parse(JSON.stringify(pl2))

                return result
            }

        }

    })
}
<commit_msg>3Scale control: get the correct API list and UI fixes<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3Scale control")
description("This will return the 3Scale control")
base_component_id("rh3scale_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "width",
            name:       "Width",
            default:    80,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    80,
            type:       "Number"
        }
        ,
        {
            id:         "port",
            name:       "Port",
            default:    1234,
            type:       "Number"
        }
        ,
        {
            id:      "host",
            name:    "Host",
            default: "http://3scale.API",
            type:    "String"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "is3ScaleAvailable",
            name:       "Is 3 Scale Available?",
            type:       "Select",
            default:    "False",
            values:     [
                            {display: "True",   value: "True"},
                            {display: "False",  value: "False"}
                        ]
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:      "serviceToken",
            name:    "Service Token",
            default: "78643278346874236846873248",
            type:    "String"
        }
        ,
        {
            id:      "apiKey",
            name:    "API key",
            default: "",
            type:    "String"
        }
        ,
        {
            id:         "check3ScaleAvailable",
            pre_snippet:    `await `,
            snippet:    `check3ScaleAvailable()`,
            name:       "Check 3Scale Available",
            type:       "Action"
        }
        ,
        {
            id:         "getApplicationPlans",
            pre_snippet:    `await `,
            snippet:    `getApplicationPlans()`,
            name:       "Get app plans",
            type:       "Action"
        }
        ,
        {
            id:         "getProxyConfigList",
            pre_snippet:    `await `,
            snippet:    `getProxyConfigList()`,
            name:       "Get proxy configs",
            type:       "Action"
        }
        ,
        {
            id:         "applicationPlans",
            name:       "App plans",
            default:    [],
            hidden:     true,
            type:       "Array"
        }
        ,
        {
            id:         "proxyConfigList",
            name:       "proxy config list",
            default:    [],
            hidden:     true,
            type:       "Array"
        }
    ]
)//properties

logo_url("/driver_icons/rh3scale.png")
*/

    Vue.component("rh3scale_control",{

        props: ["meta", "args","design_mode","refresh", "children"]

        ,

        template:

`

        </src>

Red Hat 3Scale connector

        The Red Hat 3Scale Connector can be used to query 3Scale, or send
        API requests through the 3Scale gateway

            3Scale Admin Host
            <input v-model="args.host" size=60 @change="changeHost()"></input>

            Admin Service Token
            <input v-model="args.serviceToken" size=60 @change="changeServiceToken()"></input>

            API Key
            <input v-model="args.apiKey" size=60 @change="changeAPIKey()"></input>

            {{(args.is3ScaleAvailable=="True"?"Available":"Not available" )}}

 0)'
                v-bind:style='"padding:10px;"'>

            Available APIs

                {{appPlan.name}}

 0))'
                v-bind:style='"padding:10px;"'>

                No APIs available

`

        ,

        data: function() {
            return {
                msg: "..."
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

            var x = await this.check3ScaleAvailable()
            this.args.is3ScaleAvailable = x?"True":"False"
            if (this.design_mode) {
                this.updatePlans()
            }
        }
        ,

        methods: {
            readFromDocker: async function() {
                var result = await callFunction(
                {
                    driver_name: "serverDockerStuff",
                    method_name: "serverDockerStuff"
                }
                ,
                {
                    host: this.args.host ,
                    port: this.args.port
                })

                //alert(JSON.stringify(result,null,2))
                if (result) {
                    return result
                }
                return null
            }
            ,

            updatePlans: async function() {
                if (this.args.is3ScaleAvailable) {
                    this.getApplicationPlans()
                    this.getProxyConfigList()
                }
                this.refresh++

            }
            ,

            changeServiceToken: async function() {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
                this.getProxyConfigList()
                this.updatePlans()
            }
            ,
            changeApiKey: async function() {
            }

            ,
            changeHost: async function() {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
                this.getProxyConfigList()
                this.updatePlans()
            }
            ,
            check3ScaleAvailable: async function() {
                try {
                    var result = await callFunction(
                    {
                        driver_name: "rest_call_service_v2",
                        method_name: "rest_call_service_v2"
                    }
                    ,
                    {
                        URL:     this.args.host +
                                "/admin/api/application_plans.xml?access_token=" +
                                 this.args.serviceToken,
                        filter: null,
                        root:   ""
                    })

                    if (result && result.plans) {
                        return true
                    }

                } catch (e) {
                    return false
                } finally {

                }
                return false

            }
            ,
            getUrlFor: function(extraURL) {
                return this.args.host +
                        extraURL + "?" +
                        "&access_token=" + this.args.serviceToken
            }
            ,

            getApplicationPlans: async function() {
                var useURL = this.getUrlFor("/admin/api/application_plans.xml")

                 var result = await callFunction(
                 {
                     driver_name: "rest_call_service_v2",
                     method_name: "rest_call_service_v2"
                 }
                 ,
                 {
                     URL:    useURL,
                     filter: {"plans":true,"plans.plan":true,"plans.plan.[]":true,"plans.plan.[].$":false,"plans.plan.[].$.custom":false,"plans.plan.[].$.default":false,"plans.plan.[].id":true,"plans.plan.[].name":true,"plans.plan.[].type":true,"plans.plan.[].state":true,"plans.plan.[].approval_required":true,"plans.plan.[].setup_fee":true,"plans.plan.[].cost_per_month":true,"plans.plan.[].trial_period_days":true,"plans.plan.[].cancellation_period":true,"plans.plan.[].service_id":true,"plans.plan.[].end_user_required":true},
                     root:   "plans.plan"
                     //,returnDetails: true
                 })

                 this.args.applicationPlans = JSON.parse(JSON.stringify(result))

                return result
            }

            ,
            getProxyConfigList: async function() {
                var useURL = this.getUrlFor("/admin/api/services/2555417843495/proxy/configs/sandbox.json")

                 var result = await callFunction(
                 {
                     driver_name: "rest_call_service_v2",
                     method_name: "rest_call_service_v2"
                 }
                 ,
                 {
                     URL:    useURL,
                     filter: null,
                     root:   null
                     //,returnDetails: true
                 })

                 var pl = result.proxy_configs
                 var pl2=[]
                 for (var i=0;i<pl.length;i++) {
                     var rtt= pl[i].proxy_config
                     var rtt2={
                         environment: rtt.environment,
                         id: rtt.content.id,
                         account_id: rtt.content.account_id,
                         name: rtt.content.name,
                         description: rtt.content.description,
                         service_id: rtt.content.proxy.service_id,
                         auth_user_key: rtt.content.proxy.auth_user_key,
                         api_test_path: rtt.content.proxy.api_test_path,
                         sandbox_endpoint: rtt.content.proxy.sandbox_endpoint,
                         endpoint: rtt.content.proxy.endpoint
                     }
                     pl2.push(rtt2)
                 }
                 this.args.proxyConfigList = JSON.parse(JSON.stringify(pl2))

                return result
            }

        }

    })
}
<|endoftext|>


<commit_before>
// TODO Handling for children/siblings/grouping
module.exports = class MiniDOMParser {

  static parse(elemStr) {
    if (!elemStr) {
      throw new Error('Invalid element string: Empty/missing');
    }

    let elements = elemStr.split('>');
    if (elements.length > 1) {
      // Future...
      for (const e of elements) {
        if (e.includes('+')) {
          console.log('sibling elements:', e.split('+'));
        }
      }

      return elements.reduceRight((children, str, i) => {
        return [this.parseSingle(str, children)];
      }, []);
    }

    return this.parseSingle(elemStr);
  }

  static parseSingle(elemStr, children = []) {
    if (!elemStr) {
      throw new Error('Invalid element string: Empty/missing');
    }

    let parts = elemStr.split(/([#\.][_a-zA-Z0-9-]+)/).filter(p => !!p);

    if (parts[0].match(/[a-zA-Z]/).index !== 0) {
      throw new Error('Invalid element string: Must start with tag name');
    }

    const tagName = parts.shift().match(/[a-zA-Z]+/)[0];
    let id = parts.find(p => p.startsWith('#'));
    if (id) {
      id = id.substring(1);
    }
    const classes = parts
      .filter(p => p.startsWith('.') && p.substring(1).match(/[_a-zA-Z0-9-]/))
      .map(p => p.substring(1));

    return {
      children,
      classes,
      id,
      tagName
    };
  }

  static isClass(divider) {
    return divider === '.';
  }

  static isId(divider) {
    return divider === '#';
  }

}
<commit_msg>Rewriting parser, early stages<commit_after>
const elementSplit = /(?:\s|>)/;
const attributeMatch = /(\[.+=".+"\])/;

// TODO Handling for children/siblings/grouping
module.exports = class MiniDOMParser {

  static parse(elemStr) {
    if (!elemStr) {
      throw new Error('Invalid element string: Empty/missing');
    }

    let elements = elemStr.split(elementSplit).map(el => el.trim());

    //let elements = elemStr.split('>');
    if (elements.length > 1) {
      // Future...
      for (let i = 0; i < elements.length; i++) {
        if (elements[i].includes('+')) {
          elements[i] = elements[i].split('+');
        }
      }

        return elements.reduce((tree, currentElement) => {
          if (tree) {
            if (!Array.isArray(currentElement)) {
              tree.children.push(this.parseSingle(currentElement));
            } else {
              // FIXME Tree setup is really not implemented yet...
              tree.children.push(this.parseSingle(currentElement[0]));
            }
            return tree;
          }

          return this.parseSingle(currentElement);
        }, null);
    }

    return this.parseSingle(elemStr);
  }

  static parseSingle(elemStr, children = []) {
    if (!elemStr) {
      throw new Error('Invalid element string: Empty/missing');
    }

    let parts = elemStr.split(/(\[.*?\])|([#\.][_a-zA-Z0-9-]+)/).filter(p => !!p);

    if (parts[0].match(/[a-zA-Z]/).index !== 0) {
      throw new Error('Invalid element string: Must start with tag name');
    }

    const attributes = [];
    for (const part of parts) {
      if (part.match(attributeMatch) && this.isValidAttribute(part)) {
        attributes.push(part);
      }
    }

    console.log(attributes);

    const tagName = parts.shift().match(/[a-zA-Z]+/)[0];
    let id = parts.find(p => p.startsWith('#'));
    if (id) {
      id = id.substring(1);
    }
    const classes = parts
      .filter(p => p.startsWith('.') && p.substring(1).match(/[_a-zA-Z0-9-]/))
      .map(p => p.substring(1));

    return {
      children,
      classes,
      attributes,
      id,
      tagName
    };
  }

  static isValidAttribute(attrString) {
    if (!attrString) {
      return false;
    }
    const parts = attrString.split('=');
    if (parts.length !== 2) {
      return false;
    }
    return true;
  }

  static isClass(divider) {
    return divider === '.';
  }

  static isId(divider) {
    return divider === '#';
  }

}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $(".home .action_btns a.green_grad").click(function () {
		$(".home .timeline-band-input").fadeOut(200);
		$(".home .action_btns").animate({top:725},200);
    });
});<commit_msg>igor: home.js<commit_after>$(document).ready(function() {
    $(".home .action_btns a.green_grad").click(function () {
		$(".home .timeline-band-input").fadeOut(200);
		$(".home .action_btns").animate({top:725},200);
		$(".home .action_btns a.green_grad").text('× Close a Demo');
    });
});<|endoftext|>


<commit_before>/* boilerUtils
 * This object holds functions that assist Boilerplate
 */

var boilerUtils = {}

/* boilerUtils.getBoilerTemplateData (includes, appScript, content, config)
 * `includes` - An includes object created by `maniUtils.getIncludes`
 * `appScript` - The relative URL to the appScript
 * `content` - Some HTML
 * `config` - A config object, structured like `altboiler.configuration`
 * This function parses all these options to make them readable by spacebars
 * It uses EJSON to encode objects (__meteor_runtime_config__)
 * It uses encodeURICompontent for the HTML used as strings inside assets/loader.js
 * __meteor_runtime_config__ is also passed
 */
boilerUtils.getBoilerTemplateData = function getTemplateData (includes, appScript, content, config) {
  return {
    /* The assets/loader script isn't hooked using the public object, to isure, it's not removed. */
    script: boilerUtils.parseJsArr([boilerUtils.getLoader()].concat(config.js || '')).join('\n'),
    styles: [].concat(config.css).join('\n'),
    content: content,
    head: '"' + encodeURIComponent(includes['head'].join('\n')) + '"',
    body: '"' + encodeURIComponent(includes['body'].join('\n')) + '"',
    appScript: appScript,
    onLoadHooks: '[' + boilerUtils.parseJsArr([].concat(config.onLoad || '')).join(',') + ']',
    meteorRuntimeConfig: EJSON.stringify(__meteor_runtime_config__ || {})
  }
},

/* boilerUtils.parseJsArr(hooksArr)
 * `hooksArr` - An array of functions or strings to parse
 * Maps through the array;
 * simply executing and returning `toString`
 */
boilerUtils.parseJsArr = function parseJsArr (hooksArr) {
  console.log(hooksArr)
  return _.invoke(hooksArr, 'toString')
}

/* boilerUtils.getLoader()
 * returns the loader script
 * It uses `UglifyJSMinify` to minify the JS
 * It has a caching mechanism for that,
 * so it only gets minified once, at server startup
 */
boilerUtils.getLoader = (function makeGetLoader () {
  var cachedLoader = false
  return function getLoader () {
    if(cachedLoader) return cachedLoader
    return cachedLoader = UglifyJSMinify(
        Assets.getText('assets/loader.js'),
        {fromString: true}
    ).code
  }
})()

_altboilerScope = _altboilerScope || {}
_altboilerScope.boilerUtils = boilerUtils
<commit_msg>Remove a console.log used for debugging<commit_after>/* boilerUtils
 * This object holds functions that assist Boilerplate
 */

var boilerUtils = {}

/* boilerUtils.getBoilerTemplateData (includes, appScript, content, config)
 * `includes` - An includes object created by `maniUtils.getIncludes`
 * `appScript` - The relative URL to the appScript
 * `content` - Some HTML
 * `config` - A config object, structured like `altboiler.configuration`
 * This function parses all these options to make them readable by spacebars
 * It uses EJSON to encode objects (__meteor_runtime_config__)
 * It uses encodeURICompontent for the HTML used as strings inside assets/loader.js
 * __meteor_runtime_config__ is also passed
 */
boilerUtils.getBoilerTemplateData = function getTemplateData (includes, appScript, content, config) {
  return {
    /* The assets/loader script isn't hooked using the public object, to isure, it's not removed. */
    script: boilerUtils.parseJsArr([boilerUtils.getLoader()].concat(config.js || '')).join('\n'),
    styles: [].concat(config.css).join('\n'),
    content: content,
    head: '"' + encodeURIComponent(includes['head'].join('\n')) + '"',
    body: '"' + encodeURIComponent(includes['body'].join('\n')) + '"',
    appScript: appScript,
    onLoadHooks: '[' + boilerUtils.parseJsArr([].concat(config.onLoad || '')).join(',') + ']',
    meteorRuntimeConfig: EJSON.stringify(__meteor_runtime_config__ || {})
  }
},

/* boilerUtils.parseJsArr(hooksArr)
 * `hooksArr` - An array of functions or strings to parse
 * Maps through the array;
 * simply executing and returning `toString`
 */
boilerUtils.parseJsArr = function parseJsArr (hooksArr) {
  return _.invoke(hooksArr, 'toString')
}

/* boilerUtils.getLoader()
 * returns the loader script
 * It uses `UglifyJSMinify` to minify the JS
 * It has a caching mechanism for that,
 * so it only gets minified once, at server startup
 */
boilerUtils.getLoader = (function makeGetLoader () {
  var cachedLoader = false
  return function getLoader () {
    if(cachedLoader) return cachedLoader
    return cachedLoader = UglifyJSMinify(
        Assets.getText('assets/loader.js'),
        {fromString: true}
    ).code
  }
})()

_altboilerScope = _altboilerScope || {}
_altboilerScope.boilerUtils = boilerUtils
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3Scale control")
description("This will return the 3Scale control")
base_component_id("rh3scale_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "width",
            name:       "Width",
            default:    80,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    80,
            type:       "Number"
        }
        ,
        {
            id:         "port",
            name:       "Port",
            default:    1234,
            type:       "Number"
        }
        ,
        {
            id:      "host",
            name:    "Host",
            default: "http://3scale.API",
            type:    "String"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "is3ScaleAvailable",
            name:       "Is 3 Scale Available?",
            type:       "Select",
            default:    "False",
            values:     [
                            {display: "True",   value: "True"},
                            {display: "False",  value: "False"}
                        ]
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:      "serviceToken",
            name:    "Service Token",
            default: "78643278346874236846873248",
            type:    "String"
        }
        ,
        {
            id:         "check3ScaleAvailable",
            pre_snippet:    `await `,
            snippet:    `check3ScaleAvailable()`,
            name:       "Check 3Scale Available",
            type:       "Action"
        }
        ,
        {
            id:         "getApplicationPlans",
            pre_snippet:    `await `,
            snippet:    `getApplicationPlans()`,
            name:       "Get app plans",
            type:       "Action"
        }

    ]
)//properties

logo_url("/driver_icons/rh3scale.png")
*/

    Vue.component("rh3scale_control",{

        props: ["meta", "args","design_mode","refresh", "children"]

        ,

        template:

`

        </src>

Red Hat 3Scale connector

        The Red Hat 3Scale Connector can be used to query 3Scale, or send
        API requests through the 3Scale gateway

            3Scale Admin Host
            <input v-model="args.host" size=60 @change="changeHost()"></input>

            API Key
            <input v-model="args.serviceToken" size=60 @change="changeAPIToken()"></input>

            {{(args.is3ScaleAvailable=="True"?"Available":"Not available" )}}

`

        ,

        data: function() {
            return {
                msg: "..."
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

            if (!this.design_mode) {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
            }
        }
        ,

        methods: {
            readFromDocker: async function() {
                var result = await callFunction(
                {
                    driver_name: "serverDockerStuff",
                    method_name: "serverDockerStuff"
                }
                ,
                {
                    host: this.args.host ,
                    port: this.args.port
                })

                //alert(JSON.stringify(result,null,2))
                if (result) {
                    return result
                }
                return null
            }
            ,
            changeAPIToken: async function() {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
            }

            ,
            changeHost: async function() {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
            }
            ,
            check3ScaleAvailable: async function() {
                try {
                    var result = await callFunction(
                    {
                        driver_name: "rest_call_service_v2",
                        method_name: "rest_call_service_v2"
                    }
                    ,
                    {
                        URL:     this.args.host +
                                "/admin/api/application_plans.xml?access_token=" +
                                 this.args.serviceToken,
                        filter: null,
                        root:   ""
                    })

                    if (result && result.plans) {
                        return true
                    }

                } catch (e) {
                    return false
                } finally {

                }
                return false

            }
            ,
            getUrlFor: function(extraURL) {
                return this.args.host +
                        extraURL + "?" +
                        "&access_token=" + this.args.serviceToken
            }
            ,

            getApplicationPlans: async function() {
                var useURL = this.getUrlFor("/admin/api/application_plans.xml")
                debugger
                 var result = await callFunction(
                 {
                     driver_name: "rest_call_service_v2",
                     method_name: "rest_call_service_v2"
                 }
                 ,
                 {
                     URL:    useURL,
                     filter: {"plans":true,"plans.plan":true,"plans.plan.[]":true,"plans.plan.[].$":false,"plans.plan.[].$.custom":false,"plans.plan.[].$.default":false,"plans.plan.[].id":true,"plans.plan.[].name":true,"plans.plan.[].type":true,"plans.plan.[].state":true,"plans.plan.[].approval_required":true,"plans.plan.[].setup_fee":true,"plans.plan.[].cost_per_month":true,"plans.plan.[].trial_period_days":true,"plans.plan.[].cancellation_period":true,"plans.plan.[].service_id":true,"plans.plan.[].end_user_required":true},
                     root:   "plans.plan"
                 })

                return result
            }

        }

    })
}
<commit_msg>Can read the application plans now<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3Scale control")
description("This will return the 3Scale control")
base_component_id("rh3scale_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "width",
            name:       "Width",
            default:    80,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    80,
            type:       "Number"
        }
        ,
        {
            id:         "port",
            name:       "Port",
            default:    1234,
            type:       "Number"
        }
        ,
        {
            id:      "host",
            name:    "Host",
            default: "http://3scale.API",
            type:    "String"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "is3ScaleAvailable",
            name:       "Is 3 Scale Available?",
            type:       "Select",
            default:    "False",
            values:     [
                            {display: "True",   value: "True"},
                            {display: "False",  value: "False"}
                        ]
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:      "serviceToken",
            name:    "Service Token",
            default: "78643278346874236846873248",
            type:    "String"
        }
        ,
        {
            id:         "check3ScaleAvailable",
            pre_snippet:    `await `,
            snippet:    `check3ScaleAvailable()`,
            name:       "Check 3Scale Available",
            type:       "Action"
        }
        ,
        {
            id:         "getApplicationPlans",
            pre_snippet:    `await `,
            snippet:    `getApplicationPlans()`,
            name:       "Get app plans",
            type:       "Action"
        }
        ,
        {
            id:         "applicationPlans",
            name:       "App plans",
            default:    [],
            hidden:     true,
            type:       "Array"
        }

    ]
)//properties

logo_url("/driver_icons/rh3scale.png")
*/

    Vue.component("rh3scale_control",{

        props: ["meta", "args","design_mode","refresh", "children"]

        ,

        template:

`

        </src>

Red Hat 3Scale connector

        The Red Hat 3Scale Connector can be used to query 3Scale, or send
        API requests through the 3Scale gateway

            3Scale Admin Host
            <input v-model="args.host" size=60 @change="changeHost()"></input>

            API Key
            <input v-model="args.serviceToken" size=60 @change="changeAPIToken()"></input>

            {{(args.is3ScaleAvailable=="True"?"Available":"Not available" )}}

`

        ,

        data: function() {
            return {
                msg: "..."
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

            if (!this.design_mode) {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
            }
        }
        ,

        methods: {
            readFromDocker: async function() {
                var result = await callFunction(
                {
                    driver_name: "serverDockerStuff",
                    method_name: "serverDockerStuff"
                }
                ,
                {
                    host: this.args.host ,
                    port: this.args.port
                })

                //alert(JSON.stringify(result,null,2))
                if (result) {
                    return result
                }
                return null
            }
            ,
            changeAPIToken: async function() {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
            }

            ,
            changeHost: async function() {
                var x = await this.check3ScaleAvailable()
                this.args.is3ScaleAvailable = x?"True":"False"
            }
            ,
            check3ScaleAvailable: async function() {
                try {
                    var result = await callFunction(
                    {
                        driver_name: "rest_call_service_v2",
                        method_name: "rest_call_service_v2"
                    }
                    ,
                    {
                        URL:     this.args.host +
                                "/admin/api/application_plans.xml?access_token=" +
                                 this.args.serviceToken,
                        filter: null,
                        root:   ""
                    })

                    if (result && result.plans) {
                        return true
                    }

                } catch (e) {
                    return false
                } finally {

                }
                return false

            }
            ,
            getUrlFor: function(extraURL) {
                return this.args.host +
                        extraURL + "?" +
                        "&access_token=" + this.args.serviceToken
            }
            ,

            getApplicationPlans: async function() {
                var useURL = this.getUrlFor("/admin/api/application_plans.xml")

                 var result = await callFunction(
                 {
                     driver_name: "rest_call_service_v2",
                     method_name: "rest_call_service_v2"
                 }
                 ,
                 {
                     URL:    useURL,
                     filter: {"plans":true,"plans.plan":true,"plans.plan.[]":true,"plans.plan.[].$":false,"plans.plan.[].$.custom":false,"plans.plan.[].$.default":false,"plans.plan.[].id":true,"plans.plan.[].name":true,"plans.plan.[].type":true,"plans.plan.[].state":true,"plans.plan.[].approval_required":true,"plans.plan.[].setup_fee":true,"plans.plan.[].cost_per_month":true,"plans.plan.[].trial_period_days":true,"plans.plan.[].cancellation_period":true,"plans.plan.[].service_id":true,"plans.plan.[].end_user_required":true},
                     root:   "plans.plan"
                     //,returnDetails: true
                 })

                 this.args.applicationPlans = JSON.parse(JSON.stringify(result))

                return result
            }

        }

    })
}
<|endoftext|>


<commit_before>'use strict';

var natural = require('natural')
  , fuse = require('fusing')
  , fs = require('fs');

/**
 * The base parser class where all parsers inherit from. This provides some
 * common functionality which the parsers can use to detect licensing.
 *
 * @constructor
 * @param {Object} parsers An object which contains all available parsers.
 * @api public
 */
function Parser(parsers) {
  if (!(this instanceof Parser)) return new Parser(parsers);

  this.parsers = parsers;
}

fuse(Parser);

/**
 * Expose some core modules through the instance.
 *
 * @type {Function}
 * @api pubilc
 */
Parser.readable('async', require('async'));
Parser.readable('request', require('request'));

/**
 * Simple regular expression based tests for figuring out which license we're
 * dealing with.
 *
 * @param {String} str
 * @returns {Array}
 * @api public
 */
Parser.readable('test', function test(str) {
  if (/BSD/.test(str)) return ['BSD'];
  if (/GPL/.test(str) || /GPLv2/.test(str)) return ['GPL'];
  if (/LGPL/.test(str)) return ['LGPL'];
  if (/MIT/.test(str) || /\(MIT\)/.test(str)) return ['MIT'];
  if (/Apache\s?Licen[cs]e/.test(str)) return ['Apache'];
  if (/MPL/.test(str)) return ['MPL'];

  //
  // Watch out we've got a bad-ass over here.
  //
  if (/DO\sWHAT\sTHE\sFUCK\sYOU\sWANT\sTO\sPUBLIC\sLICEN[CS]E/i.test(str)
   || /WTFPL/.test(str)
  ) return ['WTFPL'];
});

/**
 * There are 1000 ways of writing that you're using an MIT module. This
 * normalization module attempts to normalize the licenses in to one common
 * name.
 *
 * @param {Array} data A list of license information that needs to be normalized.
 * @api public
 */
Parser.readable('normalize', function normalize(data) {
  //
  // First we need to pass the data through our dual license checker so can
  // figure out if the module is dual licensed as both license values needs to
  // be normalized.
  //
  // 1. Direct match. Check for direct matches against our normalized license
  //    file.
  //
  // 2. toLowercase. Transform the given license string and the key of
  //    normalization to lowercase to see if it matches.
  //
  // 3. String distance. To see if there might have been some mistakes.
  //
  return data;
});

/**
 * Find an URL in the data structure.
 *
 * @param {Object} data Data structure
 * @param {String} contains A string that the URL should contain.
 * @api public
 */
Parser.readable('url', function url(data, contains) {
  if (!data) return undefined;

  if ('string' === typeof data && ~data.indexOf(contains)) return data;
  if ('object' === typeof data) {
    if ('url' in data) return url(data.url, contains);
    if ('web' in data) return url(data.web, contains);
  }

  return undefined;
});

Parser.readable('dual', function (str) {
  // check for / , or and, +
});

//
// Setup and train our classifier.
//
var classifier = new natural.BayesClassifier();

[
  { file: 'AFL2.1.txt',       as: 'AFL 2.1'       },
  { file: 'AFL3.0.txt',       as: 'AFL 3.0'       },
  { file: 'AGPL3.0.txt',      as: 'AGPL 3.0'      },
  { file: 'APL-1.0.txt',      as: 'APL 1.0'       },
  { file: 'Apache2.0.txt',    as: 'Apache 2.0'    },
  { file: 'BSD-2-Clause.txt', as: 'BSD 2-Clause'  },
  { file: 'BSD-3-Clause.txt', as: 'BSD 3-Clause'  },
  { file: 'BSD.txt',          as: 'BSD 4-Clouse'  },
  { file: 'BSL1.0.txt',       as: 'BSL 1.0'       },
  { file: 'EPL-1.0.txt',      as: 'EPL 1.0'       },
  { file: 'GPL-2.0.txt',      as: 'GPL 2.0'       },
  { file: 'GPL-3.0.txt',      as: 'GPL 3.0'       },
  { file: 'ISC.txt',          as: 'ISC.txt'       },
  { file: 'LGPL-2.1.txt',     as: 'LGPL 2.1'      },
  { file: 'LGPL-3.0.txt',     as: 'LGPL 3.0'      },
  { file: 'MIT.txt',          as: 'MIT'           },
  { file: 'MPL-1.0.txt',      as: 'MPL'           },
  { file: 'MPL-2.0.txt',      as: 'MPL 2.0'       },
  { file: 'Python2.txt',      as: 'Python 2.0'    },
  { file: 'UNLICENSE.txt',    as: 'UNLICENSE'     },
  { file: 'WTFPL.txt',        as: 'WTFPL'         },
  { file: 'beerware.txt',     as: 'Beerware'      },
  { file: 'cddl1.txt',        as: 'CDDL 1.0'      },
  { file: 'nasa.txt',         as: 'NASA 1.3'      },
  { file: 'zlib.txt',         as: 'zlib/libpng'   }
].forEach(function train(lesson) {
  classifier.addDocument(
    fs.readFileSync(__dirname +'/licenses/'+ lesson.file, 'utf-8'),
    lesson.as
  );
});

classifier.train();
Parser.readable('classifier', classifier);

//
// Expose the parser.
//
module.exports = Parser;
<commit_msg>[minor] Understand dual licensing<commit_after>'use strict';

var natural = require('natural')
  , fuse = require('fusing')
  , fs = require('fs');

/**
 * The base parser class where all parsers inherit from. This provides some
 * common functionality which the parsers can use to detect licensing.
 *
 * @constructor
 * @param {Object} parsers An object which contains all available parsers.
 * @api public
 */
function Parser(parsers) {
  if (!(this instanceof Parser)) return new Parser(parsers);

  this.parsers = parsers;
}

fuse(Parser);

/**
 * Expose some core modules through the instance.
 *
 * @type {Function}
 * @api pubilc
 */
Parser.readable('async', require('async'));
Parser.readable('request', require('request'));

/**
 * Simple regular expression based tests for figuring out which license we're
 * dealing with.
 *
 * @param {String} str
 * @returns {Array}
 * @api public
 */
Parser.readable('test', function test(str) {
  if (/BSD/.test(str)) return ['BSD'];
  if (/GPL/.test(str) || /GPLv2/.test(str)) return ['GPL'];
  if (/LGPL/.test(str)) return ['LGPL'];
  if (/MIT/.test(str) || /\(MIT\)/.test(str)) return ['MIT'];
  if (/Apache\s?Licen[cs]e/.test(str)) return ['Apache'];
  if (/MPL/.test(str)) return ['MPL'];

  //
  // Watch out we've got a bad-ass over here.
  //
  if (/DO\sWHAT\sTHE\sFUCK\sYOU\sWANT\sTO\sPUBLIC\sLICEN[CS]E/i.test(str)
   || /WTFPL/.test(str)
  ) return ['WTFPL'];
});

/**
 * There are 1000 ways of writing that you're using an MIT module. This
 * normalization module attempts to normalize the licenses in to one common
 * name.
 *
 * @param {Array} data A list of license information that needs to be normalized.
 * @api public
 */
Parser.readable('normalize', function normalize(data) {
  //
  // First we need to pass the data through our dual license checker so can
  // figure out if the module is dual licensed as both license values needs to
  // be normalized.
  //
  // 1. Direct match. Check for direct matches against our normalized license
  //    file.
  //
  // 2. toLowercase. Transform the given license string and the key of
  //    normalization to lowercase to see if it matches.
  //
  // 3. String distance. To see if there might have been some mistakes.
  //
  return data;
});

/**
 * Find an URL in the data structure.
 *
 * @param {Object} data Data structure
 * @param {String} contains A string that the URL should contain.
 * @api public
 */
Parser.readable('url', function url(data, contains) {
  if (!data) return undefined;

  if ('string' === typeof data && ~data.indexOf(contains)) return data;
  if ('object' === typeof data) {
    if ('url' in data) return url(data.url, contains);
    if ('web' in data) return url(data.web, contains);
  }

  return undefined;
});

/**
 * Check for potential dual licensing in the given license arrays. Most people
 * specify them in their package.json as : MIT/GPL because the `npm init`
 * doesn't really allow dual licensing.
 *
 * @param {Array} licenses
 * @returns {Array} licenses
 * @api public
 */
Parser.readable('dual', function dual(licenses) {
  var licensing = [];

  // check for / , or and, +
  return licenses.reduce(function reduce(licenses, license) {
    Array.prototype.push.apply(licenses, license.split(/\s{0,}(?:\/|and|or|,)\s{0,}/g));

    return licenses;
  }).filter(function duplicate(item, index, all) {
    return all.indexOf(item) === index;
  });
});

//
// Setup and train our classifier.
//
var classifier = new natural.BayesClassifier();

[
  { file: 'AFL2.1.txt',       as: 'AFL 2.1'       },
  { file: 'AFL3.0.txt',       as: 'AFL 3.0'       },
  { file: 'AGPL3.0.txt',      as: 'AGPL 3.0'      },
  { file: 'APL-1.0.txt',      as: 'APL 1.0'       },
  { file: 'Apache2.0.txt',    as: 'Apache 2.0'    },
  { file: 'BSD-2-Clause.txt', as: 'BSD 2-Clause'  },
  { file: 'BSD-3-Clause.txt', as: 'BSD 3-Clause'  },
  { file: 'BSD.txt',          as: 'BSD 4-Clouse'  },
  { file: 'BSL1.0.txt',       as: 'BSL 1.0'       },
  { file: 'EPL-1.0.txt',      as: 'EPL 1.0'       },
  { file: 'GPL-2.0.txt',      as: 'GPL 2.0'       },
  { file: 'GPL-3.0.txt',      as: 'GPL 3.0'       },
  { file: 'ISC.txt',          as: 'ISC.txt'       },
  { file: 'LGPL-2.1.txt',     as: 'LGPL 2.1'      },
  { file: 'LGPL-3.0.txt',     as: 'LGPL 3.0'      },
  { file: 'MIT.txt',          as: 'MIT'           },
  { file: 'MPL-1.0.txt',      as: 'MPL'           },
  { file: 'MPL-2.0.txt',      as: 'MPL 2.0'       },
  { file: 'Python2.txt',      as: 'Python 2.0'    },
  { file: 'UNLICENSE.txt',    as: 'UNLICENSE'     },
  { file: 'WTFPL.txt',        as: 'WTFPL'         },
  { file: 'beerware.txt',     as: 'Beerware'      },
  { file: 'cddl1.txt',        as: 'CDDL 1.0'      },
  { file: 'nasa.txt',         as: 'NASA 1.3'      },
  { file: 'zlib.txt',         as: 'zlib/libpng'   }
].forEach(function train(lesson) {
  classifier.addDocument(
    fs.readFileSync(__dirname +'/licenses/'+ lesson.file, 'utf-8'),
    lesson.as
  );
});

classifier.train();
Parser.readable('classifier', classifier);

//
// Expose the parser.
//
module.exports = Parser;
<|endoftext|>


<commit_before>psc.namespace('admin');

psc.admin.UserAdmin = (function ($) {
  var user;

  var provisionableSiteList = new Array();
  PROVISIONABLE_SITES.each(function(site) {
    provisionableSiteList.push(site.identifier)
  });

  function selectRole(roleKey) {
    $('a.role').removeClass('selected');
    $('#role-' + roleKey).addClass('selected');
    startEditing(roleKey);
  }

  function selectRoleTab(evt) {
    var roleKey = evt.target.id.substring("role-".length)
    selectRole(roleKey);
    return false;
  }

  function determineProvisionableStudies(role) {
    var isTM = _(role.uses || []).indexOf("template_management") >= 0;
    var isSP = _(role.uses || []).indexOf("site_participation") >= 0;
    if (isTM && isSP) {
      return PROVISIONABLE_STUDIES['template_management+site_participation'];
    } else if (isTM) {
      return PROVISIONABLE_STUDIES['template_management'];
    } else {
      // use participation even for roles that don't have uses
      return PROVISIONABLE_STUDIES['site_participation'];
    }
  }

  function startEditing(roleKey) {
    var role = _.detect(PROVISIONABLE_ROLES, function (role) { return role.key === roleKey });
    if (role) {
      var enabledGroupControl = true;
      var enabledSitesControl = true;
      var provisionableStudyList = new Array();
      determineProvisionableStudies(role).each(function(study) {
          provisionableStudyList.push(study.identifier)
      });
      var userMembershipsRole = user.memberships[role.key]
      if (userMembershipsRole != null) {

        if (userMembershipsRole['sites'] != null) {
          var membershipSiteList = userMembershipsRole['sites'].toString().split(",");
          var isSiteSubset = isSubsetOfProvision(provisionableSiteList, membershipSiteList);
        }

        if (userMembershipsRole['studies'] != null) {
          var membershipStudyList;
          membershipStudyList = userMembershipsRole['studies'].toString().split(",");
          var isStudySubset = isSubsetOfProvision(provisionableStudyList, membershipStudyList);
          if (!isSiteSubset || !isStudySubset) {
            enabledGroupControl = false;
          }
        } else {
          if (!isSiteSubset) {
            enabledGroupControl = false;
          }
        }

        if (!_.isEmpty(provisionableSiteList) && !_.isEmpty(membershipSiteList)) {
          if (!_.include(provisionableSiteList,'__ALL__') && _.include(membershipSiteList,'__ALL__')) {
            enabledSitesControl = false;
          }
        }
      }

      $('#role-editor-pane').html(resigTemplate('role_editor_template', {
          role: role, sites: PROVISIONABLE_SITES, studies: determineProvisionableStudies(role),
          enabledGroupControl: enabledGroupControl, enabledSitesControl: enabledSitesControl
        })).
        find('input.role-group-membership').attr('checked', !!user.memberships[role.key]).
        click(updateGroupMembership).end().
        parent().attr('role', roleKey);
      registerScopeControls('#role-editor-pane', role, 'site', 'sites');
      registerScopeControls('#role-editor-pane', role, 'study', 'studies');
    } else {
      alert("No such role " + roleKey);
    }
  }

  function isSubsetOfProvision(provisionableList, membershipList) {
    if(!_.isEmpty(provisionableList) && !_.isEmpty(membershipList)) {
      return _.all(membershipList, function(ele){
        return _.include(provisionableList,ele)
      })
    }
  }

  function registerScopeControls(pane, role, scopeType, scopeTypePlural) {
    $(pane).find('input.scope-' + scopeType).each(function (i, input) {
      var qMembership = {}; qMembership[scopeType] = $(input).attr(scopeType + '-identifier');
      $(input).attr(
        'checked',
        user.hasMembership(role.key, qMembership));
    }).click(_(updateMembershipScope).bind(this, role.key, scopeType, scopeTypePlural));
  }

  function updateGroupMembership(evt) {
    var role = evt.target.id.substring("group-".length);
    if ($(evt.target).attr('checked')) {
      user.add(role);
    } else {
      user.remove(role);
    }
  }

  function updateMembershipScope(roleKey, scopeType, scopeListName, evt) {
    console.log("Updating user obj", roleKey, scopeType, scopeListName, evt);
    var scope = {}; scope[scopeListName] = [ evt.target.getAttribute(scopeType + '-identifier') ];
    if ($(evt.target).attr('checked')) {
      user.add(roleKey, scope);
    } else {
      user.remove(roleKey, scope);
    }
  }

  function syncRoleTabOnChange(evt, data) {
    if (user.hasMembership(data.role)) {
      $('a#role-' + data.role).addClass('member');
    } else {
      $('a#role-' + data.role).removeClass('member');
    }
  }

  function syncRoleEditorOnChange(evt, data) {
    var role = data.role;
    var editorRole = $('#role-editor').attr('role');
    if (role !== editorRole) { return; }
    var input;
    if (data.scopeType) {
      input = $('#role-editor input#scope-' + data.scopeType + '-' + data.scopeIdentifier);
      setTimeout(syncAllVsOne, 0);
    } else {
      input = $('#role-editor input#group-' + data.role);
    }
    input.attr('checked', data.kind === 'add');
  }

  function syncAllVsOne() {
    _(['scope-study', 'scope-site']).each(function (scopeClass) {
      var isAll = $('#role-editor input.all.' + scopeClass + ":checked").length > 0;
      if (isAll) {
        $('#role-editor input.one.' + scopeClass).
          filter(':checked').click().end().
          attr("disabled", true).
          closest('div.row').addClass('disabled');
      } else {
        $('#role-editor input.one.' + scopeClass).
          attr("disabled", false).
          closest('div.row').removeClass('disabled');
      }
    });
  }

  function syncUsername() {
    user.username = $('input#username').val();
  }

  return {
    init: function (u) {
      user = u;
      _(user.memberships).each(function (scopes, roleKey) {
        $('#role-' + roleKey).addClass('member');
      }, this);
      var firstRole;
      if ($('a.role.member').length > 0) {
        firstRole = $('a.role.member')[0].id.substring("role-".length);
      } else {
        firstRole = 'study_subject_calendar_manager';
      }
      selectRole(firstRole);
      $('a.role').click(selectRoleTab);
      $(user).bind('membership-change', syncRoleTabOnChange).
        bind('membership-change', syncRoleEditorOnChange);
      $('input#username').keyup(syncUsername);
      syncAllVsOne();
    },

    serializeRoleChanges: function () {
      if (user.username) {
        var changes = {}; changes[user.username] = user.changes;
        return YAHOO.lang.JSON.stringify(changes);
      } else {
        return "{}";
      }
    }
  };
})(jQuery);
<commit_msg>Now checkboxes remain disabled when selecting all site/study and go to another role and back again. Fixes #1161.<commit_after>psc.namespace('admin');

psc.admin.UserAdmin = (function ($) {
  var user;

  var provisionableSiteList = new Array();
  PROVISIONABLE_SITES.each(function(site) {
    provisionableSiteList.push(site.identifier)
  });

  function selectRole(roleKey) {
    $('a.role').removeClass('selected');
    $('#role-' + roleKey).addClass('selected');
    startEditing(roleKey);
  }

  function selectRoleTab(evt) {
    var roleKey = evt.target.id.substring("role-".length)
    selectRole(roleKey);
    syncAllVsOne();
    return false;
  }

  function determineProvisionableStudies(role) {
    var isTM = _(role.uses || []).indexOf("template_management") >= 0;
    var isSP = _(role.uses || []).indexOf("site_participation") >= 0;
    if (isTM && isSP) {
      return PROVISIONABLE_STUDIES['template_management+site_participation'];
    } else if (isTM) {
      return PROVISIONABLE_STUDIES['template_management'];
    } else {
      // use participation even for roles that don't have uses
      return PROVISIONABLE_STUDIES['site_participation'];
    }
  }

  function startEditing(roleKey) {
    var role = _.detect(PROVISIONABLE_ROLES, function (role) { return role.key === roleKey });
    if (role) {
      var enabledGroupControl = true;
      var enabledSitesControl = true;
      var provisionableStudyList = new Array();
      determineProvisionableStudies(role).each(function(study) {
          provisionableStudyList.push(study.identifier)
      });
      var userMembershipsRole = user.memberships[role.key]
      if (userMembershipsRole != null) {

        if (userMembershipsRole['sites'] != null) {
          var membershipSiteList = userMembershipsRole['sites'].toString().split(",");
          var isSiteSubset = isSubsetOfProvision(provisionableSiteList, membershipSiteList);
        }

        if (userMembershipsRole['studies'] != null) {
          var membershipStudyList;
          membershipStudyList = userMembershipsRole['studies'].toString().split(",");
          var isStudySubset = isSubsetOfProvision(provisionableStudyList, membershipStudyList);
          if (!isSiteSubset || !isStudySubset) {
            enabledGroupControl = false;
          }
        } else {
          if (!isSiteSubset) {
            enabledGroupControl = false;
          }
        }

        if (!_.isEmpty(provisionableSiteList) && !_.isEmpty(membershipSiteList)) {
          if (!_.include(provisionableSiteList,'__ALL__') && _.include(membershipSiteList,'__ALL__')) {
            enabledSitesControl = false;
          }
        }
      }

      $('#role-editor-pane').html(resigTemplate('role_editor_template', {
          role: role, sites: PROVISIONABLE_SITES, studies: determineProvisionableStudies(role),
          enabledGroupControl: enabledGroupControl, enabledSitesControl: enabledSitesControl
        })).
        find('input.role-group-membership').attr('checked', !!user.memberships[role.key]).
        click(updateGroupMembership).end().
        parent().attr('role', roleKey);
      registerScopeControls('#role-editor-pane', role, 'site', 'sites');
      registerScopeControls('#role-editor-pane', role, 'study', 'studies');
    } else {
      alert("No such role " + roleKey);
    }
  }

  function isSubsetOfProvision(provisionableList, membershipList) {
    if(!_.isEmpty(provisionableList) && !_.isEmpty(membershipList)) {
      return _.all(membershipList, function(ele){
        return _.include(provisionableList,ele)
      })
    }
  }

  function registerScopeControls(pane, role, scopeType, scopeTypePlural) {
    $(pane).find('input.scope-' + scopeType).each(function (i, input) {
      var qMembership = {}; qMembership[scopeType] = $(input).attr(scopeType + '-identifier');
      $(input).attr(
        'checked',
        user.hasMembership(role.key, qMembership));
    }).click(_(updateMembershipScope).bind(this, role.key, scopeType, scopeTypePlural));
  }

  function updateGroupMembership(evt) {
    var role = evt.target.id.substring("group-".length);
    if ($(evt.target).attr('checked')) {
      user.add(role);
    } else {
      user.remove(role);
    }
  }

  function updateMembershipScope(roleKey, scopeType, scopeListName, evt) {
    console.log("Updating user obj", roleKey, scopeType, scopeListName, evt);
    var scope = {}; scope[scopeListName] = [ evt.target.getAttribute(scopeType + '-identifier') ];
    if ($(evt.target).attr('checked')) {
      user.add(roleKey, scope);
    } else {
      user.remove(roleKey, scope);
    }
  }

  function syncRoleTabOnChange(evt, data) {
    if (user.hasMembership(data.role)) {
      $('a#role-' + data.role).addClass('member');
    } else {
      $('a#role-' + data.role).removeClass('member');
    }
  }

  function syncRoleEditorOnChange(evt, data) {
    var role = data.role;
    var editorRole = $('#role-editor').attr('role');
    if (role !== editorRole) { return; }
    var input;
    if (data.scopeType) {
      input = $('#role-editor input#scope-' + data.scopeType + '-' + data.scopeIdentifier);
      setTimeout(syncAllVsOne, 0);
    } else {
      input = $('#role-editor input#group-' + data.role);
    }
    input.attr('checked', data.kind === 'add');
  }

  function syncAllVsOne() {
    _(['scope-study', 'scope-site']).each(function (scopeClass) {
      var isAll = $('#role-editor input.all.' + scopeClass + ":checked").length > 0;
      if (isAll) {
        $('#role-editor input.one.' + scopeClass).
          filter(':checked').click().end().
          attr("disabled", true).
          closest('div.row').addClass('disabled');
      } else {
        $('#role-editor input.one.' + scopeClass).
          attr("disabled", false).
          closest('div.row').removeClass('disabled');
      }
    });
  }

  function syncUsername() {
    user.username = $('input#username').val();
  }

  return {
    init: function (u) {
      user = u;
      _(user.memberships).each(function (scopes, roleKey) {
        $('#role-' + roleKey).addClass('member');
      }, this);
      var firstRole;
      if ($('a.role.member').length > 0) {
        firstRole = $('a.role.member')[0].id.substring("role-".length);
      } else {
        firstRole = 'study_subject_calendar_manager';
      }
      selectRole(firstRole);
      $('a.role').click(selectRoleTab);
      $(user).bind('membership-change', syncRoleTabOnChange).
        bind('membership-change', syncRoleEditorOnChange);
      $('input#username').keyup(syncUsername);
      syncAllVsOne();
    },

    serializeRoleChanges: function () {
      if (user.username) {
        var changes = {}; changes[user.username] = user.changes;
        return YAHOO.lang.JSON.stringify(changes);
      } else {
        return "{}";
      }
    }
  };
})(jQuery);
<|endoftext|>


<commit_before>// load type definitions that come with Cypress module
/// <reference types="cypress" />
/**
 * @param {number} initialMoodValue
 */
function recordMeasurementAndCheckHistoryPage (initialMoodValue) {
  cy.url().should('contain', '/measurement-add')
  cy.get(`.primary-outcome-variable-history > img:nth-of-type(${initialMoodValue})`)
        .click({ force: true })
  cy.get('#saveButton').click({ force: true })
  cy.log('Waiting for measurement to post to API...')
  cy.wait(10000)
  cy.visitIonicAndSetApiUrl('/#/app/history-all-variable/Overall Mood')
  //let desiredImageName = moodValueToImage(initialMoodValue)
  // cy.get("#historyItem-0 > img", {timeout: 30000}).invoke('attr', 'src')
  //     .should('contain', desiredImageName);
}
/**
 * @param {number} [dosageValue]
 */
function recordTreatmentMeasurementAndCheckHistoryPage (dosageValue) {
  if (!dosageValue) {
    let d = new Date()

    dosageValue = d.getMinutes()
  }

  cy.loginWithAccessTokenIfNecessary('/#/app/measurement-add-search?variableCategoryName=Treatments')
  let variableName = 'Aaa Test Treatment'

  cy.searchAndClickTopResult(variableName, true)
  cy.log('Click Remind me to track')
  cy.get('#reminderButton').click({ force: true })
  cy.log('Check that reminders add page was reached')
  cy.url().should('include', '#/app/reminder-add')
  cy.get('#cancelButton').click({ force: true })
  cy.log('Get dosage value from current time (minutes)')
  cy.log('Assign current minutes to dosage')
  cy.get('#defaultValue').type(dosageValue.toString(), { force: true })
  cy.get('#unitSelector').should('contain', 'Milligrams')
  cy.log('Check that mg is selected')
  cy.get('#saveButton').click({ force: true })
  cy.wait(10000)
  cy.visitIonicAndSetApiUrl('/#/app/history-all-category/Treatments')
  let treatmentStringNoQuotes = `${dosageValue} mg Aaa Test Treatment`

  cy.get('#historyItemTitle', { timeout: 40000 })
        .should('contain', treatmentStringNoQuotes)
}
/**
 * @param {string} itemTitle
 */
function editHistoryPageMeasurement (itemTitle) {
  cy.log(`Editing history measurement with title containing: ${itemTitle}`)
  cy.get('#historyItemTitle', { timeout: 30000 }).contains(itemTitle)
  cy.get('#action-sheet-button', { timeout: 30000 }).click({ force: true })
  cy.clickActionSheetButtonContaining('Edit')
  cy.wait(2000)
  cy.url().should('include', 'measurement-add')
}
describe('Measurements', function () {
  it('Goes to edit measurement from history page', function () {
    cy.loginWithAccessTokenIfNecessary('/#/app/history-all-category/Anything')
    cy.get('#historyItemTitle', { timeout: 30000 }).click({force: true})
    cy.clickActionSheetButtonContaining('Edit')
    cy.wait(2000)
    cy.url().should('include', 'measurement-add')
  })
  it('Records, edits, and deletes a mood measurement', function () {
    cy.loginWithAccessTokenIfNecessary('/#/app/measurement-add-search')
    let variableName = 'Overall Mood'

    cy.searchAndClickTopResult(variableName, true)
    let d = new Date()
    let seconds = d.getSeconds()
    let initialMoodValue = (seconds % 5) + 1

    recordMeasurementAndCheckHistoryPage(initialMoodValue)
    // cy.get('#hidden-measurement-id').then(($el) => {
    //     let measurementId = $el.text();
    //     cy.get(
    //         '.list > [id="historyItem-0"].item.item-avatar.item-button-right:nth-of-type(1) > .buttons >
    // button.button.button-dark') .click({force: true}); cy.clickActionSheetButtonContaining('Edit'); let
    // newMoodValue = ((initialMoodValue % 5) + 1);
    // cy.visit(`/#/app/measurement-add?measurementId=${measurementId}`);
    // recordMeasurementAndCheckHistoryPage(newMoodValue); cy.get("#hidden-measurement-id").then(($el) => { let
    // editedMeasurementId = $el.text(); cy.visit(`/#/app/measurement-add?measurementId=${editedMeasurementId}`);
    // cy.get('#deleteButton').click({force: true}); cy.wait(10000); cy.visit(`/#/app/history-all-variable/Overall
    // Mood`); cy.get("#hidden-measurement-id").should('not.contain', editedMeasurementId); }); });
  })
    // Skipping because it fails randomly and can't reproduce failure locally
  it.skip('Record, edit, and delete a treatment measurement', function () {
    let dosageValue = 100

    recordTreatmentMeasurementAndCheckHistoryPage(dosageValue)
    editHistoryPageMeasurement(dosageValue.toString())
    let newDosageValue = dosageValue / 10

    cy.get('#defaultValue').type(newDosageValue.toString(), { force: true })
    cy.get('#saveButton').click({ force: true })
    cy.wait(10000)
    cy.visitIonicAndSetApiUrl('/#/app/history-all-category/Treatments')
    let treatmentStringEditedNoQuotes = `${newDosageValue} mg Aaa Test Treatment`

    editHistoryPageMeasurement(newDosageValue.toString())
    cy.get('button.button.icon-left.ion-trash-a').click({ force: true })
    cy.wait(10000)
    cy.url().should('include', '/#/app/history-all-category/Treatments')
    cy.log('Check that deleted measurement is gone (must use does not equal instead of does not contain because a ' +
            'measurement of 0mg will be true if the value is 50mg)')
    cy.get('#historyItemTitle', { timeout: 40000 })
            .should('not.contain', treatmentStringEditedNoQuotes)
  })
    // Randomly fails and can't reproduce locally
  it.skip('Records a treatment measurement and checks history', function () {
    recordTreatmentMeasurementAndCheckHistoryPage()
  })
})
<commit_msg>skip('Records, edits, and deletes a mood measurement'<commit_after>// load type definitions that come with Cypress module
/// <reference types="cypress" />
/**
 * @param {number} initialMoodValue
 */
function recordMeasurementAndCheckHistoryPage (initialMoodValue) {
  cy.url().should('contain', '/measurement-add')
  cy.get(`.primary-outcome-variable-history > img:nth-of-type(${initialMoodValue})`)
        .click({ force: true })
  cy.get('#saveButton').click({ force: true })
  cy.log('Waiting for measurement to post to API...')
  cy.wait(10000)
  cy.visitIonicAndSetApiUrl('/#/app/history-all-variable/Overall Mood')
  //let desiredImageName = moodValueToImage(initialMoodValue)
  // cy.get("#historyItem-0 > img", {timeout: 30000}).invoke('attr', 'src')
  //     .should('contain', desiredImageName);
}
/**
 * @param {number} [dosageValue]
 */
function recordTreatmentMeasurementAndCheckHistoryPage (dosageValue) {
  if (!dosageValue) {
    let d = new Date()

    dosageValue = d.getMinutes()
  }

  cy.loginWithAccessTokenIfNecessary('/#/app/measurement-add-search?variableCategoryName=Treatments')
  let variableName = 'Aaa Test Treatment'

  cy.searchAndClickTopResult(variableName, true)
  cy.log('Click Remind me to track')
  cy.get('#reminderButton').click({ force: true })
  cy.log('Check that reminders add page was reached')
  cy.url().should('include', '#/app/reminder-add')
  cy.get('#cancelButton').click({ force: true })
  cy.log('Get dosage value from current time (minutes)')
  cy.log('Assign current minutes to dosage')
  cy.get('#defaultValue').type(dosageValue.toString(), { force: true })
  cy.get('#unitSelector').should('contain', 'Milligrams')
  cy.log('Check that mg is selected')
  cy.get('#saveButton').click({ force: true })
  cy.wait(10000)
  cy.visitIonicAndSetApiUrl('/#/app/history-all-category/Treatments')
  let treatmentStringNoQuotes = `${dosageValue} mg Aaa Test Treatment`

  cy.get('#historyItemTitle', { timeout: 40000 })
        .should('contain', treatmentStringNoQuotes)
}
/**
 * @param {string} itemTitle
 */
function editHistoryPageMeasurement (itemTitle) {
  cy.log(`Editing history measurement with title containing: ${itemTitle}`)
  cy.get('#historyItemTitle', { timeout: 30000 }).contains(itemTitle)
  cy.get('#action-sheet-button', { timeout: 30000 }).click({ force: true })
  cy.clickActionSheetButtonContaining('Edit')
  cy.wait(2000)
  cy.url().should('include', 'measurement-add')
}
describe('Measurements', function () {
  it('Goes to edit measurement from history page', function () {
    cy.loginWithAccessTokenIfNecessary('/#/app/history-all-category/Anything')
    cy.get('#historyItemTitle', { timeout: 30000 }).click({force: true})
    cy.clickActionSheetButtonContaining('Edit')
    cy.wait(2000)
    cy.url().should('include', 'measurement-add')
  })
    // Skipping because it fails randomly and can't reproduce failure locally
  it.skip('Records, edits, and deletes a mood measurement', function () {
    cy.loginWithAccessTokenIfNecessary('/#/app/measurement-add-search')
    let variableName = 'Overall Mood'

    cy.searchAndClickTopResult(variableName, true)
    let d = new Date()
    let seconds = d.getSeconds()
    let initialMoodValue = (seconds % 5) + 1

    recordMeasurementAndCheckHistoryPage(initialMoodValue)
    // cy.get('#hidden-measurement-id').then(($el) => {
    //     let measurementId = $el.text();
    //     cy.get(
    //         '.list > [id="historyItem-0"].item.item-avatar.item-button-right:nth-of-type(1) > .buttons >
    // button.button.button-dark') .click({force: true}); cy.clickActionSheetButtonContaining('Edit'); let
    // newMoodValue = ((initialMoodValue % 5) + 1);
    // cy.visit(`/#/app/measurement-add?measurementId=${measurementId}`);
    // recordMeasurementAndCheckHistoryPage(newMoodValue); cy.get("#hidden-measurement-id").then(($el) => { let
    // editedMeasurementId = $el.text(); cy.visit(`/#/app/measurement-add?measurementId=${editedMeasurementId}`);
    // cy.get('#deleteButton').click({force: true}); cy.wait(10000); cy.visit(`/#/app/history-all-variable/Overall
    // Mood`); cy.get("#hidden-measurement-id").should('not.contain', editedMeasurementId); }); });
  })
    // Skipping because it fails randomly and can't reproduce failure locally
  it.skip('Record, edit, and delete a treatment measurement', function () {
    let dosageValue = 100

    recordTreatmentMeasurementAndCheckHistoryPage(dosageValue)
    editHistoryPageMeasurement(dosageValue.toString())
    let newDosageValue = dosageValue / 10

    cy.get('#defaultValue').type(newDosageValue.toString(), { force: true })
    cy.get('#saveButton').click({ force: true })
    cy.wait(10000)
    cy.visitIonicAndSetApiUrl('/#/app/history-all-category/Treatments')
    let treatmentStringEditedNoQuotes = `${newDosageValue} mg Aaa Test Treatment`

    editHistoryPageMeasurement(newDosageValue.toString())
    cy.get('button.button.icon-left.ion-trash-a').click({ force: true })
    cy.wait(10000)
    cy.url().should('include', '/#/app/history-all-category/Treatments')
    cy.log('Check that deleted measurement is gone (must use does not equal instead of does not contain because a ' +
            'measurement of 0mg will be true if the value is 50mg)')
    cy.get('#historyItemTitle', { timeout: 40000 })
            .should('not.contain', treatmentStringEditedNoQuotes)
  })
    // Randomly fails and can't reproduce locally
  it.skip('Records a treatment measurement and checks history', function () {
    recordTreatmentMeasurementAndCheckHistoryPage()
  })
})
<|endoftext|>


<commit_before>var ElementType = require("./ElementType.js");

function DefaultHandler (callback, options) {
	this.dom = [];
	this._done = false;
	this._tagStack = [];
	this._options = options ? options : { };
	if (this._options.ignoreWhitespace === undefined)
		this._options.ignoreWhitespace = false; //Keep whitespace-only text nodes
	if (this._options.verbose === undefined)
		this._options.verbose = true; //Keep data property for tags and raw property for all
	if (this._options.enforceEmptyTags === undefined)
		this._options.enforceEmptyTags = true; //Don't allow children for HTML tags defined as empty in spec
	if ((typeof callback) === "function")
		this._callback = callback;
}

//**"Static"**//
//HTML Tags that shouldn't contain child nodes
DefaultHandler._emptyTags = {
	area: 1
	, base: 1
	, basefont: 1
	, br: 1
	, col: 1
	, frame: 1
	, hr: 1
	, img: 1
	, input: 1
	, isindex: 1
	, link: 1
	, meta: 1
	, param: 1
	, embed: 1
};
//Regex to detect whitespace only text nodes
var reWhitespace = /^\s*$/;

//**Public**//
//Methods//
//Resets the handler back to starting state
DefaultHandler.prototype.reset = function() {
	this.dom = [];
	this._done = false;
	this._tagStack = [];
	this._tagStack.last = function() {
		return(this.length ? this[this.length - 1] : null);
	};
};
//Signals the handler that parsing is done
DefaultHandler.prototype.done = function() {
	this._done = true;
	this.handleCallback(null);
};
DefaultHandler.prototype.writeText = function(element) {
	if(this._options.ignoreWhitespace)
		if(reWhitespace.test(element.data))
			return;
	this.handleElement(element);
};

//Methods//
DefaultHandler.prototype.error =
DefaultHandler.prototype.handleCallback = function(error) {
		if ((typeof this._callback) !== "function")
			if (error)
				throw error;
			else
				return;
		this._callback(error, this.dom);
};

DefaultHandler.prototype.isEmptyTag = function(element) {
	var name = element.name.toLowerCase();
	if (name.charAt(0) === '/') {
		name = name.substring(1);
	}
	return this._options.enforceEmptyTags && !!DefaultHandler._emptyTags[name];
};

DefaultHandler.prototype.writeTag = DefaultHandler.prototype.writeDirective = DefaultHandler.prototype.writeComment =
DefaultHandler.prototype.handleElement = function(element) {
	if (this._done)
		this.handleCallback(new Error("Writing to the handler after done() called is not allowed without a reset()"));
	if (!this._options.verbose) {
		//element.raw = null; //FIXME: Not clean
		//FIXME: Serious performance problem using delete
		delete element.raw;
		if (element.type === "tag" || element.type === "script" || element.type === "style")
			delete element.data;
	}
	if (!this._tagStack.last()) { //There are no parent elements
		//If the element can be a container, add it to the tag stack and the top level list
		if (element.type !== ElementType.Text && element.type !== ElementType.Comment && element.type !== ElementType.Directive) {
			if (element.name.charAt(0) !== "/") { //Ignore closing tags that obviously don't have an opening tag
				this.dom.push(element);
				if (!this.isEmptyTag(element)) { //Don't add tags to the tag stack that can't have children
					this._tagStack.push(element);
				}
			}
		}
		else //Otherwise just add to the top level list
			this.dom.push(element);
	}
	else { //There are parent elements
		//If the element can be a container, add it as a child of the element
		//on top of the tag stack and then add it to the tag stack
		if (element.type !== ElementType.Text && element.type !== ElementType.Comment && element.type !== ElementType.Directive) {
			if (element.name.charAt(0) === "/") {
				//This is a closing tag, scan the tagStack to find the matching opening tag
				//and pop the stack up to the opening tag's parent
				var baseName = element.name.substring(1);
				if (!this.isEmptyTag(element)) {
					var pos = this._tagStack.length - 1;
					while (pos > -1 && this._tagStack[pos--].name !== baseName) { }
					if (pos > -1 || this._tagStack[0].name === baseName)
						while (pos < this._tagStack.length - 1)
							this._tagStack.pop();
				}
			}
			else { //This is not a closing tag
				if (!this._tagStack.last().children)
					this._tagStack.last().children = [];
				this._tagStack.last().children.push(element);
				if (!this.isEmptyTag(element)) //Don't add tags to the tag stack that can't have children
					this._tagStack.push(element);
			}
		}
		else { //This is not a container element
			if (!this._tagStack.last().children)
				this._tagStack.last().children = [];
			this._tagStack.last().children.push(element);
		}
	}
};

module.exports = DefaultHandler;<commit_msg>moved "last()"-method from _callStack to DefaultHandlers prototype<commit_after>var ElementType = require("./ElementType.js");

function DefaultHandler (callback, options) {
	this.dom = [];
	this._done = false;
	this._tagStack = [];
	this._options = options ? options : { };
	if (this._options.ignoreWhitespace === undefined)
		this._options.ignoreWhitespace = false; //Keep whitespace-only text nodes
	if (this._options.verbose === undefined)
		this._options.verbose = true; //Keep data property for tags and raw property for all
	if (this._options.enforceEmptyTags === undefined)
		this._options.enforceEmptyTags = true; //Don't allow children for HTML tags defined as empty in spec
	if ((typeof callback) === "function")
		this._callback = callback;
}

DefaultHandler.prototype._lastTag = function() {
	var stack = this._tagStack;
	return(stack.length ? stack[stack.length - 1] : null);
};

//HTML Tags that shouldn't contain child nodes
var _emptyTags = {
	area: true
	, base: true
	, basefont: true
	, br: true
	, col: true
	, frame: true
	, hr: true
	, img: true
	, input: true
	, isindex: true
	, link: true
	, meta: true
	, param: true
	, embed: true
};
//Regex to detect whitespace only text nodes
var reWhitespace = /^\s*$/;

//**Public**//
//Methods//
//Resets the handler back to starting state
DefaultHandler.prototype.reset = function() {
	this.dom = [];
	this._done = false;
	this._tagStack = [];
};
//Signals the handler that parsing is done
DefaultHandler.prototype.done = function() {
	this._done = true;
	this.handleCallback(null);
};
DefaultHandler.prototype.writeText = function(element) {
	if(this._options.ignoreWhitespace)
		if(reWhitespace.test(element.data))
			return;
	this.handleElement(element);
};

//Methods//
DefaultHandler.prototype.error =
DefaultHandler.prototype.handleCallback = function(error) {
		if ((typeof this._callback) !== "function")
			if (error)
				throw error;
			else
				return;
		this._callback(error, this.dom);
};

DefaultHandler.prototype.isEmptyTag = function(element) {
	var name = element.name.toLowerCase();
	if (name.charAt(0) === '/') {
		name = name.substring(1);
	}
	return this._options.enforceEmptyTags && _emptyTags[name];
};

DefaultHandler.prototype.writeTag = DefaultHandler.prototype.writeDirective = DefaultHandler.prototype.writeComment =
DefaultHandler.prototype.handleElement = function(element) {
	if (this._done)
		this.handleCallback(new Error("Writing to the handler after done() called is not allowed without a reset()"));
	if (!this._options.verbose) {
		//element.raw = null; //FIXME: Not clean
		//FIXME: Serious performance problem using delete
		delete element.raw;
		if (element.type === "tag" || element.type === "script" || element.type === "style")
			delete element.data;
	}
	if (!this._lastTag()) { //There are no parent elements
		//If the element can be a container, add it to the tag stack and the top level list
		if (element.type !== ElementType.Text && element.type !== ElementType.Comment && element.type !== ElementType.Directive) {
			if (element.name.charAt(0) !== "/") { //Ignore closing tags that obviously don't have an opening tag
				this.dom.push(element);
				if (!this.isEmptyTag(element)) { //Don't add tags to the tag stack that can't have children
					this._tagStack.push(element);
				}
			}
		}
		else //Otherwise just add to the top level list
			this.dom.push(element);
	}
	else { //There are parent elements
		//If the element can be a container, add it as a child of the element
		//on top of the tag stack and then add it to the tag stack
		if (element.type !== ElementType.Text && element.type !== ElementType.Comment && element.type !== ElementType.Directive) {
			if (element.name.charAt(0) === "/") {
				//This is a closing tag, scan the tagStack to find the matching opening tag
				//and pop the stack up to the opening tag's parent
				var baseName = element.name.substring(1);
				if (!this.isEmptyTag(element)) {
					var pos = this._tagStack.length - 1;
					while (pos > -1 && this._tagStack[pos--].name !== baseName) { }
					if (pos > -1 || this._tagStack[0].name === baseName)
						while (pos < this._tagStack.length - 1)
							this._tagStack.pop();
				}
			}
			else { //This is not a closing tag
				if (!this._lastTag().children)
					this._lastTag().children = [];
				this._lastTag().children.push(element);
				if (!this.isEmptyTag(element)) //Don't add tags to the tag stack that can't have children
					this._tagStack.push(element);
			}
		}
		else { //This is not a container element
			if (!this._lastTag().children)
				this._lastTag().children = [];
			this._lastTag().children.push(element);
		}
	}
};

module.exports = DefaultHandler;<|endoftext|>


<commit_before>$(document).ready(function() {
  $('#edit_seo_btn').bind('click', function() {
    $('#edit_seo_btn').slideUp();
    $('#edit_seo_dialog').slideDown();
  });

  $('#cancel_seo_btn, #save_seo_tag').bind('click', function() {
    hideSeoForm();
  });

  $('#more-options-btn').bind('click', function() {
    $('#more-options').toggle();
  });

});

function hideSeoForm(){
  $('#edit_seo_dialog').slideUp();
  $('#edit_seo_btn').slideDown();
}<commit_msg>updated js to hide more-options-link<commit_after>$(document).ready(function() {
  $('#edit_seo_btn').bind('click', function() {
    $('#edit_seo_btn').slideUp();
    $('#edit_seo_dialog').slideDown();
  });

  $('#cancel_seo_btn, #save_seo_tag').bind('click', function() {
    hideSeoForm();
  });

  $('#more-options-btn').bind('click', function() {
    $('#more-options').show();
    $('#more-options-btn').hide();
  });

});

function hideSeoForm(){
  $('#edit_seo_dialog').slideUp();
  $('#edit_seo_btn').slideDown();
  $('#more-options').hide();
  $('#more-options-btn').show();
}<|endoftext|>


<commit_before>function cw2pad(x){

  var out, i$, ref$, len$, ln, replace$ = ''.replace;
  out = '';
  var names = {};
  ref$ = x.split(/\n+/);
  if ((ref$.length > 0) && (!/[：:]/.exec(ref$[0]))) {
    out += (ref$.shift() + "\n");
  }
  for (i$ = 0, len$ = ref$.length; i$ < len$; ++i$) {
    ln = ref$[i$];
    if (/^\s*$/.exec(ln)) {
      continue;
    }
    if (/[\(\[]crosstalk[\)\]]/.exec(ln)) {
      continue;
    }
    if (/[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+:(?!\d)/.exec(ln) && /^((?:\s\w\.|[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+)+):(?!\d)/.exec(ln)) {
      var n = RegExp.$1;
      if (/ /.test(n)) {
        names[n.replace(/ .*/, '')] = n;
      }
      else if (names[n]) {
        ln = replace$.call(ln, /^(?:\s\w\.|[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+)+:/, (names[n] + ':'));
      }
    }

    if (/^\[(.*)\]/.exec(ln)) {
      out += "\n" + (replace$.call(ln, /^\[(.*)\]/, '($1)')) + "\n";
      continue;
    }
    if (/[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+:(?!\d)/.exec(ln) && /^(?:\s\w\.|[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+)+: +/.exec(ln)) {
      out += "\n" + (replace$.call(ln, /^((?:\s\w\.|[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+)+): +/, "$1:\n    ")) + "\n";
      continue;
    }
    if (/\S/.exec(ln))  {
      out += "    " + ln + "\n";
      continue;
    }
  }
  return out;
}

function pad2md(x){
  var out, i$, ref$, len$, ln, replace$ = ''.replace;
  out = '';
  for (i$ = 0, len$ = (ref$ = x.split(/\n+/)).length; i$ < len$; ++i$) {
    ln = ref$[i$];
    if (/^[🌐📅🏡]|^:::/.exec(ln)) {
	out += ln + "\n";
      continue;
    }
    if (/^((?:19|2[0-9])\d{2})-(1[012]|0[1-9])-(3[01]|[12][0-9]|0?[1-9])/.exec(ln)) {
      out += "# " + ln + "\n\n";
      continue;
    }
    if (/^\s+/.exec(ln)) {
      out += (replace$.call(ln, /^\s+/, '').replace(/\]（(.*?)）/g, ']($1)')) + "\n\n";
      continue;
    }
    if (/[：:]\s*$/.exec(ln)) {
      out += "### " + (replace$.call(ln, /([：:])\s+$/, '$1')) + "\n";
      continue;
    }
    if (/^[（(]/.exec(ln)) {
	out += "> " + ln + "\n\n";
      continue;
    }
    if (/^[【[]/.exec(ln)) {
	out += "\n" + ln + "\n\n";
      continue;
    }
    if (/\S/.exec(ln))  {
	out += ":::warning\n" + ln + "\n:::\n\n";
      continue;
    }
  }

  return out;
}

function md2pad(x){
  var out, i$, ref$, len$, ln, replace$ = ''.replace;
  out = '';
  for (i$ = 0, len$ = (ref$ = x.split(/\n+/)).length; i$ < len$; ++i$) {
    ln = ref$[i$];
    if (/^###\s+/.exec(ln)) {
      out += "\n" + (replace$.call(ln, /^###\s+/, '')) + "\n";
      continue;
    }
    if (/^#\s+/.exec(ln)) {
        out += (replace$.call(ln, /^#\s+/, '')) + "\n\n";
      continue;
    }
    if (/^>\s+/.exec(ln)) {
        out += "\n" + (replace$.call(ln, /^>\s+/, '')) + "\n";
      continue;
    }
    if (/^【/.exec(ln)) {
        out += "\n" + ln + "\n\n";
      continue;
    }
    if (/^[🌐📅🏡]|^:::/.exec(ln)) {
	out += ln + "\n";
      continue;
    }
    if (/\S/.exec(ln))  {
	out += "    " + ln + "\n";
      continue;
    }
  }

  return out;
}
<commit_msg>* adjust md2pad metadata line handling<commit_after>function cw2pad(x){

  var out, i$, ref$, len$, ln, replace$ = ''.replace;
  out = '';
  var names = {};
  ref$ = x.split(/\n+/);
  if ((ref$.length > 0) && (!/[：:]/.exec(ref$[0]))) {
    out += (ref$.shift() + "\n");
  }
  for (i$ = 0, len$ = ref$.length; i$ < len$; ++i$) {
    ln = ref$[i$];
    if (/^\s*$/.exec(ln)) {
      continue;
    }
    if (/[\(\[]crosstalk[\)\]]/.exec(ln)) {
      continue;
    }
    if (/[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+:(?!\d)/.exec(ln) && /^((?:\s\w\.|[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+)+):(?!\d)/.exec(ln)) {
      var n = RegExp.$1;
      if (/ /.test(n)) {
        names[n.replace(/ .*/, '')] = n;
      }
      else if (names[n]) {
        ln = replace$.call(ln, /^(?:\s\w\.|[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+)+:/, (names[n] + ':'));
      }
    }

    if (/^\[(.*)\]/.exec(ln)) {
      out += "\n" + (replace$.call(ln, /^\[(.*)\]/, '($1)')) + "\n";
      continue;
    }
    if (/[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+:(?!\d)/.exec(ln) && /^(?:\s\w\.|[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+)+: +/.exec(ln)) {
      out += "\n" + (replace$.call(ln, /^((?:\s\w\.|[-'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\w ]+)+): +/, "$1:\n    ")) + "\n";
      continue;
    }
    if (/\S/.exec(ln))  {
      out += "    " + ln + "\n";
      continue;
    }
  }
  return out;
}

function pad2md(x){
  var out, i$, ref$, len$, ln, replace$ = ''.replace;
  out = '';
  for (i$ = 0, len$ = (ref$ = x.split(/\n+/)).length; i$ < len$; ++i$) {
    ln = ref$[i$];
    if (/^[🌐📅🏡]|^:::/.exec(ln)) {
	out += ln + "\n";
      continue;
    }
    if (/^((?:19|2[0-9])\d{2})-(1[012]|0[1-9])-(3[01]|[12][0-9]|0?[1-9])/.exec(ln)) {
      out += "# " + ln + "\n\n";
      continue;
    }
    if (/^\s+/.exec(ln)) {
      out += (replace$.call(ln, /^\s+/, '').replace(/\]（(.*?)）/g, ']($1)')) + "\n\n";
      continue;
    }
    if (/[：:]\s*$/.exec(ln)) {
      out += "### " + (replace$.call(ln, /([：:])\s+$/, '$1')) + "\n";
      continue;
    }
    if (/^[（(]/.exec(ln)) {
	out += "> " + ln + "\n\n";
      continue;
    }
    if (/^[【[]/.exec(ln)) {
	out += "\n" + ln + "\n\n";
      continue;
    }
    if (/\S/.exec(ln))  {
	out += ":::warning\n" + ln + "\n:::\n\n";
      continue;
    }
  }

  return out;
}

function md2pad(x){
  var out, i$, ref$, len$, ln, replace$ = ''.replace;
  out = '';
  x = replace$.call(x, /^#+\s+/, '# ');
  for (i$ = 0, len$ = (ref$ = x.split(/\n+/)).length; i$ < len$; ++i$) {
    ln = ref$[i$];
    if (/^[【🌐📅🏡]|^:::/.exec(ln)) {
      continue;
    }
    if (/^###\s+/.exec(ln)) {
      out += "\n" + (replace$.call(ln, /^###\s+/, '')) + "\n";
      continue;
    }
    if (/^#\s+/.exec(ln)) {
        out += (replace$.call(ln, /^#\s+/, '')) + "\n\n";
      continue;
    }
    if (/^>\s+/.exec(ln)) {
        out += "\n" + (replace$.call(ln, /^>\s+/, '')) + "\n";
      continue;
    }
    if (/^【/.exec(ln)) {
        out += "\n" + ln + "\n\n";
      continue;
    }
    if (/^[🌐📅🏡]|^:::/.exec(ln)) {
	out += ln + "\n";
      continue;
    }
    if (/\S/.exec(ln))  {
	out += "    " + ln + "\n";
      continue;
    }
  }

  return out;
}
<|endoftext|>


<commit_before>/** @babel */

import FuzzyFinderView from './fuzzy-finder-view'

export default class BufferView extends FuzzyFinderView {
  getEmptyMessage () {
    return 'No open editors'
  }

  async toggle () {
    if (this.panel && this.panel.isVisible()) {
      this.cancel()
    } else {
      const workspaceEditors = atom.workspace.getTextEditors().filter((editor) => editor.getPath())
      const activeEditor = atom.workspace.getActiveTextEditor()
      workspaceEditors.sort((a, b) => {
        if (a === activeEditor) {
          return 1
        } else if (b === activeEditor) {
          return -1
        } else {
          return (b.lastOpened || 1) - (a.lastOpened || 1)
        }
      })

      const uniqueWorkspacePaths = Array.from(new Set(workspaceEditors.map((editor) => editor.getPath())))
      const workspaceItems = this.projectRelativePathsForFilePaths(uniqueWorkspacePaths)

      let remoteItems
      if (this.teletype) {
        const remoteBuffers = await this.teletype.getRemoteBuffers()
        remoteItems = remoteBuffers.map((b) => {
          return {filePath: b.uri, label: b.label}
        })
      } else {
        remoteItems = []
      }

      const items = remoteItems.concat(workspaceItems)
      if (items.length > 0) {
        this.show()
        await this.setItems(items)
      }
    }
  }
}
<commit_msg>Don't use Babel in lib/buffer-view.js<commit_after>const FuzzyFinderView = require('./fuzzy-finder-view')

module.exports =
class BufferView extends FuzzyFinderView {
  getEmptyMessage () {
    return 'No open editors'
  }

  async toggle () {
    if (this.panel && this.panel.isVisible()) {
      this.cancel()
    } else {
      const workspaceEditors = atom.workspace.getTextEditors().filter((editor) => editor.getPath())
      const activeEditor = atom.workspace.getActiveTextEditor()
      workspaceEditors.sort((a, b) => {
        if (a === activeEditor) {
          return 1
        } else if (b === activeEditor) {
          return -1
        } else {
          return (b.lastOpened || 1) - (a.lastOpened || 1)
        }
      })

      const uniqueWorkspacePaths = Array.from(new Set(workspaceEditors.map((editor) => editor.getPath())))
      const workspaceItems = this.projectRelativePathsForFilePaths(uniqueWorkspacePaths)

      let remoteItems
      if (this.teletype) {
        const remoteBuffers = await this.teletype.getRemoteBuffers()
        remoteItems = remoteBuffers.map((b) => {
          return {filePath: b.uri, label: b.label}
        })
      } else {
        remoteItems = []
      }

      const items = remoteItems.concat(workspaceItems)
      if (items.length > 0) {
        this.show()
        await this.setItems(items)
      }
    }
  }
}
<|endoftext|>