获取resource中出现的类型 //louis
348949
public function getRescTypesInUse($key=0)
	{
		$types = Resource::where('resources.show', 0)
		             ->rightJoin('config', 'resources.type', '=', 'config.id')
		             ->groupBy('resources.type')
		             ->distinct()
		             ->select('resources.type', 'config.name as typeName')
		             ->get();

		//$arr = [];
		$key === 1 ? $arr = [] : $arr = ['0'=>'不限类型'];

		if(count($types)){
			foreach ($types as $t) {
				$arr = array_add($arr, $t->type, $t->typeName);
			}
		}
		return $arr;
	}
798765
function getlist(fpath, prefix) {
    try {
      folders = fs.readdirSync(fpath);
    } catch (e) {
      return;
    }

    prefix = prefix || '';

    _.each(folders, function(f) {
      var p;
      npath = path.join(fpath, f);

      // 如果当前f是文件夹，则添加代表文件夹的分隔符，否则判断文件名是否匹配正则，不匹配则不扔进数组
      if (fs.existsSync(npath) && fs.lstatSync(npath).isDirectory()) {

        f += '/';

        // 如果要获取所有文件则递归获取下一层目录的文件
        if (hasGrep) getlist(npath, prefix + f);

      } else if (f.match(re)) {

        p = re ? RegExp.$1 : f;

      } else {
        return;
      }

      // 如果grepKey为string则匹配文件/文件夹名
      if (hasGrep && f.indexOf(grepKey) === -1) return;

      urlList.push({
        name: f,
        path: prefix + (p || f)
      });
    });
  }
1293941
function getPath(tpl, config) {
    const defaultExt = config.extension;
    const tplAbsPath = path.resolve(config.root, tpl);

    if (TPL_MATCH[tplAbsPath]) return TPL_MATCH[tplAbsPath];

    const tplExt = path.extname(tpl);

    // 如果有后缀名，且等于默认后缀名，则直接返回
    if (tplExt && tplExt === `.${defaultExt}`) {
      return TPL_MATCH[tplAbsPath] = tplAbsPath;
    }

    try {
      let stats = fs.statSync(tplAbsPath);
      // 如果当前是一个文件目录，则返回： 文件目录 + index.html
      if (stats.isDirectory()) {
        return TPL_MATCH[tplAbsPath] = path.resolve(tplAbsPath, `index.${defaultExt}`)
      }

      // 否则是一个文件路径，直接返回 tplAbsPath
      return TPL_MATCH[tplAbsPath] = tplAbsPath

    } catch (err) {
      // 进入报错，则说明文件找不到，直接返回自动添加文件名的情况
      return TPL_MATCH[tplAbsPath] = `${tplAbsPath}.${defaultExt}`
    }

  }
1146185
function () {

        var that = this;
        var base = this.base;
        var $ = this.$;
        var files = [];


        $('link[rel=stylesheet]').each(function () {

            var $this = $(this);
            var cssFile;
            var href = $this.attr('href');

            cssFile = utils.resolve(base, href);
            cssFile = getUrl(cssFile);

            // 注意：为空也得放进去，保持与 link 标签一一对应
            files.push(cssFile);
        });


        // 转换 file 地址
        // 执行顺序：ignore > map > normalize
        function getUrl (file) {

            if (!that.ignore(file)) {
                file = that.map(file);
                file = utils.normalize(file);
                return file;
            }
        }


        if (this.options.debug) {
            console.log('');
            console.log('[DEBUG]', 'HtmlParser#getCssFiles', this.file);
            console.log(files);
        }


        return files;
    }
