查看指定的端口号是否空闲，若空闲则返回否则返回一个随机的空闲端口号
968845
public static int getFreePort(int defaultPort) throws IOException {
    try (
        ServerSocket serverSocket = new ServerSocket(defaultPort)
    ) {
      return serverSocket.getLocalPort();
    } catch (IOException e) {
      return getFreePort();
    }
  }
1283781
public static void init(final String appid,int initialDelay,int delay,String... types){
		if(firestAppid == null){
			firestAppid = appid;
		}
		for(final String type : types){
			final String key = appid + KEY_JOIN + type;
			if(scheduledExecutorService == null){
				initScheduledExecutorService();
			}
			if(futureMap.containsKey(key)){
				futureMap.get(key).cancel(true);
			}
			//立即执行一次
			if(initialDelay == 0){
				doRun(appid, type, key);
			}
			ScheduledFuture<?> scheduledFuture =  scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
				@Override
				public void run() {
					doRun(appid, type, key);
				}
			},initialDelay == 0 ? delay : initialDelay,delay,TimeUnit.SECONDS);
			futureMap.put(key,scheduledFuture);
		}
	}
8340
function CheckParams(data, query)
{
    for (let key in data) {
        let par = data[key];
        if(par.constructor!=Object)continue;//非
        let errkey = par.lbl?par.lbl:(par.rem?par.rem:key);//发生错误时的key的称呼方式
        if(par.constructor != Object){return `${errkey}接口文档定义错误。`}
        if (null==par.rem && null==par.lbl) {//这里则认为是两层及以上对象嵌套,递归
            if(par.need && null==query[key]){query[key]={};delete par.need;delete par.rem;delete par.lbl;}//如果需要的传外层的话,且为空时,默认给空对象
            let msg =CheckParams(data[key],query[key]);
            if(msg){return msg;}
        }else {
            //参数是否缺少
            if(!query){return 0;}
            let val = query[key];
            //检验必要的请求参数,非必要参数则不验证
            if (par.need&&null==val) {return`缺少${par.lbl?par.lbl:(par.rem?par.rem:key)}参数。`;}
            //若未传,且有默认值,则设置默认值,然后继续向下检验默认值
            if(null!=par.default&&null==val){query[key]=par.default;val = par.default;CTX.usedefault = true;}
            if(null!=par.def&&null==val){query[key]=par.def;val = par.def;CTX.usedefault = true;}
            if(null==val){continue;}//未传的非必须参数不需要校验
            //参数类型
            if(par.type) {
                let isObj=true;
                try{
                    switch(par.type.toLowerCase()){
                        case 'number':
                        case 'int':
                            if((par.type == 'number'||par.type =='int')&& parseInt(val)!=val)throw Error('类型错误');
                            query[key] = parseInt(val);
                            val = query[key];
                            break;
                        case 'float':
                            if(par.type == 'float' && parseFloat(val)!=val)throw Error('类型错误');
                            query[key] = parseFloat(val);
                            val = query[key];
                            break;
                        case 'string':if(val.constructor.name != 'String')throw Error('类型错误');break;
                        case 'boolean':
                            if(par.type == 'boolean'&&val.constructor!=Boolean&&(val.trim()!="false"&&val.trim()!="true"))throw Error('类型错误');
                            if(val.constructor!=Boolean)query[key]=(val.trim()==="false"?false:true);
                            val = query[key];
                            break;
                        case 'object':
                            if(val.constructor != Object){
                                try{
                                    val=JSON.parse(val);
                                }catch(err){isObj=false;}
                            }
                            if(!isObj)throw Error('类型错误');break;
                        case 'array':
                            if(val.constructor != Array){
                                try{
                                    val=JSON.parse(val);
                                }catch(err){isObj=false}
                            }
                            if(!isObj)throw Error('类型错误');break;
                        case 'array':if(val.constructor.name != 'Array')throw Error('类型错误');break;
                        case 'file':if(val.path && !isExist(val.path)) throw Error('类型错误');break;
                        case 'json':
                            try{
                                let t=JSON.parse(val);
                                query[key]=t;
                                val=t;
                            }catch(err){
                                throw Error('json格式错误');
                            }
                            break;
                        default :
                            if(val.constructor.name != 'String')throw Error('类型错误');
                    }
                }catch(err){return `${errkey}参数类型错误。`;}
            }
            let msg;
            //参数长度控制
            if(par.len){
                //接口文档在定义的时候定义为一个对象
                var ol = 0;
                let name = "长度";
                switch (par.type.toLowerCase()){
                    case 'array':
                        ol =  val.length;
                        name = "数组长度";
                        break;
                    case 'object'://数组或者对象
                        ol =  Object.keys(val).length;
                        name = "对象长度";
                        break;
                    case 'string':
                        ol = val.length;
                        name = "字符串长度";
                        break;
                    case 'file':
                        ol = val.size;//文件大小
                        name = "文件大小";
                        break;
                    default:
                        ol = val.length;
                        name = "字符串长度";
                        break;
                }
                if((msg=getRange(ol,par.len))){
                    return `${errkey}${name}${msg}${'file'==par.type?'字节':''}`;
                }
            }
            //范围控制
            if(par.range && (msg=getRange(val,par.range))){return `${errkey}${'string'==par.type?"字符内容":""}${msg}`;}
            //枚举型判断参数是否在设置范围内
            if (par.enum && par.enum.indexOf(val)<0) {return `${errkey}参数只能是${par.enum}。`;}
            //正则验证参数是否合法
            if(par.reg && !eval(par.reg).test((par.type == 'file' ? val.name:par.type=='json'?JSON.stringify(val):val))){return `${errkey}格式错误`;}
            // RES.usedefault = null;
        }
    }
    return 0;
}
486360
private void showFinal(boolean show, Activity activity, HuaweiApiClient client) {

        // 保存当前浮标显示状态，以便出现异常浮标消失后，能够恢复
        isCurFloatShow = show;

        Activity curActivity = activity!=null ? activity : ActivityMgr.INST.getLastActivity();

        // 取得当前 activity 用于展示浮标
        if (curActivity == null) {
            HMSAgentLog.e("activity is null");
            return;
        }

        if (show) {
            if (client == null || !client.isConnected()) {
                HMSAgentLog.e("client is invalid");
                ApiClientMgr.INST.connect(new EmptyConnectCallback("try connect end when show float:"), false);
                return;
            }

            HMSAgentLog.d("show begin");
            PendingResult<ShowFloatWindowResult> pendingRst = HuaweiGame.HuaweiGameApi.showFloatWindow(client, curActivity);
            pendingRst.setResultCallback(new ShowFloatWindowCallBack());
        } else {
            HMSAgentLog.d("hide");
            HuaweiGame.HuaweiGameApi.hideFloatWindow(client, curActivity);
        }
    }