1225581
function _TPL(ctx)
{
    let method = ctx.method;
    let route = url.parse(ctx.url).pathname.substr(1);
    isDebug && console.log('route',route,ctx.url)
    let data = null;
    let routeName ;//路由名字

    if(((itFace[route] && itFace[route].method == method) || 
        (itFace[`${route}_${method}`] && itFace[`${route}_${method}`].method == method)) 
        && !isDebug){
        if(itFace[route] && itFace[route].method == method){
            routeName = route;
        }
        if(itFace[`${route}_${method}`] && itFace[`${route}_${method}`].method == method){
            routeName = `${route}_${method}`;
        }
        data = itFace[`${routeName}`];
    }else{
        //读取接口文档,并缓存起来
        // console.log('aaaa',`${interFaceRoot}${`${route}_${method}`}.json`)
        if(isExist(path.join(`${interFaceRoot}${route}.json`))){
            data = fs.readFileSync(path.join(`${interFaceRoot}${route}.json`), 'utf-8');
            try {
                data = eval('('+data+')');
            }catch (err){
                return {TPL:"接口文档定义错误!"}
            }
            //如果请求方法对不上,则清空现有数据
            if(!data || data.method != method){//
                data = null;
            }else {
                itFace[route] = data;
                routeName = route;
            }
        }
        //如果本文件不存在,则通过匹配文件名加上请求参数
        if(!data && isExist(path.join(`${interFaceRoot}${`${route}_${method}`}.json`))){
            data = fs.readFileSync(path.join(`${interFaceRoot}${`${route}_${method}`}.json`), 'utf-8');
            try {
                data = eval('('+data+')');
            }catch (err){
                data = null;
            }
            if(!data || data.method != method){//
                data = null;
            }else {
                itFace[route] = data;
                routeName = route;
            }
        }
        if(data){
            //处理数据中,含有的特殊字符
            let map={"{}":"$B","{S}":"$S","{U}":"$U","{X}":"$X"};
            if(data.pretreat)
            {
                if(String==data.pretreat.constructor) data.pretreat=[data.pretreat];
                data.pretreat=data.pretreat.join(";").replace(/{[SUX]?}/g,function($0)
                {
                    return map[$0];
                });
            }
            if(data.grant)
                data.grant=_formatCnd(data.grant,map);
            if(data.check)
                data.check=_formatCnd(data.check,map);
        }
    }
    if(data){
        if(data.params){
            for(let key in data.params){
                if('file'==data.params[key].type) data.hasFile=1;
            }
        }
    }
    return {TPL:data,routeName:routeName}
}
1272453
function getBaesVsersion(dir, callBack) {
        fs.readdir(`${dir}/`, (err, files) => {
            let dirList = [],
                baseVersion;
            if (err) {
                console.log('第一次部署中...');
                fs.mkdir(dir, () => {
                    callBack([1, 1, 1]);
                });
            } else {
                if (files.length == 0) {
                    files = ['1.1.1'];
                }
                console.log('部署目标已存在，正在更新中...');
                files.forEach((v)=> {
                    let intV = v.replace(/\./g, '');
                    if (!!parseInt(intV)) {
                        dirList.push(intV);
                    }
                });
                baseVersion = Math.max.apply(null, dirList).toString().split('');
                callBack(baseVersion);
            }
        });
    }