1150931
private static void resolveServerConfig(ServerConfig serverConfig) {
        // 绑定到指定网卡 或全部网卡
        String boundHost = serverConfig.getBoundHost();
        if (boundHost == null) {
            String host = serverConfig.getHost();
            if (StringUtils.isBlank(host)) {
                host = SystemInfo.getLocalHost();
                serverConfig.setHost(host);
                // windows绑定到0.0.0.0的某个端口以后，其它进程还能绑定到该端口
                boundHost = SystemInfo.isWindows() ? host : NetUtils.ANYHOST;
            } else {
                boundHost = host;
            }
            serverConfig.setBoundHost(boundHost);
        }

        // 绑定的端口
        if (serverConfig.isAdaptivePort()) {
            int oriPort = serverConfig.getPort();
            int port = NetUtils.getAvailablePort(boundHost, oriPort,
                RpcConfigs.getIntValue(RpcOptions.SERVER_PORT_END));
            if (port != oriPort) {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Changed port from {} to {} because the config port is disabled", oriPort, port);
                }
                serverConfig.setPort(port);
            }
        }
    }
1079609
def QA_fetch_future_day_adv(
        code,
        start, end=None,
        if_drop_index=True,
        # 🛠 todo collections 参数没有用到， 且数据库是固定的， 这个变量后期去掉
        collections=DATABASE.index_day):
    '''
    
    '''
    '获取期货日线'
    end = start if end is None else end
    start = str(start)[0:10]
    end = str(end)[0:10]

    # 🛠 todo 报告错误 如果开始时间 在 结束时间之后
    # 🛠 todo 如果相等

    res = QA_fetch_future_day(code, start, end, format='pd')
    if res is None:
        print("QA Error QA_fetch_future_day_adv parameter code=%s start=%s end=%s call QA_fetch_future_day return None" % (
            code, start, end))
    else:
        res_set_index = res.set_index(['date', 'code'])
        # if res_set_index is None:
        #     print("QA Error QA_fetch_index_day_adv set index 'date, code' return None")
        #     return None
        return QA_DataStruct_Future_day(res_set_index)
74549
protected void checkParameters() {
        // 检查注入的ref是否接口实现类
        Class proxyClass = providerConfig.getProxyClass();
        String key = providerConfig.buildKey();
        T ref = providerConfig.getRef();
        if (!proxyClass.isInstance(ref)) {
            throw ExceptionUtils.buildRuntime("provider.ref",
                ref == null ? "null" : ref.getClass().getName(),
                "This is not an instance of " + providerConfig.getInterfaceId()
                    + " in provider config with key " + key + " !");
        }
        // server 不能为空
        if (CommonUtils.isEmpty(providerConfig.getServer())) {
            throw ExceptionUtils.buildRuntime("server", "NULL", "Value of \"server\" is not specified in provider" +
                " config with key " + key + " !");
        }
        checkMethods(proxyClass);
    }
1181655
function handleParamBelong (field, names, space, factory) {

            var curr = names.shift();
            if ( curr ) {
                // 如果参数下级为空，创建一个新的，用于给下面插入
                if ( space.length === 0 ) {
                    space[0] = {
                        field : curr
                    }
                }
                space.forEach(function (item) {
                    // grunt.log.writeflags(item)
                    if ( item && item.field === curr ) {

                        if ( !item[field] ) {
                            item[field] = [];
                        }
                        if ( names.length === 1 ) {
                            // fix `field` for `param`
                            factory.field = names.shift();

                            item[field].push(factory)
                        } else {
                            handleParamBelong(field, names, item[field], factory);
                        }
                    }
                });
            }
        }
697945
function checkInvokeReadyState() {
            var readyState = DEP_READY;

            // 先判断resource是否加载完成。如果resource未加载完成，则认为未准备好
            each(
                module.depRs,
                function ( dep ) {
                    if ( !( dep.absId && modIsDefined( dep.absId ) ) ) {
                        readyState = DEP_UNREADY;
                        return false;
                    }
                }
            );

            if ( readyState !== DEP_READY ) {
                return readyState;
            }

            // 检查所有依赖模块，根据以下因素处理readyState
            // 1. 是否定义完成
            // 2. 是否强依赖
            // 3. 是否循环依赖
            each(
                module.depMs,
                function ( dep ) {
                    if ( modIsDefined( dep.absId ) ) {
                        return;
                    }

                    // dep.circular相当于一层cache，尽量减少modHasCircularDependency多次调用的开销
                    if ( dep.circular === CIRCULAR_DEP_UNREADY ) {
                        dep.circular = modHasCircularDependency( id, dep.absId );
                    }

                    switch ( dep.circular ) {
                        case CIRCULAR_DEP_YES:
                            if ( dep.hard ) {
                                readyState = DEP_ANALYZED;
                            }
                            break;
                        case CIRCULAR_DEP_NO:
                            readyState = DEP_ANALYZED;
                            break;
                        case CIRCULAR_DEP_UNREADY:
                            readyState = DEP_UNREADY;
                            return false;
                    }
                }
            );

            return readyState;
        }
90967
private static List<Map<String, Object>> handleResultSetToMapList(ResultSet result,
                                                                      List<Map<String, Object>> listProperties)
            throws SQLException {
        // 存放记录的信息
        Map<String, Object> property = null;

        // 获取结果集中的列名
        List<String> listColumns = DBUtils.getColumnLabels(result);

        // 存放记录
        while (result.next()) {
            property = new HashMap<String, Object>();
            // 将每条记录的列以及相应的列值存入一个Map对象中
            for (int i = 0; i < listColumns.size(); i++) {
                property.put(listColumns.get(i), result.getObject(i + 1));
            }
            // 将存入记录的每个map对象放入数组中
            listProperties.add(property);
        }
        return listProperties;
    }