634270
function getVerbHelp(verb, output) {
    let targets = [];
    let options = {
        head: `Available resources for ${chalk.bold(verb)}:`,
        table: []
    };

    // special verbs

    let sections = [];

    switch (verb) {
    case "query":
        output.write(chalk.cyan.bold("luis query --query <querytext> [--appId | --endpoint | --nologging | --region | --spellCheck | --staging | --subscriptionKey | --timezoneOffset | --timing |  --verbose]\n\n"))
        options.table.push([chalk.cyan.bold("--query <query>"), "Query to analyze with LUIS prediction."]);
        options.table.push([chalk.cyan.bold("--endpoint <endpointUrl>"), "Endpoint to use for query like https://westus.api.cognitive.microsoft.com/luis/v2.0/apps, overrides region."]);
        options.table.push([chalk.cyan.bold("--nologging"), "Turn off query logging in LUIS."]);
        options.table.push([chalk.cyan.bold("--spellCheck <key>"), "Check spelling using your Bing spelling key."]);
        options.table.push([chalk.cyan.bold("--staging"), "Use the staging environtment rather than production."]);
        options.table.push([chalk.cyan.bold("--timezoneOffset <minutes>"), "Specify the timezone offset in minutes used for resolving data time."]);
        options.table.push([chalk.cyan.bold("--timing [iterations]"), "Perform timings on query, default is 5 iterations."]);
        options.table.push([chalk.cyan.bold("--verbose"), "Include scores for all intents."]);
        sections.push(options);
        sections.push(configSection);
        sections.push(globalArgs);
        return sections;

    case "set":
        output.write(chalk.cyan.bold("luis set <appIdOrName> [--appId|--versionId|--authoringKey|--endpoint] <value>\n\n"))
        options.table.push([chalk.cyan.bold("<appIdOrName>"), "change the active application by looking it up by name or id"]);
        options.table.push([chalk.cyan.bold("--appId <appId>"), "change the active application id "]);
        options.table.push([chalk.cyan.bold("--versionId <version>"), "change the active version id "]);
        options.table.push([chalk.cyan.bold("--authoringKey <authoringKey>"), "change the active authoringKey◘"]);
        options.table.push([chalk.cyan.bold("--endpoint <endpointUrl>"), "change the active endpointBasePath url"]);
        sections.push(options);
        sections.push(configSection);
        sections.push(globalArgs);
        return sections;
    }

    for (let iOperation in operations) {
        let operation = operations[iOperation];
        if (operation.methodAlias == verb) {
            let target = operation.target[0];
            if (targets.indexOf(target) < 0) {
                targets.push(target);
            }
        }
    }


    if (targets.length == 0)
        return getGeneralHelpContents(output);

    targets.sort();
    for (let target of targets) {
        options.table.push([chalk.cyan.bold(target), '']);
    }
    sections.push(options);
    sections.push(configSection);
    sections.push(globalArgs);
    return sections;
}
369713
function parseDocToTree(doc, defaultTitle) {
  // save the parsed tree
  const tree = [];
  const lines = doc.split('\n');
  let line, m;

  // 保存一个文档区域
  let section = null;
  let parentSection = null;
  // if in a ``` block
  let inBlock = false;

  // little trick，如果第一行不是 #，则增加一个 #
  if (!/^#(?!#)/.test(lines[0])) {
    lines.unshift('# ' + defaultTitle);
  }

  while ((line = lines.shift()) !== undefined) {
    m = line && line.match(/^(#+)(?!#)(.*)$/);

    if (!inBlock && m && m.length == 3) {
      section = {
        title: m[2].trim(),
        level: m[1].length,
        parent: null,
        children: []
      };

      while (parentSection && parentSection.level >= section.level) {
        parentSection = parentSection.parent;
      }

      if (parentSection) {
        section.parent = parentSection;
        parentSection.children.push(section);
        parentSection = section;
      } else {
        tree.push(section);
        parentSection = section;
      }
    } else if (section) {
      if (line.indexOf('```') === 0) {
        inBlock = !inBlock;
      }
      section.children.push(line);
    } else {
      throw new Error(`NOT VALID LINE: ${line}`);
    }
  }

  return tree;
}
690310
function (selector) {

        var chars = '';
        var that = this;


        // 将多个语句拆开进行查询，避免其中有失败导致所有规则失效
        if (selector.indexOf(',') !== -1) {
            
            selector.split(',').forEach(function (selector) {
                chars += that.querySelectorChars(selector).join('');
            });

            return chars.split('');
        }


        var $elem;
        var $ = this.$;
        var RE_DPSEUDOS = /\:(link|visited|target|active|focus|hover|checked|disabled|enabled|selected|lang\(([-\w]{2,})\)|not\(([^()]*|.*)\))?(.*)/i;


        // 剔除状态伪类
        selector = selector.replace(RE_DPSEUDOS, '');


        // 使用选择器查找节点
        try {
            $elem = $(selector);
        } catch (e) {
            // 1. 包含 :before \ :after 等不支持的伪类
            // 2. 非法语句
            return [];
        }


        // 查找文本节点
        $elem.each(function () {
            chars += $(this).text();
        });


        chars = chars.split('');


        if (this.options.debug) {
            console.log('');
            console.log('[DEBUG]', 'HtmlParser#querySelectorChars', selector, this.file);
            console.log(chars.join(''));
        }


        return chars;
    }
1118520
function saveByFilesPath(readFilesPath, saveFilesPath, program, showLogs) {
  if (!readFilesPath || !saveFilesPath || !program) {
    console.error(chalk.red('参数缺漏！'));
    process.exit(1);
    return;
  }
  let { i18n, breadcrumb, all } = program;
  readFilesPath.forEach((v, k) => {
    //兼容windwos平台路径
    v = v.replace(/\\/g, '/');
    var contents = fs.readFileSync(v, {
      encoding: 'utf-8',
    });
    if (this.pageName) {
      //处理viem template 中的替换，根据this.pageName来判断
      contents = contents.replace(/\${pageName}/g, this.pageName);
      var pageNameSplit = this.pageName.split('-');
      pageNameSplit = pageNameSplit.map(v => {
        v = util.toUpperCaseByPosition(v, 0, 1);
        return v;
      });
      var pageNameCombine = pageNameSplit.join('');
      contents = contents.replace(
        /\${pageNameFirstLetter}/g,
        util.toUpperCaseByPosition(pageNameCombine, 0, 1)
      );
    }
    if (all) {
      //启用全部特性功能
      contents = this.removeTag(contents, '.*');
    } else {
      if (i18n) {
        //启用i18n功能
        contents = this.removeTag(contents, 'Locale');
      } else {
        //移除this.t(xxx)，不移除会报错
        var m = contents.match(/\.t\(["'](.*)["']\)/g);
        m &&
          m.forEach(v2 => {
            var t = v2.split('"');
            if (!t[1]) {
              t = v2.split("'");
            }
            contents = contents.replace(`this.t('${t[1]}')`, `'${t[1]}'`);
            contents = contents.replace(`this.t("${t[1]}")`, `'${t[1]}'`);
            contents = contents.replace(
              new RegExp(`{.*'${t[1]}'.*}`, 'g'),
              t[1]
            );
          });
      }
      if (breadcrumb) {
        //启用面包屑功能
        contents = this.removeTag(contents, 'BreadCrumb');
      }
    }
    //统一移除自定义tag（//≤--begin），包括tag内容
    contents = this.removeTagContents(contents, '.*');
    var filePahtSplit = v.split('/');
    var fileName = filePahtSplit[filePahtSplit.length - 1];
    var savePath = path.resolve(saveFilesPath[k]);
    fs.ensureFileSync(savePath);
    fs.writeFileSync(savePath, contents, {
      mode: 0o777,
    });
    if (showLogs) {
      console.log(chalk.green(fileName + ' is saved at:'));
      console.log(chalk.cyan(savePath));
    }
  });
}
209341
function () {
            var reg = new RegExp(domUtils.fillChar, 'g');
            //取出来的空格会有c2a0会变成乱码，处理这种情况\u00a0
            return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
        }
455893
function (host, styles, attrs) {
        attrs || (attrs = 'rel="stylesheet"');
        attrs = ' ' + attrs.trim();
        var result = [];
        styles.forEach(function (file) {
            var content = file.getContent().replace(/(^\n+?|\n+$)/g,'').trim();
            if(content === ''){
                return;
            }
            file._md5 = undefined; // 强制清空，重新计算

            var uri = file.getUrl();
            var msg = {
                target: uri,
                file: host,
                ret: uri
            };

            /**
             * @event plugin:relative:fetch 获取相对路径的事件
             */
            fis.emit('plugin:relative:fetch', msg);

            result.push('<link href="' + msg.ret + '"' + attrs + '>');
        });
        return result.join('\n');
    }
1041612
function (resourcePath, ext) {
            var self = this;
            var staticPath;
            if (_.isEmpty(self.map)) {
                // map 为空时, 直接拼接路径, 并确保文件存在
                staticPath = FileLoader.matchFile(path.join(self.staticPath, resourcePath) + ext);
                if (staticPath) {
                    staticPath = staticPath.substr(staticPath.indexOf(self.staticFolder));
                }
            } else {
                var resourceKey = resourcePath + ext;
                var result = self.map['res'] && self.map['res'][resourceKey];
                staticPath = result && result.uri;
            }
            return staticPath;
        }
569714
function(results) {
    /*
    将所有集合求其交集; 第一个集合是最小的数组
    */
    results.sort(function(a, b) {
      a.length - b.length
    })

    var firstArr  = results[0].length
      , objectIDs = []

    for (var i = 0; i < results[0].length; i++) {
      var item = results[0][i]
        , flag = true

      for (var j = 1; j < results.length; j++) {
        if (results[j].indexOf(item) < 0) {
          flag = false
          j = results.length
        }
      }

      flag && objectIDs.push(item)
    }

    getFromIDs(objectIDs)
  }
641713
function(cb) {
  if (lithe.publicpath && publicDeps.length) {
    var pDeps = [],
        fDeps = [];

    // 汇总public依赖的依赖包

    forEach(publicDeps, function (deps) {
      values(lithe.config.publicdeps[deps]).forEach(function(rdeps) {
        if (keys(lithe.config.publicdeps).indexOf(rdeps) !== -1) {
          publicDeps.push(rdeps);
        }
      });
    });

    // 如果依赖没有js后缀,就加上js后缀然后汇总
    // 汇总结果有js后缀的和没有js后缀的,用户在config配置的时候有可能有js后缀,也有可能
    // 不写js后缀

    forEach(unique(publicDeps), function(deps){
      if (deps.lastIndexOf(jsExt) < 0){
        pDeps.push(deps);
        pDeps.push(deps + jsExt);
      }else {
        pDeps.push(deps);
      }
    });

    // 获取public依赖的真实路径

    forEach(pDeps, function(deps){
      if (lithe.config.publicdeps[deps]) {
        fDeps.push(keys(lithe.config.publicdeps[deps])[0]);
      }
    });

    var pm = unique(fDeps).join(",");
    var nginxPublic = lithe.publicpath + "??" + pm;
    forEach(publicDeps,function(mod){
      lithe.get(createUrls(mod)[0]);
    });
    getscript(nginxPublic, cb);
  }else{
    cb();
  }
}
418635
function listDevices() {
    return getDevice()
    .then(device => {
        console.log(`Device: ${device.id}`);
        return device.listResources();
    })
    .then(resources => {
        resources.forEach(resource => {
            resource.getValue()
            .then(value => {
                console.log(`\t└\x1b[1m${resource.path}\x1b[0m: ${value}`);
            })
            .catch(error => {
                console.log(`\t└\x1b[1m${resource.path}\x1b[0m: Error: ${error.message}`);
            });
        });
    });
}
851807
function toUrl( source ) {
        // 分离 模块标识 和 .extension
        var extReg = /(\.[a-z0-9]+)$/i;
        var queryReg = /(\?[^#]*)$/;
        var extname = '';
        var id = source;
        var query = '';

        if ( queryReg.test( source ) ) {
            query = RegExp.$1;
            source = source.replace( queryReg, '' );
        }

        if ( extReg.test( source ) ) {
            extname = RegExp.$1;
            id = source.replace( extReg, '' );
        }

        var url = id;

        // paths处理和匹配
        var isPathMap;
        indexRetrieve( id, pathsIndex, function ( value, key ) {
            url = url.replace( key, value );
            isPathMap = 1;
        } );

        // packages处理和匹配
        if ( !isPathMap ) {
            indexRetrieve(
                id,
                packagesIndex,
                function ( value, key, item ) {
                    url = url.replace( item.name, item.location );
                }
            );
        }

        // 相对路径时，附加baseUrl
        if ( !/^([a-z]{2,10}:\/)?\//i.test( url ) ) {
            url = requireConf.baseUrl + url;
        }

        // 附加 .extension 和 query
        url += extname + query;

        // urlArgs处理和匹配
        var isUrlArgsAppended;
        indexRetrieve( id, urlArgsIndex, function ( value ) {
            appendUrlArgs( value );
        } );
        defaultUrlArgs && appendUrlArgs( defaultUrlArgs );

        /**
         * 为url附加urlArgs
         *
         * @inner
         * @param {string} args urlArgs串
         */
        function appendUrlArgs( args ) {
            if ( !isUrlArgsAppended ) {
                url += ( url.indexOf( '?' ) > 0 ? '&' : '?' ) + args;
                isUrlArgsAppended = 1;
            }
        }

        return url;
    }