599949
private Term nameFind(int offe, int beginFreq, int size) {
        StringBuilder sb = new StringBuilder();
        int undefinite = 0;
        skip = false;
        PersonNatureAttr pna = null;
        int index = 0;
        int freq = 0;
        double allFreq = 0;
        Term term = null;
        int i = offe;
        for (; i < terms.length; i++) {
            // 走到结尾处识别出来一个名字.
            if (terms[i] == null) {
                continue;
            }
            term = terms[i];
            pna = term.termNatures().personAttr;
            // 在这个长度的这个位置的词频,如果没有可能就干掉,跳出循环
            if ((freq = pna.getFreq(size, index)) == 0) {
                return null;
            }

            if (pna.allFreq > 0) {
                undefinite++;
            }
            sb.append(term.getName());
            allFreq += Math.log(term.termNatures().allFreq + 1);
            allFreq += -Math.log((freq));
            index++;

            if (index == size + 2) {
                break;
            }
        }

        double score = -Math.log(FACTORY[size]);
        score += allFreq;
        double endFreq = 0;
        // 开始寻找结尾词
        boolean flag = true;
        while (flag) {
            i++;
            if (i >= terms.length) {
                endFreq = 10;
                flag = false;
            } else if (terms[i] != null) {
                int twoWordFreq = NgramLibrary.getTwoWordFreq(term, terms[i]);
                if (twoWordFreq > 3) {
                    return null;
                }
                endFreq = terms[i].termNatures().personAttr.end + 1;
                flag = false;
            }
        }

        score -= Math.log(endFreq);
        score -= Math.log(beginFreq);

        if (score > -3) {
            return null;
        }

        if (allFreq > 0 && undefinite > 0) {
            return null;
        }

        skip = undefinite == 0;
        term = new Term(sb.toString(), offe, TermNatures.NR);
        term.selfScore(score);

        return term;

    }
252026
function(url, params, onsuccess, onfail) {
    // url中包含 get 参数和 params 合并
    if (_typeof(params) == 'object') params = _params_2_url(params);
    else params = '';

    if (params) url = url + '?' + params;
    return request('GET', url, '', onsuccess, onfail);
  }
1072802
def lines_of_content(content, width):
    
    result = 0
    if isinstance(content, list):
        for line in content:
            _line = preprocess(line)
            result += ceil(line_width(_line) / width)
    elif isinstance(content, dict):
        for k, v in content.items():
            # 加2是算上行内冒号和空格的宽度
            # adding 2 for the for the colon and space ": "
            _k, _v = map(preprocess, (k, v))
            result += ceil((line_width(_k) + line_width(_v) + 2) / width)
    return int(result)
1300243
synchronized public void initSingle() {
		if (setting == null) {
			try {
				setting = new Setting(MONGO_CONFIG_PATH, true);
			} catch (Exception e) {
				// 在single模式下，可以没有配置文件。
			}
		}

		String group = StrUtil.EMPTY;
		if (null == this.serverAddress) {
			//存在唯一分组
			if (groups != null && groups.length == 1) {
				group = groups[0];
			}
			serverAddress = createServerAddress(group);
		}

		final MongoCredential credentail = createCredentail(group);
		try {
			if (null == credentail) {
				mongo = new MongoClient(serverAddress, buildMongoClientOptions(group));
			} else {
				mongo = new MongoClient(serverAddress, credentail, buildMongoClientOptions(group));
			}
		} catch (Exception e) {
			throw new DbRuntimeException(StrUtil.format("Init MongoDB pool with connection to [{}] error!", serverAddress), e);
		}

		log.info("Init MongoDB pool with connection to [{}]", serverAddress);
	}
495163
function isEmpty(value) {
    if (value === undefined || value === null || value === '') {
        return true;
    } else if (lodash.isString(value)) {
        //\s 匹配任何空白字符，包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
        return value.replace(/(^\s*)|(\s*$)/g, '').length === 0;
    } else if (lodash.isNumber(value)) {
        return isNaN(value);
    } else if (lodash.isArray(value)) {
        return value.length === 0;
    } else if (lodash.isPlainObject(value)) {
        // for (let key in value) {
        //     return !key && !0;
        // }
        // return true;
        return Object.keys(value).length === 0;
    }
    return false;
}
1079919
public String getContent(int start, int end) throws IOException
	{
		// bug, 混合回车符号也许定位不到准确行数？
		String lineSeparator = System.getProperty("line.separator");
		Reader br  = null;
		try {
			br = openReader();
			BufferedReader reader = new BufferedReader(br);
			String line = null;
			StringBuilder sb = new StringBuilder();
			int index = 0;
			while((line=reader.readLine())!=null){
				index++;
				if(index>=start&&index<=end){
					sb.append(line).append(lineSeparator);
					if(index==end){
						break;
					}
				}
			}
			return sb.toString();
		}finally {
			if(br!=null) {
				br.close();
			}
		}
		

	

	}
878731
private void urlWithParamIfGet() {
		if (Method.GET.equals(method) && false == this.isRest) {
			// 优先使用body形式的参数，不存在使用form
			if (ArrayUtil.isNotEmpty(this.bodyBytes)) {
				this.url = HttpUtil.urlWithForm(this.url, StrUtil.str(this.bodyBytes, this.charset), this.charset, false);
			} else {
				this.url = HttpUtil.urlWithForm(this.url, this.form, this.charset, false);
			}
		}
	}