• 通用工具类


    文章目录

    通用工具类

    • 不涉及任何业务的工具类。
    • 直接复制就可以用。
    • 由群里大家提出来的需求整出来。
    • 可以使用Ctrl+F来进行关键词查找。

    重要:希望可以和大家共建工具类,有想提供工具方法或共建的可以留言。

    分享,开源,利他,创造价值,分享学习,一起成长,相伴前行。

    字符串相关 StringUtils

    获取当前系统字符串最大长度

    ClassMethod GetStringMaxLength() As %Integer
    {
    	q $system.SYS.MaxLocalLength()
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.StringUtils).GetStringMaxLength()
    3641144
    
    • 1
    • 2

    判断字符串是否全是中文,字符串中有一个非中文即返回$$$NO

    ClassMethod IsChinese(str As %String) As %Boolean
    {
    	if 1 = $match(str,"(?x)[\u4e00-\u9fa5]*#中文正则表达式") {
    		q $$$YES
    	} else {
    		q $$$NO
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    ClassMethod IsChineseChar(str As %String) As %Boolean
    {
    	s asc = $a(str)
    	if (asc < $zhex("9fa5"))&&(asc > $zhex("4e00")){
    		q $$$YES
    	} else {
    		q $$$NO
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    USER> w ##class(Util.StringUtils).IsChinese("姚鑫")
    1
    USER> w ##class(Util.StringUtils).IsChinese("姚鑫+")
    0
    
    • 1
    • 2
    • 3
    • 4

    去除字符串首尾空格,中间保留

    ClassMethod Trim(str As %String) As %String
    {
       q $e(str, $locate(str, "[^\s]"), $locate(str, "\s*$") - 1)
    }
    
    • 1
    • 2
    • 3
    • 4
    ClassMethod Trim1(str As %String) As %String [ Language = basic ]
    {
    	return Trim(str)
    }
    
    • 1
    • 2
    • 3
    • 4
    ClassMethod Trim2(str As %String) As %String
    {
    	q $zstrip(str, "<>", " ")
    }
    
    • 1
    • 2
    • 3
    • 4
    ClassMethod Trim3(str As %String) As %String
    {
    	s target = ""
    	&sql(
    		select TRIM(both ' ' from :str) into :target
    	)
    	q target
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    USER>w ##class(Util.StringUtils).Trim("    姚    鑫    ")
    姚    鑫
    USER>w ##class(Util.StringUtils).Trim1("    姚    鑫    ")
    姚    鑫
    USER>w ##class(Util.StringUtils).Trim2("    姚    鑫    ")
    姚    鑫
    USER>w ##class(Util.StringUtils).Trim3("    姚    鑫    ")
    姚    鑫
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    删除字符串中空格,数组方式

    ClassMethod DeleteSpace(str As %String) As %String
    {
      	s str = $lts($lfs(str," "),"")
    	q str
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.StringUtils).DeleteSpace("    姚    鑫    ")
    姚鑫
    
    • 1
    • 2

    高效重复字符串

    ClassMethod Repeat(target As %String, num As %Integer) As %String
    {
    	s str = ""
      	s $p(str, target, num) = target
      	q str
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>w ##class(Util.StringUtils).Repeat("yx",5)
    yxyxyxyxyx
    
    • 1
    • 2

    查找字符串中是否包含某个目标字符串

    ClassMethod IsContain(str As %String, target As %String, del As %String = "^") As %Boolean
    {
    	s len = $l(str, del)
    	s ret = $$$NO
    	for i = 1 : 1 : len {
    		q:ret
    		s sub = $p(str, del, i)
    		s:(sub = target) ret = $$$YES
    	}
    	q ret
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    ClassMethod IsContain1(str As %String, target As %String, del As %String = "^") As %Boolean
    {
    	s lb = $lfs(str, del)
    	q:($lf(lb, target)) $$$YES
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>w ##class(Util.StringUtils).IsContain("1,11,222,333","1",",")
    1
    USER>w ##class(Util.StringUtils).IsContain1("1,11,222,333","11",",")
    1
    
    • 1
    • 2
    • 3
    • 4

    匹配字符串前缀

    ClassMethod PrefixMatch(str As %String, target As %String) As %Boolean
    {
    	if ($locate(str, "^"_target) > 0){
    		q $$$YES
    	}
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##class(Util.StringUtils).PrefixMatch("1123*456xzc","123*")
    0
    USER>w ##class(Util.StringUtils).PrefixMatch("1123*456xzc","1123*")
    1
    
    • 1
    • 2
    • 3
    • 4

    匹配字符串后缀

    ClassMethod SuffixMatch(str As %String, target As %String) As %Boolean
    {
    	if ($locate(str, target_"$") > 0){
    		q $$$YES
    	}
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##class(Util.StringUtils).SuffixMatch("1123*456xzc","zxc")
    0
    USER>w ##class(Util.StringUtils).SuffixMatch("1123*456xzc","xzc")
    1
    
    • 1
    • 2
    • 3
    • 4

    判断字符串变量类型

    ClassMethod GetTypeOf(str) As %String
    {
    	q [(str)].%GetTypeOf(0)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.StringUtils).GetTypeOf([])
    array
    USER>w ##class(Util.StringUtils).GetTypeOf({})
    object
    USER>w ##class(Util.StringUtils).GetTypeOf("0")
    string
    USER>w ##class(Util.StringUtils).GetTypeOf(.12)
    number
    USER>w ##class(Util.StringUtils).GetTypeOf(".12")
    string
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    验证身份证

    ClassMethod IsIdentityCard(str As %String) As %Boolean
    {
    	if 1 = $match(str,"(?x)^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$*#18位身份证正则表达式") {
    		q $$$YES
    	} else {
    		q $$$NO
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    USER>w ##class(Util.StringUtils).IsIdentityCard("11111119111111111X")
    1
    USER>w ##class(Util.StringUtils).IsIdentityCard("11111119111111111a")
    0
    
    • 1
    • 2
    • 3
    • 4

    只保留汉字

    ClassMethod RemoveLetter(str As %String) As %String
    {
    	s str = $zstrip(str, "*ANP")
    	q str
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER> w ##class(Util.StringUtils).RemoveLetter("2李4lll")
    李
    USER>w ##class(Util.StringUtils).RemoveLetter("hello world 欢迎世界")
    欢迎世界
    
    • 1
    • 2
    • 3
    • 4

    获取字符串中的数字

    ClassMethod GetStringOfNumber(str As %String) As %String
    {
    	s str = $zstrip(str, "*E'N")
    	q str
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.StringUtils).GetStringOfNumber("AS1DAS姚鑫1234511A2S")
    112345112
    
    • 1
    • 2

    根据十六进制转汉字

    ClassMethod UnicodeToString(unicode As %String) As %Boolean
    {
    	s ascii = $zhex(unicode)
    	q $c(ascii)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.StringUtils).UnicodeToString("59da")
    • 1
    • 2

    汉字转换拼音

    • 需要导入^pinyinGlobal
    ClassMethod Chinese2Spell(str As %String) As %String
    {
    	s spellStr= ""
    	s len = $l(str)
    	for i = 1 : 1 : len {
    		s char = $e(str, i)
    		s spell = $g(^pinyin(char))
    		s spellStr = spellStr _ spell
    	}
    	q spellStr
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    USER>w ##class(Util.StringUtils).Chinese2Spell("姚鑫")
    yaoxin
    
    • 1
    • 2

    判断字符串开头是否为数字

    ClassMethod IsPrefixNum(str As %String) As %Boolean
    {
    	q $isvalidnum($e(str))
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.StringUtils).IsPrefixNum("yx")
    0
    USER>w ##class(Util.StringUtils).IsPrefixNum("1yx")
    1
    
    • 1
    • 2
    • 3
    • 4

    全角转半角

    ClassMethod Angle2HalfAngle(str)
    {
    	s ascii  = $ascii(str)
    	s hex = $zhex(ascii)
    	s halfHex = "00" _ ($e(hex, 3) + 2) _ $e(hex, 4)
    	s halfAscii = $zhex(halfHex)
    	q $char(halfAscii)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    USER>w ##class(Util.StringUtils).Angle2HalfAngle("!")
    !
    USER>w ##class(Util.StringUtils).Angle2HalfAngle(",")
    ,
    
    • 1
    • 2
    • 3
    • 4

    判断字符串的长度. 汉字,全角字符,全角字母为2个长度, 字母为1个长度

    ClassMethod GetStringByte(str)
    {
    	s len = 0
    	for i = 1 : 1 : $l(str) {
    		s word = $e(str, i)
    		if ($ziswide(word)) {
    			s len = len + 2
    		} else {
    			s len = len + 1
    		}
    	}
    	q len
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    USER>w ##class(Util.StringUtils).GetStringByte("姚鑫1A“”'")
    11
    USER>w ##class(Util.StringUtils).GetStringByte(".。")
    3
    
    • 1
    • 2
    • 3
    • 4

    汉字,全角字符,全角字母返回 1, 其它返回0

    ClassMethod IsFullAngle(word) As %Boolean
    {
    	/* 汉字范围 */
    	q:(($a(word) >= 19968) && ($a(word) <= 40869)) $$$OK	
    	q:("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890`!@#$%^&*()_+|\{}[]"'。《》/?:;¥{},!、" [ word) $$$OK
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER> w ##class(Util.StringUtils).IsFullAngle("A")
    0
    USER>w ##class(Util.StringUtils).IsFullAngle("A")
    1
    
    • 1
    • 2
    • 3
    • 4

    按字节截取字符串

    ClassMethod GetStringSplit(str, num)
    {
    	s len = "0", j = ""
    	for i = 1 : 1 : $l(str) {
    		s word = $e(str, i)
    		if ($ziswide(word)) {
    			s len = len + 2
    		} else {
    			s len = len + 1
    		}
    		i (len = num)||(len - num = 1)  s j = i
    		q:(j '= "")
    	}
    	q:(j = "") str
    	s target = $e(str, 1, j)	
    	q target
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    USER>w ##class(Util.StringUtils).GetStringSplit("全角字母为2个长度",2)
    • 1
    • 2

    目标字符串替换为指定字符,其他替换为空

    ClassMethod ReplaceStr(source, del, target, str) As %Boolean
    {
    	s list = $lfs(source, "^")
    	s pos = $lf(list, target)
    	s num = $ll(list)
    	s newStr = ""
    	s $p(newStr, del, num) = ""
    	s array = $lfs(newStr, "^") 
    	s $li(array, pos) = str
    	s array = $lts(array, del)
    	q array
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    USER>w ##class(Util.StringUtils).ReplaceStr("1^2^3^4^5", "^", 4, "a")
    ^^^a^
    
    • 1
    • 2

    查找重复的字符串

    ClassMethod FindRepeat(str) As %Boolean
    {
    	s len = $l(str)
    	for i = 1 : 1 : len {
    		s array($i(array($e(str,i)))) = $e(str, i)
    	}
    	zw array
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 大于1为重复字符。
    USER>d ##class(Util.StringUtils).FindRepeat("abcdea1b2c3d4e5")
    array(1)=5
    array(2)="e"
    array(3)=1
    array(4)=1
    array(5)=1
    array("a")=2
    array("b")=2
    array("c")=2
    array("d")=2
    array("e")=2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    驼峰转下划线

    ClassMethod Camel2Underline(str)
    {
    	s old = str
    	s pos = 1
    	s count = 0
    	while $locate(str,"\w{1}[A-Z]{1}",pos, pos, val) {
    		s old = $e(old, 1, pos - 2 + count) _ "_" _   $e(old, pos - 1 + count, *)
    		s count = $i(count)
    	}
    	q old
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    USER> w ##class(Util.StringUtils).Camel2Underline("Red1YellowGreen23BlackWhite")
    Red1_Yellow_Green23_Black_White
    
    • 1
    • 2

    内部数组转字符串

    ClassMethod lb2String(lb)
    {
    	q $$Format^%qcr(lb, 1)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER> w ##class(Util.StringUtils).lb2String($lb(1,2,3,,"","yx"))
    $lb(1,2,3,,"","yx")
    
    • 1
    • 2

    格式化字符串

    ClassMethod FormatString(string As %String, flags As %Integer = 1, ByRef overflow As %Boolean) As %String
    {
    	q $$Quote^%qcr(string, 0, .overflow, flags)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.StringUtils).FormatString($lb(1,2,3,,"","yx"))
    $lb(1,2,3,,"","yx")
    
    • 1
    • 2

    将字符串至于行中间

    ClassMethod Center(str As %String = "", width As %Integer = 80) As %String
    {
    	q $j(str, ($l(str) + width) \ 2)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER> w ##class(Util.StringUtils).Center("yx",4)
     yx
    
    • 1
    • 2

    按次数替换字符串

    ClassMethod Replace(source As %String = "", findWhat As %String = "", replaceWith As %String = "", matchCase As %Boolean = 1, start As %Integer = 1, repeatCount As %Integer = 0, startMode As %Integer = 0) As %Integer
    {
    	if start < 0 {
    		s source = $re(source), findWhat = $re(findWhat), replaceWith = $re(replaceWith)
    		s start = -start, reverse = 1
    	}
    	s work = source, outputString = source, count = 0
    	q:(work = "") 0
    	s findLen = $l(findWhat), replaceLen = $l(replaceWith), dLen = replaceLen - findLen
    	q:('findLen) 0
    	s:'matchCase work = $zcvt(work, "U"),findWhat = $zcvt(findWhat, "U")
    	if startMode = 1 {
    		s f = 0
    		for i = 1 : 1 : start - 1 {
    			s f = $find(work, findWhat, f) q:'f
    		}
    		s start = f
    	}
    	for {
    		s start = $find(work, findWhat, start) q:'start
    		s startOut = count * dLen + start
    		s $e(outputString, startOut - findLen, startOut - 1) = replaceWith
    		if $i(count) = repeatCount q
    	}
    	s start = start - findLen + replaceLen
    	if $g(reverse) s outputString = $re(outputString), start = -start
    	q outputString
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    USER> w ##class(Util.StringUtils).Replace("ayxb","yx","yaoxin","")
    ayaoxinb
    USER>w ##class(Util.StringUtils).Replace("ayxb","yx","","")
    ab
    USER> w ##class(Util.StringUtils).Replace("ayxyxb","yx","","",1,1)
    ayxb
    USER>w ##class(Util.StringUtils).Replace("ayxyxb","yx","yaoxin","",1,2)
    ayaoxinyaoxinb
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    判断汉字是否是UTF8编码

    ClassMethod IsChineseUtf8(str) As %Boolean
    {
    	s len =  $l(str)
    	for i = 1 : 1 : len {
    		s byte = $e(str, i)
    		s ascii = $a(byte)
    		s bitStr = ##class(Util.BitUtils).LogicalToDisplay(ascii)
    		if (i = 1) {
    			s highBit = $e(bitStr, * - len, *)
    			#;s one = ##class(Util.StringUtils).Repeat("1", len)
    			#;s high = 0 _ one
    			ret:(highBit '= "0111") $$$NO
    		} else {
    			s highBit = $e(bitStr, * - 1, *)
    			ret:(highBit '= "01") $$$NO
    		}
    	}
    	q $$$YES
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    USER>w ##class(Util.StringUtils).IsChineseUtf8($zcvt("姚", "O", "UTF8"))
    1
    USER>w ##class(Util.StringUtils).IsChineseUtf8("姚")
    0
    
    • 1
    • 2
    • 3
    • 4

    数字相关 NumberUtils

    向上取整

    ClassMethod UpInteger(number As %Integer)
    {
    	q ##class(%SYSTEM.SQL).CEILING(number)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER> w ##class(Util.NumberUtils).UpInteger(0.3)
    1
    
    • 1
    • 2

    向下取整

    ClassMethod DownInteger(number As %Integer)
    {
    	q $normalize(number, -1)
    }
    
    • 1
    • 2
    • 3
    • 4
    ClassMethod DownInteger1(number As %Integer)
    {
    	q $system.SQL.FLOOR(number)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.NumberUtils).DownInteger(32.3)
    32
    w ##class(Util.NumberUtils).DownInteger1(32.3)
    32
    
    • 1
    • 2
    • 3
    • 4

    获取数字长度,不含 - ,.

    ClassMethod GetNumLen(number As %Integer) As %Integer
    {
    	if ('$isvalidnum(number)){
    		throw ##class(%Exception.General).%New("不是数字")
    	}
    	q $l($zstrip(+number,"*E'N"))
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##class(Util.NumberUtils).GetNumLen(32.3)
    3
    
    • 1
    • 2

    判断是否是整数

    ClassMethod IsInteger(str As %String) As %Boolean
    {
    	q:'$isvalidnum(str) $$$NO
    	q:(+str [ ".") $$$NO
    	q $$$YES
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    ClassMethod IsInteger1(str As %String) As %Boolean
    {
    	q:($number(str, "I") = "") $$$NO
    	q $$$YES
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.NumberUtils).IsInteger(-32.3)
    0
    USER>w ##class(Util.NumberUtils).IsInteger(-32.0)
    1
    USER>w ##class(Util.NumberUtils).IsInteger1(-32.3)
    0
    USER>w ##class(Util.NumberUtils).IsInteger1(-32.0)
    1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    字符串数字取最大值

    ClassMethod GetMaxNumber(str As %String) As %Decimal
    {
    	s len = $l(str, ",")
    	for i = 1 : 1 : len {
    		s array($p(str, ",", i)) = ""
    	}
    	q $o(array(""), -1)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    USER>w ##class(Util.NumberUtils).GetMaxNumber("1,2,3.1,5500.56,6.9,100,100.1")
    5500.56
    
    • 1
    • 2

    取第一段连续数字

    ClassMethod GetSuffixNumber(str As %String) As %Decimal
    {
    	s firstNum = $locate(str, "\d")
    	s str = $e(str, firstNum, *)
    	s secondNum = $locate(str, "\d*" ,1, end)
    	s str = $e(str, 1, end - 1)
    	q str
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    USER>w ##class(Util.NumberUtils).GetSuffixNumber("abcdef12a1")
    12
    
    • 1
    • 2

    对比数字是否相同

    ClassMethod IsSame(str As %String, target As %String) As %Boolean
    {
    	s list1 = $lfs(str, "^")
    	s list2 =  $lfs(target, "^")
    	q:$ls(list1, list2) $$$YES
    	s len1 = $ll(list1)
    	s len2 = $ll(list2)
    	q:(len1 '= len2) $$$NO
    	
    	for i = 1 : 1 : $ll(list1) {
    		if ('$lf(list2, $li(list1, i))) {
    			ret $$$NO
    		}
    	}
    	q $$$YES
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    USER> w ##class(Util.NumberUtils).IsSame("1^2^3", "3^2^1^0")
    0
    
    • 1
    • 2

    小数转分数

    ClassMethod GetComDiv(num1, num2)
    {
        s big = $s(num1 > num2 : num1 , 1 : num2)
        s sm = $s(num1 < num2 : num1 , 1 : num2)
        s rem = big # sm
        q:(rem = 0) sm
        q ..GetComDiv(rem, sm)
    }
    
    /// w ##class(Util.NumberUtils).Deci2Fra(0.125)
    ClassMethod Deci2Fra(num)
    {
        s nnum = $zabs(num)
        q:(nnum '< 1)&&(nnum '[ ".") num
        s ten = $l($p(num, ".", 2)) * 10
        s num1 = num * ten
        s num2 = ten
        s com =  ..GetComDiv(num1, num2)
        q (num1 / com) _ "/" _ (num2 / com)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    USER>w ##class(Util.NumberUtils).Deci2Fra(0.125)
    1/8
    
    • 1
    • 2

    不足N位补0

    ClassMethod ZeroPadding(target, num)
    {
        q $tr($j(target, num), " ", "0")
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.NumberUtils).ZeroPadding(1234,9)
    000001234
    
    • 1
    • 2

    转换为钱格式

    ClassMethod ConvertMoneyFomat(num, zeroNum)
    {
    	s len = $l(num)
    	s suffixNum = len \ 4
    	s suffix = ##class(Util.StringUtils).Repeat(",999", suffixNum)
    	
    	s prefixNum = (len # 4) +1
    	s prefix = ##class(Util.StringUtils).Repeat("9", prefixNum)
    	s format = prefix _ suffix
    	
    	s zero = ##class(Util.StringUtils).Repeat("9", zeroNum)
    	
    	s format = prefix _ suffix _ "." _ zero
    	&sql(
    		SELECT 
    			TO_CHAR(:num, :format)
    		INTO 
    			:target
    	)
    	q target
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    ClassMethod ConvertMoneyFomat1(num, zeroNum)
    {
    	q $fn(num, ",", zeroNum)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.NumberUtils).ConvertMoneyFomat(200000,2)
     200,000.00
    USER>w ##class(Util.NumberUtils).ConvertMoneyFomat1(200000,2)
    200,000.00
    
    • 1
    • 2
    • 3
    • 4

    数字转大写人民币

    ClassMethod Num2Rmb(num As %Integer) As %Integer
    {
    	q:'$isvalidnum(num) $$$ERROR(5001, "不是数字")
    	s minusSign = ""      
    	if num < 0 {
    		s minusSign = "负"
    		s num = $zabs(num)
    	}
    	s num = $fn(num, "N", 2)
    	s num = +num
    	
    	#; 整数部分
    	s units = $lb("元","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟","万")
    	s digitals = $lb("零","壹","贰","叁","肆","伍","陆","柒","捌","玖")
    	s target = ""
    	s int = $p(num, ".", 1) 
    	s decimal = $p(num, ".", 2) 
    	s int = $re(int)
    	s len = $l(int)
    	for i = 1 : 1 : len {
    		s pos = $e(int, i)
    		s digital = $lg(digitals, pos + 1)
    		s unit = $lg(units, i)
    		s target =  digital _ unit _ target
    	}
    	s target = minusSign _ target
    	s:(decimal = "") target = target _ "整"
    	#; 小数部分
    	s decimalStr = ""
    	s decimalUnits = $lb("分","角")
    	for i = 1 : 1 : $l(decimal) {
    		s pos = $e(decimal, i)
    		s digital = $lg(digitals, pos + 1)
    		s unit = $lg(decimalUnits, i)
    		s decimalStr =  digital _ unit _ decimalStr
    	}
    	s target = target _ decimalStr
    	q target
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    USER>w ##class(Util.NumberUtils).Num2Rmb("1119876543210.123456789")
    壹万壹仟壹佰玖拾捌亿柒仟陆佰伍拾肆万叁仟贰佰壹拾零元贰角壹分
    USER>w ##class(Util.NumberUtils).Num2Rmb("-111980000.01")
    负壹亿壹仟壹佰玖拾捌万壹分
    USER>w ##class(Util.NumberUtils).Num2Rmb("100")
    壹佰整
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    根号运算

    周志强提供

    ClassMethod Root(num, power)
    {
    	q +$fn(num ** (1 / power), "N", 4)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.NumberUtils).Root(1024,10)
    2
    USER>w ##class(Util.NumberUtils).Root(512,9)
    2
    USER>w ##class(Util.NumberUtils).Root(81,4)
    3
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    隋国阳提供

    • 使用二分法根号运算
    ClassMethod Root1(val, powerVal, negPoint = "", posPoint = "")
    {
    	s:(negPoint = "") negPoint = 0
    	s:(posPoint = "") posPoint = val
    	#; 计算平均值
    	s midpoint = (negPoint + posPoint) / 2  
    	#; 判断是否已经满足精度
    	if (..IsEnough(negPoint, posPoint)) {   
            q +$fn(midpoint, "N", 4)
        } else {
    	    s testValue = 1
    	    for i = 1 : 1 : powerVal{
    		   q:(testValue > val)   				
    		   s testValue = testValue * midpoint		
    		}
            s testValue = testValue - val				
            if (testValue > 0) {
                q ..Root1(val, powerVal, negPoint, midpoint)	
            } elseif (testValue < 0) {
                q ..Root1(val, powerVal, midpoint, posPoint)	
            } else {
                q +$fn(midpoint, "N", 4)
            }
        }
    }
    
    
    /// 判断两个数之差是否已经满足需要的精度
    ClassMethod IsEnough(x, y) As %Boolean
    {
    	s absVal = $zabs(x - y) 
    
    	q:(absVal < 0.00000000000001) $$$YES
    	
    	q $$$NO
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    USER>w ##class(Util.NumberUtils).Root1(27,3)
    3
    USER>w ##class(Util.NumberUtils).Root1(81,4)
    3
    
    • 1
    • 2
    • 3
    • 4
    • 牛顿迭代法
    ClassMethod Root2(val, powerVal)
    {
    	s k = val / powerVal
    	s testValue = 1
    	for i = 1 : 1: powerVal {
    		s testValue = testValue * k							
        }
    	while($zabs(testValue - val) > 0.00000000001){
    		s k = k - ((testValue - val) / (powerVal * (testValue / k)))  	
    		s testValue = 1
    		for i = 1 : 1 : powerVal{
    			s testValue = testValue * k							
    	    }
    	}
    	q +$fn(k, "N", 4)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    USER>w ##class(Util.NumberUtils).Root2(8,3)
    2
    USER>w ##class(Util.NumberUtils).Root2(1024,10)
    2
    
    • 1
    • 2
    • 3
    • 4

    大数相加

    ClassMethod BigNumAdd(x, y) As %Boolean
    {
    	s xLen = $l(x)
    	s yLen = $l(y)
    	
    	s overflow  = $$$NO
    	
    	s sum = ""
    	s len = $s(yLen > xLen : yLen, 1 : xLen)
    	for i = 0 : 1 : len - 1 {
    		s xi = $e(x, xLen - i)
    		s:(xi = "") xi = 0
    		
    		s yi = $e(y, yLen - i)
    		s:(yi = "") yi = 0
    		
    		s sumi = xi - yi + $s(overflow : 1, 1 : 0)
    		s:(sumi >= 10) overflow = $$$YES
    		s:(sumi < 10) overflow = $$$NO
    		
    		s:(overflow) sumi = sumi - 10
    		
    		s sum = sumi _ sum
    	}
    	
    	s:(overflow) sum= "1" _ sum
    	
    	q sum
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    USER>w ##class(Util.NumberUtils).BigNumAdd(102411111111111111111,108099999999999999999)
    00-6311111111111111100
    
    • 1
    • 2

    八位随机数 - 可当作salt

    ClassMethod GenCryptToken() 
    {
    	q ##class(%SYSTEM.Encryption).GenCryptToken()
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.NumberUtils).GenCryptToken()
    96718613
    
    • 1
    • 2

    日期相关 Util.DateUtils

    根据日期取年龄

    • 入参为逻辑格式。
    ClassMethod GetCurrentAge(date As %Date = "") As %Integer
    {
    	s age = $s(date = "" : "", 1 : ($zd($h, 8) - $ZD(date, 8) \ 10000))
    	q age
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.DateUtils).GetCurrentAge((+$h-3650))
    9
    
    • 1
    • 2

    获取年龄日期到当前的月数

    ClassMethod GetMonthsAge(from As %Date, to = {$zd(+$h, 3)}) As %Integer
    {
    	s fromDay = $zdh(from, 3)
    	s toDay  = $zdh(to, 3)
    	s num = $SYSTEM.SQL.DATEDIFF("mm", fromDay, toDay)
    	q num
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##class(Util.DateUtils).GetMonthsAge("1990-04-25")
    391
    
    • 1
    • 2

    获取年龄日期到当前的天数

    ClassMethod GetDaysAge(from As %Date, to = {$zd(+$h, 3)}) As %Integer
    {
    	s fromDay = $zdh(from, 3)
    	s toDay  = $zdh(to, 3)
    	
    	s num = $SYSTEM.SQL.DATEDIFF("dd", fromDay, toDay)
    	q num
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    USER> w ##class(Util.DateUtils).GetDaysAge("1990-04-25")
    11890
    
    • 1
    • 2

    计算日期相差秒数

    ClassMethod GetDiffSecond(date1 As %DateTime, date2 As %DateTime) As %Integer
    {
    	
    	s num = $SYSTEM.SQL.DATEDIFF("second", date1, date2)
    	q num
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##class(Util.DateUtils).GetDiffSecond("1990-04-25 21:00:00","1990-04-25 21:00:10")
    10
    
    • 1
    • 2

    计算日期相差分数

    ClassMethod GetDiffMinute(date1 As %DateTime, date2 As %DateTime) As %Integer
    {
    	
    	s num = $SYSTEM.SQL.DATEDIFF("mi", date1, date2)
    	q num
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>w ##class(Util.DateUtils).GetDiffMinute("1990-04-25 21:00:10","1990-04-26 21:00:20")
    1440
    
    • 1
    • 2

    计算输入日期的最后一天

    ClassMethod GetLastDay(date As %Date) As %Integer
    {
    	s date = $SYSTEM.SQL.LASTDAY(date)
    	q $zd(date, 3)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.DateUtils).GetLastDay("2021-06-01")
    2021-06-30
    USER>w ##class(Util.DateUtils).GetLastDay("2021-07-01")
    2021-07-31
    USER>w ##class(Util.DateUtils).GetLastDay("2021-02-01")
    2021-02-28
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    时间戳转日期默认精确到毫秒

    • 第二个参数传入 0 精确到秒
    ClassMethod Timestamp2DateTime(timestamp, ms As %Boolean = 1)
    {
    	s timestamp = $g(timestamp)
    	q:timestamp="" ""
    	i ms s timestamp = timestamp \ 1000
    	s datetime = timestamp + 4070937600
    	s time = datetime # 86400
    	s date = (datetime - time) / 86400
    	s date = $zd(date, 3)
    	s time = $zt(time, 1)
    	s toDateTime = date _ " " _ time
    	q toDateTime
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    USER>w ##class(Util.DateUtils).Timestamp2DateTime(1668340100, 0)
    2022-11-13 19:48:20
    USER>w ##class(Util.DateUtils).Timestamp2DateTime(327686400000)
    1980-05-21 00:00:00
    
    • 1
    • 2
    • 3
    • 4

    当前日期转时间戳默认精确到毫秒

    • 参数 0 精确到秒
    ClassMethod DateTime2Timestamp(ms As %Boolean = 1)
    {
    	if (ms) {
    		s timestamp = (+$h - 47117) * 3600 * 24 * 1000 
    		s nowtimestamp = $p($zts, ",", 2) * 1000
    		s timestamp = timestamp + nowtimestamp
    	} else {
    		s timestamp = (+$h - 47117) * 3600 * 24 
    		s nowtimestamp = $p($p($zts, ",", 2), ".")
    		s timestamp = timestamp + nowtimestamp
    	}
    	q timestamp
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    USER>w ##class(Util.DateUtils).DateTime2Timestamp(0)
    1668340100
    USER>w ##class(Util.DateUtils).DateTime2Timestamp()
    1668340101867
    
    • 1
    • 2
    • 3
    • 4

    获取上个月一号到上个月最后一天

    • 返回为数组格式
    ClassMethod GetLastMonthDuring() As %String
    {
    	s currentDate = $zd(+$h, 3)
    	s currentYear = $p(currentDate, "-", 1)
    	s currentMonth = $p(currentDate, "-", 2)
    	s currentDate = $p(currentDate,"-", 3)
    	s:(currentMonth = 1) year = currentYear - 1,month = 12
    	s:(currentMonth '= 1) year = currentYear, month = currentMonth - 1
    	s:($l(month) = 1) month = "0" _ month
    	s startDate = year _ "-" _ month _ "-" _ "01"
    	s:($l(currentMonth) = 1) month = "0" _ currentMonth
    	s mDate = currentYear _ "-" _ currentMonth _ "-"_"01"
    	s m = $zdh(mDate, 3)
    	s endDate = $zd(m - 1, 3)
    	q $lb(startDate, endDate)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    USER 2e1>zw ##class(Util.DateUtils).GetBeforeMothday()
    $lb("2022-10-01","2022-10-31")
    
    • 1
    • 2

    获取上个月的今天

    ClassMethod GetLastMonthToday() As %String
    {
    	q $SYSTEM.SQL.DATEADD("mm", -1, +$h)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.DateUtils).GetLastMonthToday()
    2022-10-13 00:00:00
    
    • 1
    • 2

    获取今天是月中第几天

    ClassMethod GetMonthDay() As %String
    {
    	q $SYSTEM.SQL.DAYOFMONTH(+$H)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.DateUtils).GetMonthDay()
    13
    
    • 1
    • 2

    当前时间加上N个小时

    ClassMethod GetAddHour(hour) As %String
    {
    	q $SYSTEM.SQL.DATEADD("hh", hour, $h)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.DateUtils).GetAddHour(1)
    2022-11-13 20:55:59
    
    • 1
    • 2

    获取一年中第几个星期

    ClassMethod GetWeekOfYear(date) As %String
    {
    	q $SYSTEM.SQL.WEEK(date)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER> w ##class(Util.DateUtils).GetWeekOfYear("2020-01-01")
    1
    USER>w ##class(Util.DateUtils).GetWeekOfYear(+$h)
    47
    
    • 1
    • 2
    • 3
    • 4

    格式化日期

    ClassMethod FormatDate(date, toFormat, fromFormt)
    {
    	s fDate = $system.SQL.TODATE(date, toFormat)
    	s tDate = $system.SQL.TOCHAR(fDate, fromFormt)
    	q tDate
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>w ##Class(Util.DateUtils).FormatDate("20/04/2022", "DD/MM/YYYY", "YYYY/MM/DD")
    2022/04/2
    
    • 1
    • 2

    验证日期是否合法

    ClassMethod IsValidDate(date, toFormat, fromFormt) As %Boolean
    {
    	s sc = ##class(%Library.TimeStamp).IsValid(date)
    	q:($$$ISERR(sc)) $$$NO
    	q $$$YES
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##Class(Util.DateUtils).IsValidDate("2022-04-25")
    1
    USER>w ##Class(Util.DateUtils).IsValidDate("20/04/2022")
    0
    
    • 1
    • 2
    • 3
    • 4

    遍历两个日期中间的月份

    ClassMethod ForMonth(startMonth, endMonth)
    {
    	s startMonth = +startMonth * 12 + (+$p(startMonth, "-", 2)) 
    	s endMonth = +endMonth * 12 + (+$p(endMonth, "-", 2)) 
    	for i = startMonth : 1 : endMonth {
    		s year = i \ 12
    		s month  = i # 12 + 1
    		w year _ "-" _ month,!
    	}
    	q ""
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    USER>w ##Class(Util.DateUtils).ForMonth("2020-7","2022-07")
    2020-8
    2020-9
    2020-10
    2020-11
    2020-12
    2021-1
    2021-2
    2021-3
    2021-4
    2021-5
    2021-6
    2021-7
    2021-8
    2021-9
    2021-10
    2021-11
    2021-12
    2022-1
    2022-2
    2022-3
    2022-4
    2022-5
    2022-6
    2022-7
    2022-8
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    根据年份获取每一个月的开始和结束日期的函数

    ClassMethod GetMonthPeriods(initialYear As %Integer, endYear As %Integer) As %Status
    {
        s sc = $$$OK
        s result = []
        for currentYear = initialYear : 1 : endYear {
            for currentMonth = 1 : 1 : 12 {
                set item = {}
                if currentMonth < 10 {
                    s currentMonthStr = "0" _ currentMonth
                } else {
                    s currentMonthStr = "" _ currentMonth
                }
                s item.startDate = currentYear _ "-" _ currentMonthStr _ "-01T00:00:00"
                s nextMonth = currentMonth + 1
                if nextMonth = 13 {
                    s item.endDate = currentYear _ "-12-31T23:59:59"
                } else {
                    s nextDate = $system.SQL.TODATE(currentYear _ "-" _ nextMonth _ "-01", "YYY-MM-DD")
                    s nextDate = $i(nextDate, -1)
                    s item.endDate = $zd(nextDate, 3) _ "T23:59:59"
                }
                
                d result.%Push(item)
            }
        }
        w result.%ToJSON()
    
        ret sc
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    USER> w ##Class(Util.DateUtils).GetMonthPeriods("2022",2022)
    [{"startDate":"2022-01-01T00:00:00","endDate":"2022-01-31T23:59:59"},{"startDate":"2022-02-01T00:00:00","endDate":"2022-02-28T23:59:59"},{"startDate":"2022-03-01T00:00:00","endDate":"2022-03-31T23:59:59"},{"startDate":"2022-04-01T00:00:00","endDate":"2022-04-30T23:59:59"},{"startDate":"2022-05-01T00:00:00","endDate":"2022-05-31T23:59:59"},{"startDate":"2022-06-01T00:00:00","endDate":"2022-06-30T23:59:59"},{"startDate":"2022-07-01T00:00:00","endDate":"2022-07-31T23:59:59"},{"startDate":"2022-08-01T00:00:00","endDate":"2022-08-31T23:59:59"},{"startDate":"2022-09-01T00:00:00","endDate":"2022-09-30T23:59:59"},{"startDate":"2022-10-01T00:00:00","endDate":"2022-10-31T23:59:59"},{"startDate":"2022-11-01T00:00:00","endDate":"2022-11-30T23:59:59"},{"startDate":"2022-12-01T00:00:00","endDate":"2022-12-31T23:59:59"}]
    
    • 1
    • 2

    SQL相关 Util.SqlUtls

    判断当前是否在事务当中

    ClassMethod IsIntrans() As %Boolean
    {
    	n SQLCODE
    	&sql(%INTRANSACTION)
    	q:'SQLCODE $$$YES
    	q $$$NO
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    USER>w ##class(Util.SqlUtls).IsIntrans()
    0
    USER>ts
     
    TL1:USER>w ##class(Util.SqlUtls).IsIntrans()
    1
    TL1:
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    获取最大ID

    ClassMethod GetMaxID(table)
    {
    	&sql(SELECT MAX(%ID) INTO :maxID FROM Sample.Person )
    	q maxID
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.SqlUtls).GetMaxID()
    215
    
    • 1
    • 2

    修正索引

    ClassMethod ValidateIndices()
    {
    	s sc = ##class(Sample.Person).%ValidateIndices("",1,2,1)
    	if sc=1 {
    		w !,"成功索引验证/更正" 
    	} else {
    		w !,"索引验证/更正失败",!
    		d $System.Status.DisplayError(sc) 
    	}
    	q ""
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    USER>w ##class(Util.SqlUtls).ValidateIndices()
     
     
    Checking index integrity for class 'Sample.Person'
    Begin time:  11/13/2022 20:29:25
     
    Verifying data from data map 'IDKEY' is indexed correctly...
    Index 'AddDateTimeIndex', entry ^Sample.PersonI("AddDateTimeIndex"," ",116) missing.  Corrected
    Bitmap index 'ZipCode', entry $bit(^Sample.PersonI("ZipCode"," 15537",1),117)=0, row is missing from index, it should be 1.  Corrected
    ...
    
    成功索引验证/更正
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    查询表结构存在的sql语句所在的类

    ClassMethod QuerySqlTableStatements(schema, table)
    {
    	s call = "CALL %Library.SQLTableStatements('"_ schema _ "','"_ table _ "')"
    	s tStatement = ##class(%SQL.Statement).%New()
    	s sc = tStatement.%Prepare(call)
    	if sc '= 1 {
    		w "%Prepare 失败" 
    		d $System.Status.DisplayError(sc) q
    	}
    	s rset = tStatement.%Execute()
    	if rset.%SQLCODE '= 0 {
    		w "SQL 错误",rset.%SQLCODE q
    	}
    	d rset.%Display()
    	q ""
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    USER>w ##class(Util.SqlUtls).QuerySqlTableStatements("Sample","Person")
     
     
    Dumping result #1
    SCHEMA  RELATION_NAME   PLAN_STATE      LOCATION        STATEMENT
    SAMPLE  PERSON  0       PHA.TEST.SQLCommand.1   SELECT HOME_STATE , NAME , AGE INTO :state , :name , :age FROM SAMPLE . PERSON
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    判断表在当前命名空间是否存在

    • %SYSTEM.SQL ,IRIS和Cache包名有区别。
    ClassMethod IsTableExists(table)
    {
    	q ##class(%SYSTEM.SQL.Schema).TableExists(table)
    }
    
    • 1
    • 2
    • 3
    • 4

    验证表名是否合法

    ClassMethod IsValidTableName(tablename)
    {
    	s x = $SYSTEM.SQL.IsValidRegularIdentifier(tablename)
    	if x = 0 {
    		if $length(tablename) > 200 {
    			q "表名太长" 
    		} elseif $SYSTEM.SQL.IsReservedWord(tablename) {
    			q "表名是保留字" 
    		} else {
    			s nls = ##class(%SYS.NLS.Locale).%New()
    			if nls.Language [ "Japanese" {
    				q "日语区域设置不能使用重音字母"
    			}
    			q "表名包含无效字符"
    		}
    	} else { 
    		q tablename _" 是有效的表名称"
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    USER>w ##class(Util.SqlUtls).IsValidTableName("#asdasasdas")
    表名包含无效字符
    USER>w ##class(Util.SqlUtls).IsValidTableName("asdasasdas")
    asdasasdas 是有效的表名称
    
    • 1
    • 2
    • 3
    • 4

    确定字段最大值

    ClassMethod GetFieldMaxVal(integer, decimal)
    {
     	q $$maxval^%apiSQL(integer, decimal)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER> w ##class(Util.SqlUtls).GetFieldMaxVal(6,2)
    9999.99
    
    • 1
    • 2

    确定字段最小值

    ClassMethod GetFieldMinVal(integer, decimal)
    {
    	q $$minval^%apiSQL(integer, decimal)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.SqlUtls).GetFieldMinVal(6,2)
    -9999.99
    
    • 1
    • 2

    Query变成表

    ClassMethod QueryToTable(query, tablename)
    {
     	d $SYSTEM.SQL.QueryToTable(query, tablename ,0)
    }
    
    • 1
    • 2
    • 3
    • 4

    创建UUID

    ClassMethod CreateUUID()
    {
     	q $System.Util.CreateGUID()
    }
    
    • 1
    • 2
    • 3
    • 4

    根据类名获取sql表名

    ClassMethod GetTableName(className As %String) As %String
    {
    	q ##class(%Dictionary.ClassDefinition).%OpenId(className).SqlTableName
    }
    
    • 1
    • 2
    • 3
    • 4
    ClassMethod GetTableName1(className As %String) As %String
    {
    	s tableName = ""
    	&sql(SELECT TABLE_NAME into :tableName FROM INFORMATION_SCHEMA.Tables WHERE TABLE_SCHEMA='SQLUser' AND CLASSNAME = :className)
    	q tableName
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER> w ##class(Util.MethodUtils).GetTableName("User.Person")
    BS_Person
    USER>w ##class(Util.MethodUtils).GetTableNameBySQLUser("User.Person")
    BS_Person
    
    • 1
    • 2
    • 3
    • 4

    流字段模糊查询like

    李高提供

    ClassMethod StreamLike()
    {
    	&sql(select SUBSTRING(Notes,0) ,* from Sample.MyTable where SUBSTRING(Notes,0) like '%yx%')
    }
    
    • 1
    • 2
    • 3
    • 4

    进程相关 Util.ProcessUtils

    停止当前进程所有Break断点

    ClassMethod StopBreak()
    {
    	d ##class(%SYSTEM.Process).BreakMode(0)
    }
    
    • 1
    • 2
    • 3
    • 4

    开启当前进程所有Break断点

    ClassMethod StartBreak()
    {
    	d ##class(%SYSTEM.Process).BreakMode(1)
    }
    
    • 1
    • 2
    • 3
    • 4

    列出当前进程可用的所有命名空间(显式和隐式)

    ClassMethod GetAllNameSpace()
    {
    	d ##class(%SYS.Namespace).ListAll(.result)
    	zw result
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    网络相关 Util.NetUtils

    格式化Url

    ClassMethod UrlParser()
    {
    	s url = "https://www.google.com/search?q=Java+site%3Adocs.intersystems.com&oq=Java+site%3Adocs.intersystems.com"
    	d ##class(%Net.URLParser).Parse(url,.components)
    	zw components
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>d ##class(Util.NetUtils).UrlParser()
    components("fragment")=""
    components("host")="www.google.com"
    components("netloc")="www.google.com"
    components("params")=""
    components("path")="/search"
    components("query")="q=Java+site%3Adocs.intersystems.com&oq=Java+site%3Adocs.intersystems.com"
    components("scheme")="https"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    命名空间相关 Util.NamespaceUtils

    判断命名空间是否存在

    ClassMethod IsNamespaceExist(name) As %Boolean
    {
    	q ##class(%SYS.Namespace).Exists(name)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.NamespaceUtils).IsNamespaceExist("user1")
    0
    USER>w ##class(Util.NamespaceUtils).IsNamespaceExist("user")
    1
    
    • 1
    • 2
    • 3
    • 4

    类相关 Util.ClassUtils

    获取方法的参数数量

    ClassMethod GetParamsNum(className As %String, methodName As %String) As %Integer
    {
    	s methodParams = $g(^oddCOM(className, "m", methodName, 60))
    	s paramsNum = $ll(methodParams)
    	q paramsNum
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    ClassMethod GetNowParamsNum(arg...) As %Integer
    {
    	w arg,!
    	q $zutil(141)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER> w ##class(Util.ClassUtils).GetParamsNum("Util.ClassUtils","GetParamsNum")
    2
    USER>w ##class(Util.ClassUtils).GetNowParamsNum("Util.ClassUtils","GetParamsNum","2","3")
    4
    4
    
    • 1
    • 2
    • 3
    • 4
    • 5

    判断方法是否存在

    ClassMethod IsHasMethod(className As %String, methodName As %String) As %Boolean
    {
    	q:($d(^oddCOM(className, "m", methodName))) $$$YES
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    ClassMethod IsHasMethod1(className As %String, methodName As %String) As %Boolean
    {
    	q:(##class(%Dictionary.MethodDefinition).%ExistsId(className _ "||" _ methodName)) $$$YES
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.ClassUtils).IsHasMethod("Util.ClassUtils","IsHasMethod")
    1
    USER>w ##class(Util.ClassUtils).IsHasMethod("Util.ClassUtils","IsHasMethod1")
    1
    
    • 1
    • 2
    • 3
    • 4

    判断类方法属性是否存在

    ClassMethod IsPropExist(className As %String, prop As %String) As %Boolean
    {
    	q:($d(^oddCOM(className, "a", prop))) $$$YES
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    ClassMethod IsPropExist1(className As %String, prop As %String) As %Boolean
    {
    	q:(##class(%Dictionary.PropertyDefinition).%ExistsId(className _ "||" _ prop)) $$$YES
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.ClassUtils).IsPropExist("Util.ClassUtils","Name")
    1
    USER>w ##class(Util.ClassUtils).IsPropExist1("Util.ClassUtils","Name1")
    0
    
    • 1
    • 2
    • 3
    • 4

    判断类是否存在

    ClassMethod IsExistsCls(cls As %String) As %Boolean
    {
        if '##class(%Dictionary.CompiledClass).%ExistsId(cls) {
            q $$$NO
        }
        q $$$OK
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##class(Util.ClassUtils).IsExistsCls("Util.ClassUtils")
    1
    USER>w ##class(Util.ClassUtils).IsExistsCls("Util.ClassUtils1")
    0
    
    • 1
    • 2
    • 3
    • 4

    判断类是否继承了某个类

    ClassMethod IsExtendCls(cls As %String, parentCls As %String) As %Boolean
    {
        Set check = $classmethod(cls, "%Extends", parentCls)
        If 'check {
            q $$$NO
        }
        q $$$OK
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    USER> w ##class(Util.ClassUtils).IsExtendCls("IMP.LOCK.BIZ","IMP.LOCK.Base")
    1
    
    • 1
    • 2

    根据类名获取表名

    ClassMethod GetTableNameByClassName(className)
    {
    	&sql(SELECT SqlQualifiedNameQ into :tableName FROM   %Dictionary.CompiledClass WHERE ID = :className)
    	q tableName
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.ClassUtils).GetTableNameByClassName("M.T.PERSON")
    M.T_Person
    
    • 1
    • 2

    根据视图名称查询视图SQL语句

    ClassMethod GetViewText(sqlViewName)
    {
    	&sql(SELECT SqlQuery into :text FROM  %Dictionary.QueryDefinition WHERE   SqlView =1 AND SqlViewName = :sqlViewName)
    	q text
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.ClassUtils).GetViewText("Query_With_Parameters")
    SELECT P.Id, P.NameSpace, P.QueryText, P.RunTime, P.JobNumber, PV.PValues
    FROM %SYS_PTools.SQLBenchMarkQueries P
    LEFT OUTER JOIN %SYS_PTools.SQLBenchMarkQueries_PValues PV ON P.ID = PV.SQLBenchMarkQueries
    
    • 1
    • 2
    • 3
    • 4

    获取类描述

    ClassMethod GetClassDesc(className)
    {
    	&sql(SELECT Description into :desc FROM  %Dictionary.ClassDefinition WHERE  ID = :className )
    	q $g(desc)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>w ##class(Util.ClassUtils).GetClassDesc("M.M79")
    author:姚鑫
    
    • 1
    • 2

    获取方法描述

    ClassMethod GetMethodDesc(className, methodName)
    {
    	s ID = className _ "||" _ methodName
    	&sql(SELECT Description into :desc FROM  %Dictionary.MethodDefinition WHERE  ID = :ID )
    	q $g(desc)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>w ##class(Util.ClassUtils).GetMethodDesc("M.M79","WaitLock")
    desc:加锁
    d ##class(M.M79).WaitLock()
    
    • 1
    • 2
    • 3

    获取关键字描述

    ClassMethod GetKeywordDesc(keyWord, flag, name)
    {
    	q $$FindDesc^%occName(keyWord, flag ,name)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.ClassUtils).GetKeywordDesc("M.M79","m","WaitLock")
    desc:加锁
    d ##class(M.M79).WaitLock()
    
    • 1
    • 2
    • 3

    获取方法入参数组

    • 无参返回空
    ClassMethod GetParamsList(className, methodName)
    {
        s method = className _ "||" _ methodName
        &SQL(
    		SELECT FormalSpecParsed INTO :formalSpecParsed
    			FROM %Dictionary.CompiledMethod
    		WHERE ID1 = :method 
        )
        q formalSpecParsed
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    USER>zw ##class(Util.ClassUtils).GetParamsList("M.M79","WaitLock")
    $lb($lb("name","%Library.String","",""),$lb("age","%Library.String","",""))
    
    • 1
    • 2

    验证方法名是否合法

    ClassMethod IsValidMethodName(name) As %Boolean
    {
    	q $zname(name)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER> w ##class(Util.ClassUtils).IsValidMethodName("%M79")
    1
    USER>w ##class(Util.ClassUtils).IsValidMethodName("#M79")
    0
    
    • 1
    • 2
    • 3
    • 4

    获取类创建日期时间

    ClassMethod GetClassCreatedDateTime(className)
    {
    	&sql(SELECT TimeCreated into :TimeCreated FROM   %Dictionary.ClassDefinition WHERE ID = :className)
    	q $zdt(TimeCreated,3)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>w ##class(Util.ClassUtils).GetClassCreatedDateTime("User.Person")
    2011-08-12 19:54:41
    
    • 1
    • 2

    锁相关 Util.LockUtils

    判断锁是否存在

    ClassMethod IsLockExist(lockname) As %Boolean
    {
    	q:($d(^$lock(lockname))) $$$YES
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>l +^yx(1,1)
     
    USER>w ##class(Util.LockUtils).IsLockExist("^yx(1,1)")
    1
    USER>w ##class(Util.LockUtils).IsLockExist("^yx(1,2)")
    0
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    获取锁进程ID

    ClassMethod GetLockPid(lockname) As %Boolean
    {
    	q ^$lock(lockname, "OWNER")
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.LockUtils).GetLockPid("^yx(1,1)")
    3544
    
    • 1
    • 2

    获取锁进程类型

    ClassMethod GetLockType(lockname) As %Boolean
    {
    	q ^$lock(lockname, "MODE")
    }
    
    • 1
    • 2
    • 3
    • 4
    USER> w ##class(Util.LockUtils).GetLockType("^yx(1,1)")
    X
    
    • 1
    • 2

    获取锁进程状态

    ClassMethod GetLockFlag(lockname) As %Boolean
    {
    	q ^$lock(lockname, "FLAGS")
    }
    
    • 1
    • 2
    • 3
    • 4

    删除所有锁,会删除系统固定锁

    ClassMethod DeleteAllLock(namespace) As %Boolean
    {
    	s ret = 0
    	do
    	.n $namespace
    	.s $namespace = "%sys"
    	.s ret = ##Class(SYS.Lock).DeleteAllLocks()
    	q ret
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    删除进程pid相关锁

    ClassMethod DeleteLockByPid(pid) As %Boolean
    {
    	s ret = 0
    	
    	do
    	.n $namespace
    	.s $namespace = "%sys"
    	.s ret = ##Class(SYS.Lock).DeleteAllLocks(pid)
    	
    	q ret
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    根据lockname删除锁

    ClassMethod DeleteLockByLockname(lockname) As %Boolean
    {
    	s ret = 0
    	s rs = ##class(%ResultSet).%New("%SYS.LockQuery:List")
    	d rs.Execute("")
    	while rs.Next(){
    		if (rs.Data("LockString") = lockname) {
    			do
    			.n $namespace
    			.s $namespace = "%sys"
    			.s ret = ##Class(SYS.Lock).DeleteOneLock(rs.Data("DelKey"), "", 1)
    		}
    	}
    	q ret
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    查询锁相关信息

    ClassMethod QueryLockInfo(lockname) As %Boolean
    {
    	
    	s rs = ##class(%ResultSet).%New("%SYS.LockQuery:List")
    	d rs.Execute("")
    
    	while rs.Next() {
    		w rs.Data("Owner"),!
    		w rs.Data("LockString"),!
    		w rs.Data("DelKey"),!
    		w rs.Data("Mode"),!
    		w rs.Data("Flags"),!
    		w rs.Data("DelKey"),!
    		w rs.Data("Sfn"),!
    		w rs.Data("FullReference"),!
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    遍历命名空间所有锁

    ClassMethod QueryLock(namespace) As %Boolean
    {
    	s lockname=""
    	for i = 1 : 1 {
    		s lockname = $o(^$|namespace|lock(lockname))
    		q:lockname=""
    		w lockname,!
    
    	}
    	q ""
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    USER>w ##class(Util.LockUtils).QueryLock("%sys")
    ^%SYS("CSP","Daemon")
    ^ISC.LMFMON("License Monitor")
    ^ISC.Monitor.System
    ^TASKMGR
    
    • 1
    • 2
    • 3
    • 4
    • 5

    工具相关 Util.FunctionUtils

    获取当前HostName

    ClassMethod GetHostName() As %String
    {
    	s str = ##class(%Library.Function).HostName()
    	q str
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    ClassMethod GetHostName1() As %String
    {
    	s x = ##class(%SYS.System).GetNodeName()
    	q x
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>w ##class(Util.FunctionUtils).GetHostName()
    LAPTOP-ARLL3DSO
    USER>w ##class(Util.FunctionUtils).GetHostName1()
    LAPTOP-ARLL3DSO
    
    • 1
    • 2
    • 3
    • 4

    获取客户端IP

    ClassMethod GetOutLocalIP() As %String
    {
    	q ##class(%SYSTEM.Process).ClientIPAddress()
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.FunctionUtils).GetOutLocalIP()
    127.0.0.1
    
    • 1
    • 2

    获取服务器本地IP

    ClassMethod GetInLocalIP() As %String
    {
    	q $p($zu(54,13,$zu(54,0)),",",1 )
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.FunctionUtils).GetInLocalIP()
    192.168.18.4
    
    • 1
    • 2

    获取当前命名空间物理路径

    ClassMethod GetNameSpacePath() As %String
    {
    	q ##class(%Library.File).NormalizeDirectory("")
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(%Library.File).NormalizeDirectory("")
    C:\InterSystems\Cache\mgr\user\
    
    • 1
    • 2

    判断环境是否是中文

    ClassMethod IsChineseLocale() As %Boolean
    {
    	s nls = ##class(%SYS.NLS.Locale).%New()
    	q:(nls.Language [ "Chinese") $$$OK
    	q $$$NO
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##class(Util.FunctionUtils).IsChineseLocale()
    1
    
    • 1
    • 2

    获取License信息

    ClassMethod ShowLicenseInfo() As %Boolean
    {
    	d ##class(%SYSTEM.License).ShowCounts()
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER> d ##class(Util.FunctionUtils).ShowLicenseInfo()
     
    本地软件许可使用视图.
     
        300     授权的总数量 LU
        299     当前可用 LU
        299     最小可用 LU
          1     当前用户处于活动状态
          1     处于活动状态的最大用户数
          0     当前 CSP 用户处于活动状态
          0     处于活动状态的最大 CSP 用户数
          0     当前 CSP 会话处于宽限期
          0     处于宽限期的最大 CSP 会话数
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    获取可用最大的许可证数量

    ClassMethod GetMaxAvailableLicense() As %Boolean
    {
    	q $SYSTEM.License.LUMinAvailable()
    }
    
    • 1
    • 2
    • 3
    • 4
    USER> w ##class(Util.FunctionUtils).GetMaxAvailableLicense()
    299
    
    • 1
    • 2

    用X命令初始化N个变量

    刘小明 提供

    ClassMethod InitMultiVar(name, num) As %Status
    {
    	s str = ""
    	for i = 1 : 1 : num {
    		if i = 1 {
    			s str = "s (" _ name _ "" _ i	
    		} else {
    			s str = str _ ", " _ name _ "" _ i	
    		}
    	}
    	s str = str _ ") = 0"
    
    	x str
    	
    	for i = 1 : 1 : num {
    		s str="w " _ name _ ""_i_",!"
    		x str
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    USER> d ##class(Util.FunctionUtils).InitMultiVar("yx",3)
    0
    0
    0
    
    • 1
    • 2
    • 3
    • 4

    获取程序运行时间

    ClassMethod GetRunTime(className, methodName, params...) As %Boolean
    {
    	s t1 = $zh
    	d $classmethod(className, methodName, params...)
    	q $zh - t1
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER> w ##class(Util.FunctionUtils).GetRunTime("Util.FunctionUtils","InitMultiVar","yx",3)
    .000028
    
    • 1
    • 2

    导出当前所有进程的进程GLOABL到CSV文件

    ClassMethod ExportAllProcessPrivateGlobal2Csv(path) As %Boolean
    {
    	do
    	.s $namespace = "%sys"
    	.d ^GETPPGINFO("*", "MNN", path)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    d ##class(Util.FunctionUtils).ExportAllProcessPrivateGlobal2Csv("E:/m/ppg.csv")
    
    • 1

    读取类int文件中方法代码

    ClassMethod GetIntFileMethod(className, methodName)
    {
    	for {
    		s str = "z" _ methodName _ "+" _ ($i(line) - 1) _ "^" _ className _ ".1"
    		s code = $text(@str)
    		q:(code = "")
    		w code,!
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    USER>d ##class(Util.FunctionUtils).GetIntFileMethod("Util.FunctionUtils","GetIntFileMethod")
    zGetIntFileMethod(className,methodName) public {
     for {
            s str = "z" _ methodName _ "+" _ ($i(line) - 1) _ "^" _ className _ ".1"
            s code = $text(@str)
            q:($i(count) > 1)&&($e(code) = "z")
            w code,!
     } }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    读取类int文件所有内容

    ClassMethod GetIntFileContent(className)
    {
    	for {
    		s str =  "+" _ ($i(line) - 1) _ "^" _ className _ ".1"
    		s code = $text(@str)
    		q:(code = "")
    		w code,!
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    USER>d ##class(Util.FunctionUtils).GetIntFileContent("Util.FunctionUtils")   Util.FunctionUtils.1
     ;Util.FunctionUtils.1
     ;(C)InterSystems, generated for class Util.FunctionUtils.  Do NOT edit. 12/14/2022 10:08:22PM
     ;;6A677733;Util.FunctionUtils
     ;
    zExportAllProcessPrivateGlobal2(path) public {
     do
     .s $namespace = "%sys"
     .d ^GETPPGINFO("*", "MNN", path)
    }
    
    ...
    
    zIsChineseLocale(str) public {
     s nls = ##class(%SYS.NLS.Locale).%New()
     q:(nls.Language [ "Chinese") 1
     q 0 }
    zShowLicenseInfo() public {
     d ##class(%SYSTEM.License).ShowCounts()
    }
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    判断CTRL-C是否可以中断程序

    ClassMethod IsEnableCtrlC() As %Boolean
    {
    	q:($zjob\4#2 = 1) $$$OK
    	q $$$NO
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER> w ##class(Util.FunctionUtils).IsEnableCtrlC()
    299
    
    • 1
    • 2

    检查X命令语法是否正确

    ClassMethod CheckSyntax(str) As %Boolean
    {
    	s ret = ##class(%Library.Routine).CheckSyntax(str)
    	q:($$$ISERR(ret)) $$$NO
    	q $$$YES
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>w ##class(Util.FunctionUtils).CheckSyntax("   s ^yx(""Xecute"") = 3")
    1
    
    • 1
    • 2

    通过代码创建routine方法

    ClassMethod CreateRoutine(name, code)
    {
    	s routine = ##class(%Routine).%New(name)
    	s index = ""
    	for {
    		s index = $o(code(index))
    		q:(index = "")
    		d routine.WriteLine(code(index))
    	}
    	d routine.Save()
    	d routine.Compile()
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    ClassMethod Code()
    {
    	s code($i(code)) = "zYx1() public { "
    	s code($i(code)) = " w ""This is my routine1"",!"
    	s code($i(code)) = " q }"
    	d ##class(Util.FunctionUtils).CreateRoutine("M.M91.mac", .code)
    }
    
    USER>w ##class(Util.FunctionUtils).Code()
     
    正在编译例程 : M.M91.mac
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    单步执行调试方法

    ClassMethod SingleStepDebug(className, methodName, params...)
    {
    	b "L+"
    	s ret = $classmethod(className, methodName, params...)
    	b "off"
    	q ret
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>d ##class(Util.FunctionUtils).SingleStepDebug("Util.FunctionUtils","IsEnableCtrlC")
     
     s ret = $classmethod(className, methodName, params...)
     ^
    <BREAK>zSingleStepDebug+2^Util.FunctionUtils.1
    USER 2d1>g
     
     q:($zjob\4#2 = 1) 1
     ^
    <BREAK>zIsEnableCtrlC+1^Util.FunctionUtils.1
    USER 3e1>g
     
     b "off"
     ^
    <BREAK>zSingleStepDebug+3^Util.FunctionUtils.1
    USER 2d1>g
     
    USER>g
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    不转命名空间调用其他命名空间方法

    ClassMethod CallOtherNameSpaceMethod(namespace, class, method, arg...)
    {
    	s params = ""
    	for i = 1 : 1 :arg {
    		if (params = "") {
    			s params = """"_arg(i)_""""
    		} else {
    			s params = params _ "," _ """"_arg(i)_""""
    		}
    	}
    
    	x ("(ret) s ret = $$z" _ method _ "^|"""_ namespace _"""|"_ class _".1("_params_")", .ret)
    	
    	q ret
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    USER>w ##class(Util.FunctionUtils).CallOtherNameSpaceMethod("IMP","M.M91","TransactionFeature2","y","x")
    y 与 x
    
    • 1
    • 2

    获取当前系统名称

    ClassMethod GetOsName()
    {
    	q:($zversion(1) = 2) "WINDOWS "
    	q:($zversion(1) = 1) "VMS"
    	q:($zversion(1) = 3) "UNIX"
    	q:($zv [ "Mac OS X") "MAC"
    	q "OTHER"
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    USER> w ##class(Util.FunctionUtils).GetOsName()
    WINDOWS
    
    • 1
    • 2

    位操作相关 Util.BitUtil

    将字符转为为字符串形式的位串

    ClassMethod LogicalToDisplay(bitint As %Integer)
    {
    	s str = ""
    	for i = 0 : 1 { 
    		q:((2 ** i) > bitint)
    		if $zboolean(bitint, 2**i, 1) {
    			s str = str _ 1
    		} else {
    			s str = str _ 0
    		}
    	}
    	q str
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    USER>w ##class(Util.BitUtil).LogicalToDisplay(1)
    1
    USER>w ##class(Util.BitUtil).LogicalToDisplay(16)
    00001
    USER>w ##class(Util.BitUtil).LogicalToDisplay(15)
    1111
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    将数字转为位2的幂次

    ClassMethod FindSetBits(bitint As %Integer)
    {
    	s bits = "" 
    	while (bitint '= 0) { 
    		s bit = $zlog(bitint) \ $zlog(2)
    		s bits = bit _ " " _ bits
    		s bitint = bitint - (2 ** bit) 
    	} 
    	q bits
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    USER>w ##class(Util.BitUtil).FindSetBits(1024)
    10
    USER>w ##class(Util.BitUtil).FindSetBits(1023)
    0 1 2 3 4 5 6 7 8 9
    
    • 1
    • 2
    • 3
    • 4

    将位串转为十进制

    ClassMethod bit2Decimal(bit)
    {
    	s decimal = 0
    	for i = 1 : 1 : $bitcount(bit) {
    		s num = $bit(bit, i)
    		if (num = 1 ){
    			s decimal = decimal + $zpower(2, i - 1)
    		}
    	}
      	q decimal
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    USER> w ##class(Util.BitUtil).bit2Decimal($factor(10))
    10
    
    • 1
    • 2

    获取数字对应位串

    ClassMethod GetBit(ascii)
    {
    	q $factor(ascii)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>zw ##class(Util.BitUtil).GetBit(10)
    $zwc(128,4)_$c(10,0,0,0)/*$bit(2,4)*/
     
    
    • 1
    • 2
    • 3

    获取字符串对应的二进制位串

    ClassMethod String2Bit(str)
    {
    	q $factor($ascii(str))
    }
    
    • 1
    • 2
    • 3
    • 4
    USER> zw ##class(Util.BitUtil).String2Bit("姚")
    $zwc(128,4)_$c(218,89,0,0)/*$bit(2,4,5,7..9,12,13,15)*/
    
    • 1
    • 2

    位串移位

    • 正数右移
    • 负数左移
    ClassMethod Offset(char, offset)
    {
    	s bit = $factor(0)
    	for i = 64 : -1 : 1{
      		s pos = i - offset
      		if pos > 0 {
          		s $bit(bit, pos) = $bit(char, i)
          	}
      	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    USER>zw ##class(Util.BitUtil).Offset($factor(16),-2)
    $zwc(406,9,6)/*$bit(7)*/
     
    USER>zw ##class(Util.BitUtil).Offset($factor(16),2)
    $zwc(402,8,2)/*$bit(3)*/
    
    • 1
    • 2
    • 3
    • 4
    • 5

    位串移位后转数字

    ClassMethod Offset2Num(char, offset)
    {
    	s bit = ..Offset(char, offset)
    	q ..bit2Decimal(bit)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.BitUtil).Offset2Num($factor(16),2)
    4
    USER>w ##class(Util.BitUtil).Offset2Num($factor(16),-2)
    64
    
    • 1
    • 2
    • 3
    • 4

    加密相关 Util.EncryptionUtils

    MD5加密以16进制输出

    MD5加密Base64输出

    MD加密原生输出

    HMACMD5加密

    SHA1加密

    SHA224加密

    SHA256加密

    SHA384加密

    SHA512加密

    HMACSHA1加密

    HMACSHA224加密

    HMACSHA256加密

    HMACSHA384加密

    HMACSHA512加密

    AESCBCPKCS7Padding加密

    AESCBCPKCS7Padding解密

    AESCBCPKCS5Padding加密

    AESCBCPKCS5Padding解密

    AESEBCZeroPadding加密

    AESEBCZeroPadding解密

    AESECBPKCS5Padding加密

    AESECBPKCS5Padding解密

    AESECBPKCS7Padding加密

    AESECBPKCS7Padding解密

    Base64编码

    Base64解码

    Base64URL编码

    Base32编码

    Base32解码

    URL编码

    URL解码

    Unicode编码

    Unicode解码

    Hex2字节编码

    Hex2字节解码

    将字符转成16进制字符

    UTF8编码

    UTF8解码

    SM3加密

    HMACSM3加密

    SM4加密

    SM4解密

    RSA加密

    RSA解密

    文件相关 FileUtils

    判断文件夹是否存在

    ClassMethod IsDirectoryExists(filePath) As %Boolean
    {
    	q ##class(%File).DirectoryExists(filePath)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.FileUtils).IsDirectoryExists("E:\m\cls\")
    1
    
    • 1
    • 2

    文件夹不存在创建文件夹

    ClassMethod CreateNotExistDir(filePath) As %Boolean
    {
        if ('..IsDirectoryExists(filePath)){
            d ##class(%File).CreateNewDir(filePath, "")
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    USER>d ##class(Util.FileUtils).CreateNotExistDir("E:\m\cls\")
     
    
    • 1
    • 2

    比特转最大单位,支持到MB,

    ClassMethod Byte2MaxUnit(size)
    {
    	if size > 1048576 {
    		s dispSize = $fn(size/1024/1024, ",", 1) _ "MB"
    	} elseif size > 1024 {
    		s dispSize = $fn(size/1024, ",", 1) _" KB"
    	} else {
    		s dispSize = size _" bytes"
    	}
    	q dispSize
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    USER>w ##class(Util.FileUtils).Byte2MaxUnit("1048577")
    1.0MB
    
    • 1
    • 2

    获取文件数据

    ClassMethod GetFileData(filename, showAll = 0)
    {
    	s obj = {}
    	s content = ""
    	if ##class(%File).Exists(filename) {
    		s stream = ##class(%Stream.FileCharacter).%New()
    		s stream.Filename = filename
    		s max = 1048576
    		s size = stream.Size
    		s dispSize = ..Byte2MaxUnit(size)
    		
    		if ('showAll)&&(size > max) {
    			d stream.MoveTo(size - max)
    		}
    		
    		while 'stream.AtEnd {
    			s line = stream.Read()
    			s content = content _ line
    		}
    	}
    	s obj.size = dispSize
    	s obj.content = content
    	s obj.filename = filename
    	q obj
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    继续写入文件

    ClassMethod ContinueWriteFile(filePath, str)
    {
    	s stream = ##class(%FileCharacterStream).%New()
    	s stream.Filename = "E:\m\stack.txt"
    	d stream.MoveToEnd()
    	d stream.WriteLine(str)
    	d stream.SaveStream()
    	d stream.%Close()
    	q $$$OK
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    类方法生成csv文件

    赵新龙提供

    • 返回必须为Json数组
    ClassMethod Json2Csv(className, methodName, filePath, arg...) As %String
    {
    	q:(methodName = "") ""
    	s file = ##class(%FileCharacterStream).%New()
    	s file.Filename = filePath
    	s ret = $classmethod(className, methodName, arg...)
    	
    	#; 字符串Json转对象
    	if '$IsObject(ret)	{
    		s ret = [].%FromJSON(ret)
    	}
    	s iterArr = ret.%GetIterator()
    	while iterArr.%GetNext(.key, .value) {
    		
    		if (columnHeaderFlag = 1 ){
    			#; 列名
    			if (key = 0) {
    				s colNameStr = ""
    				s colObj = value.%GetIterator()
    				while colObj.%GetNext(.iKey, .iValue) {
    					s colNameStr = $s(colNameStr = "" : iKey, 1 : colNameStr _ "," _ iKey)
    				}	
    				d file.WriteLine(colNameStr)	
    			}
    		}
    		
    		#; 属性值
    		s rowStr = ""
    		s iterObj = value.%GetIterator()
    		while iterObj.%GetNext(.iKey, .iValue) {
    			s rowStr = $s(rowStr = "" : iValue, 1 : rowStr _ "," _ iValue)
    		}
    		d file.WriteLine(rowStr)
    	}
     	d file.%Save()
     	q $$$OK
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    Query生成csv文件

    ClassMethod Query2Csv(className, queryName, filePath, arg...)
    {
    	s file = ##class(%FileCharacterStream).%New()
    	s file.Filename = filePath
    	
    	s array = []
    	s rs = ##class(%ResultSet).%New()
    	s rs.ClassName = className
    	s rs.QueryName = queryName
    	d rs.Execute(arg...)
    
    	#; 列名
    	s colStr = ""
    	for i = 1 : 1 : rs.GetColumnCount(){
    		s columnName = rs.GetColumnName(i)
    		s colStr = $s(colStr = "" : columnName, 1 : colStr _ "," _ columnName)
    	}
    	d file.Write(colStr)
    	
    	#; 属性值
    	while (rs.Next()) {
    		s valStr = ""
    		for i = 1 : 1 : rs.GetColumnCount(){
    			s columnName = rs.GetColumnName(i)
    			s val = rs.Data(columnName)
    			s valStr = $s(valStr = "" : val, 1 : valStr _ "," _ val)	
    		}
    		d file.Write($c(10) _ valStr)
    	}
    	
    	d file.%Save()
    	q $$$OK
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    把文件转成Base64的字符流对象

    ClassMethod File2Base64(path) As %Stream.GlobalCharacter
    {
        #dim sgc As %Stream.GlobalCharacter
        s sgc = ##class(%Stream.GlobalCharacter).%New()
        s path = ##Class(%File).NormalizeFilename(path)
        throw:('##class(%File).Exists(path)) ##class(%Exception.SystemException).%New("文件不存在")
        s img = ##class(%FileBinaryStream).%New()  
        s img.Filename = $g(path)   
        s byteList = img.Read(12288)      
        while(byteList'=""){ 
            s baseStr = ##class(%SYSTEM.Encryption).Base64Encode(byteList)
            d sgc.Write(baseStr)
            s byteList = ""         
            s byteList = img.Read(12288)
        }     
        d img.%Close()  
        q sgc
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    把Base64流对象转为对应文件

    ClassMethod Base642File(sgc, path As %String) As %Boolean
    {
    	throw:('$IsObject(sgc)) ##class(%Exception.SystemException).%New("请传入对象")
        s path = ##Class(%File).NormalizeFilename(path)
        s img = ##class(%FileBinaryStream).%New()
        s img.Filename = $g(path)
        if ($IsObject(sgc)) {   ;sgc字符流
            d sgc.Rewind()
            while ('sgc.AtEnd){         
                s baseStr = sgc.Read(16814) ;不能用16k
                s byteList = ##class(%SYSTEM.Encryption).Base64Decode(baseStr)
                d img.Write(byteList)  
            }
        }else{  ;sgc字符串
            s byteList = ##class(%SYSTEM.Encryption).Base64Decode(sgc)
            d img.Write(byteList)
        }
        d img.SaveStream()
        d img.%Close()
        s img = ""
    
        q $$$OK
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    USER>w ##class(Util.FileUtils).Base642File(##class(Util.FileUtils).File2Base64("E:\m\CsvFile.csv"),"E:\m\CsvFile5.csv")
    1
    
    • 1
    • 2

    查看目标路径所有文件

    ClassMethod QueryDirAllFile(dir As %String = "", wildcard As %String = "", sort As %String = "Name")
    {
        s stmt = ##class(%SQL.Statement).%New()
        s sc = stmt.%PrepareClassQuery("%File", "FileSet")
        $$$ThrowOnError(sc)    
        s rs = stmt.%Execute(dir, wildcard, sort) 
        while rs.%Next() {
            w rs.%Get("Name")
            w " ", rs.%Get("Type")
            w " ", rs.%Get("Size"),!
        }
        q $$$OK
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    USER> w ##class(Util.FileUtils).QueryDirAllFile("E:\temp", "*.xml", "Size")
    E:\temp\testPerson.xml F 117
    E:\temp\samplePerson.xml F 327
    E:\temp\xmlnewtest.xml F 351
    E:\temp\Person.xml F 259854
    E:\temp\tempPerson.xml F 259854
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    递归目录所有文件夹。

    ClassMethod QueryAllFilesInDir(directory As %String = "")
    {
        s stmt = ##class(%SQL.Statement).%New()
        s sc = stmt.%PrepareClassQuery("%File", "FileSet")
    	$$$ThrowOnError(sc)   
        s rs = stmt.%Execute(directory) 
        while rs.%Next() {
            s name = rs.%Get("Name")
            s type = rs.%Get("Type")
            
            if (type = "F") {
                w name,!
            } elseif (type = "D"){
                d ..QueryAllFilesInDir(name)
            }
        }
        q $$$OK
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    USER>w ##class(Util.FileUtils).QueryAllFilesInDir("E:\temp")
    E:\temp\autocommit.sh
    E:\temp\config.txt
    E:\temp\data2.txt
    E:\temp\game.jpg
    E:\temp\Git.jpg
    E:\temp\image\Git.png
    E:\temp\image\python.png
    E:\temp\image\yaoxin.pdf
    E:\temp\myfile.txt
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    查询所有盘符

    ClassMethod QueryDrives()
    {
        s stmt = ##class(%SQL.Statement).%New()
        s sc = stmt.%PrepareClassQuery("%File","DriveList")
    	$$$ThrowOnError(sc)  
        
        s rs = stmt.%Execute(1) 
        while rs.%Next() {
            w rs.%Get("Drive"),!
        }
        q $$$OK
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    USER>d ##class(Util.FileUtils).QueryDrives()
    c:\
    d:\
    e:\
    f:\
    g:\
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    处理输入文件,对内容执行替换,并将新内容写入输出文件

    ClassMethod ProcessFile(inputfilename As %String = "", outputfilename As %String = "")
    {
        #; 确保文件名被传入
        if (inputfilename = "") || (outputfilename = "") {
      		throw ##class(%Exception.SystemException).%New("文件不能为空")
        }
    
        #; 打开输入文件进行读取
        s inputfile = ..SetUpInputFile(inputfilename)
        q:(inputfile = $$$NULLOREF)
        
        #; 打开输出文件进行写入
        s outputfile = ..SetUpOutputFile(outputfilename)
        q:(outputfile = $$$NULLOREF)
    
    
        #; 循环输入文件中的每一行
        #; 1. 从文件中读出一行
        #; 2. 调用ProcessLine()来处理该行
        #; 3. 将新的行内容写入输出文件
        while (inputfile.AtEnd = 0) {
    		set line = inputfile.ReadLine(,.sc)
    		$$$ThrowOnError(sc)  
    		s newline = ..ProcessLine(line)
    		d outputfile.WriteLine(newline)
        }
    
    	#; 关闭输入和输出文件
    	d inputfile.Close()
    	d outputfile.Close()
    	q $$$OK
    }
    
    /// desc:设置输入文件,创建文件对象,打开文件RU,返回文件对象
    ClassMethod SetUpInputFile(filename As %String) As %File
    {
        s fileObj = ##class(%File).%New(filename)
        s status = fileObj.Open("RU")
       	$$$ThrowOnError(sc) 
        q fileObj
    }
    
    /// desc:设置输出文件,创建文件对象,打开文件WSN,返回文件对象
    ClassMethod SetUpOutputFile(filename As %String) As %File
    {
        s dir=##class(%File).GetDirectory(filename)
        d ##class(%File).CreateDirectoryChain(dir)
        s fileObj = ##class(%File).%New(filename)
        s status = fileObj.Open("WSN")
    	$$$ThrowOnError(sc) 
        q fileObj
    }
    
    /// desc:处理一行,使用$replace对该行执行一系列替换,内容自定义
    ClassMethod ProcessLine(line As %String = "") As %String
    {
        s newline = line
        s newline = $replace(newline, "yx", "yaoxin")
        q newline
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    USER>d ##class(Util.FileUtils).ProcessFile("E:\m\input.txt","E:\m\output.txt")
    
    • 1

    获取流下载连接加密OID

    ClassMethod DownloadStream(pFilename As %String, pDocName As %String, pCharSet As %String)
    {
    	s stream = ##class(%FileBinaryStream).%New()
    	s sc = stream.LinkToFile(pFilename)
    	d stream.SetAttribute("ContentDisposition","attachment; filename="_pDocName)
    	d stream.SetAttribute("CharSet",pCharSet)
    	s sc = stream.%Save()
    	s oid = stream.%Oid()
    
    	#; 根据SessionLicense,加密,不同浏览器不互通。使用对称加密算法
    	s str = ##class(%CSP.Page).Encrypt(oid)
    	q str
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    w ##class(Util.FileUtils).DownloadStream("E:\temp\test\yx.xml.xml","yx.xml","")
    
    • 1

    创建空文件,任意后缀

    ClassMethod CreateFile(filename)
    {
        s fileObj = ##class(%File).%New(filename)
        s sc = fileObj.Open("SN")
    	$$$ThrowOnError(sc) 
        q fileObj
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    w ##class(Util.FileUtils).CreateFile("E:\temp\test\yx.abc")
    
    • 1

    给定一个目录名,返回从根节点开始一直到最后一个目录名的子目录

    ClassMethod QueryParseDirectory(dir)
    {
    	s array = []
    	s rs = ##class(%ResultSet).%New()
    	s rs.ClassName = "%File"
    	s rs.QueryName = "ParseDirectory"
    	d rs.Execute(dir)
    	while (rs.Next()) {
    		s name = rs.Get("Name")
    		s isDrive = rs.Get("IsDrive")
    		s directory = rs.Get("Directory")
    		
    		s obj = {}
    		s obj.name = name
    		s obj.isDrive = isDrive
    		s obj.directory = directory
    		d array.%Push(obj)
    	}
    	q array
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    USER>w ##class(Util.FileUtils).QueryParseDirectory("E:\temp\test\").%ToJSON()
    [{"name":"E:","isDrive":"1","directory":"E:\\"},{"name":"temp","isDrive":"0","directory":"E:\\temp\\"},{"name":"test","isDrive":"0","directory":"E:\\temp\\test\\"}]
    
    • 1
    • 2

    JSON相关 JSONUtils

    反转json数组,倒序数组

    ClassMethod ReverseArrayJson(array)
    {
    	s newArr = []
    	for i = (array.%Size() - 1) : -1 : 0 {
    		s obj = array.%Get(i)
    		d newArr.%Push(obj)
    	}
    	q newArr
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    USER>w ##class(Util.JsonUtils).ReverseArrayJson([{"name":"yx1"},{"name":"yx2"}]).%ToJSON()
    [{"name":"yx2"},{"name":"yx1"}]
    
    • 1
    • 2

    Json转Xml

    马浩提供

    ClassMethod Json2Xml(pJSONString As %String, pRootElementName As %String, Output pXMLString As %String) As %Status
    {
        s sc = $system.Status.OK()
        try
        {
    		s obj = ##class(%Library.DynamicObject).%FromJSON(pJSONString)
    		
    		s pXMLString = ""1.0"" encoding=""utf-8""?>" _ $c(13,10)
    		s pXMLString = pXMLString_  "<" _ pRootElementName _ ">" _ $c(13,10)
    
    		s tSC = ..ConvertFromJSONObjectToXMLString(obj, .pXMLString)
    		q:$System.Status.IsError(tSC)
    
    		s pXMLString = pXMLString _ " _ pRootElementName _ ">" _ $c(13,10)
        } catch (e) {
            s sc = e.AsStatus()
        }
        
        q sc
    }
    
    ClassMethod ConvertFromJSONObjectToXMLString(pJSONObject As %Library.DynamicAbstractObject, Output pXMLString As %String) As %Status
    {
    	s sc = $system.Status.OK()
    	try
    	{
    	    set iterator = pJSONObject.%GetIterator()
    	    
    	    while iterator.%GetNext(.key, .value)
    	    {
    	        s tXMLKey = $tr(key, " ")
    	        s pXMLString = pXMLString_"<" _ tXMLKey _ ">"
    	        
    	        if value '= ""
    	        {
    	            if '$IsObject(value)
    	            {
    	                s pXMLString = pXMLString _ value
    	            } else {
    	                s pXMLString = pXMLString _ $c(13,10)
    	                
    	                if value.%ClassName() = "%DynamicObject"
    	                {
    	                    s sc = ..ConvertFromJSONObjectToXMLString(value, .pXMLString)
    	                    q:$System.Status.IsError(sc)                            
    	                } elseif value.%ClassName() = "%DynamicArray" {
    	                    s arrayIterator = value.%GetIterator()
    	                                
    	                    while arrayIterator.%GetNext(.arrayKey, .arrayValue)
    	                    {
    	                        s pXMLString = pXMLString _ "<" _ tXMLKey _ "Item key=""" _ arrayKey _ """>"_ $c(13,10)
    	                        if '$IsObject(arrayValue)
    	                        {
    	                            s pXMLString=pXMLString_arrayValue
    	                        } else {                                    
    	                            s sc = ..ConvertFromJSONObjectToXMLString(arrayValue, .pXMLString)
    	                            q:$System.Status.IsError(sc)                            
    	                        }
    	                        s pXMLString=pXMLString _ " _ tXMLKey _ "Item>" _ $c(13,10)
    	                    }
    	                    q:$System.Status.IsError(sc)
    	                }
    	            }
    	        }
    	        
    	        s pXMLString = pXMLString _ " _ tXMLKey _ ">" _ $c(13,10)
    	    } 
    	}
    	catch (e)
    	{
    	    s sc = e.AsStatus()
    	}
    
    	q sc
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    /// w ##class(Util.ObjectUtils).Main()
    ClassMethod Main()
    {
    	s obj = {"name" : "yx", "age" : 18}
    	s sc = ..Json2Xml(obj.%ToJSON(), "Root", .xml)
    	q:$System.Status.IsError(sc)
    	q xml
    }
    
    /// w ##class(Util.ObjectUtils).Main1()
    ClassMethod Main1()
    {
    	s obj = {"name" : "yx", "age" : 18, "row":[{"class" : "math", "score" : 80},{"class" : "english", "score" : 70}]}
    	s sc = ..Json2Xml(obj.%ToJSON(), "Root", .xml)
    	q:$System.Status.IsError(sc)
    	q xml
    }
    
    /// w ##class(Util.ObjectUtils).Main2()
    ClassMethod Main2()
    {
    	s obj = {"name" : "yx", "age" : 18, "row": ["math", "chinese", "english"] }
    	s sc = ..Json2Xml(obj.%ToJSON(), "Root", .xml)
    	q:$System.Status.IsError(sc)
    	q xml
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    USER>w ##class(Util.ObjectUtils).Main()
    <?xml version="1.0" encoding="utf-8"?>
    <Root>
    <name>yx</name>
    <age>18</age>
    </Root>
     
    USER>w ##class(Util.ObjectUtils).Main1()
    <?xml version="1.0" encoding="utf-8"?>
    <Root>
    <name>yx</name>
    <age>18</age>
    <row>
    <rowItem key="0">
    <class>math</class>
    <score>80</score>
    </rowItem>
    <rowItem key="1">
    <class>english</class>
    <score>70</score>
    </rowItem>
    </row>
    </Root>
    
    USER>w ##class(Util.ObjectUtils).Main2()
    <?xml version="1.0" encoding="utf-8"?>
    <Root>
    <name>yx</name>
    <age>18</age>
    <row>
    <rowItem key="0">
    math</rowItem>
    <rowItem key="1">
    chinese</rowItem>
    <rowItem key="2">
    english</rowItem>
    </row>
    </Root>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    合并JSON数组 - 不去重

    ClassMethod ConcatArrays(pArgs...) As %DynamicArray
    {
        s array = ##class(%DynamicArray).%New()
        for i = 1 : 1 : pArgs {
            s arg = pArgs(i)
            if ($isObject(arg) && arg.%IsA("%DynamicArray")) {
                s iter = arg.%GetIterator()
                while iter.%GetNext(.key, .value) {
                    d array.%Push(value)
                }
            } else {
                d array.%Push(arg)
            }
        }
        ret array
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    USER>w ##class(Util.JsonUtils).ConcatArrays([1,2],[3,4],[3,4,5,6]).%ToJSON()
    [1,2,3,4,3,4,5,6]
    
    • 1
    • 2

    合并JSON数组 - 去重

    ClassMethod SetArrays(pArgs...) As %DynamicArray
    {
        s array = ##class(%DynamicArray).%New()
        for i = 1 : 1 : pArgs {
            s arg = pArgs(i)
            if ($isObject(arg) && arg.%IsA("%DynamicArray")) {
                s iter = arg.%GetIterator()
                while iter.%GetNext(.key, .value) {
    	            s str = array.%ToJSON()
    	            s str = $e(str, 2, * - 1)
    	            s list = $lfs(str)
    	         	continue:($lf(list, value))
                    d array.%Push(value)
                }
            } else {
                d array.%Push(arg)
            }
        }
        ret array
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    USER>w ##class(Util.JsonUtils).SetArrays([1,2],[3,4],[3,4,5,6]).%ToJSON()
    [1,2,3,4,5,6]
    
    • 1
    • 2

    JSON数组根据分隔符转字符串

    ClassMethod Array2String(array, del = ",") As %String
    {
    	 s str = array.%ToJSON()
    	 s str = $e(str, 2, * - 1)
    	 s list = $lfs(str)
    	 q $lts(list, del)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##class(Util.JsonUtils).Array2String([1, 2, 3], "^")
    1^2^3
    
    • 1
    • 2
    • 内部数组转字符串
    ClassMethod List2String(list, del = ",") As %String
    {
    	 q $lts(list, del)
    }
    
    • 1
    • 2
    • 3
    • 4
    USER>w ##class(Util.JsonUtils).List2String($lb(1,2,3), "^")
    1^2^3
    
    • 1
    • 2

    Xml相关 XmlUtils

    Xml转Json

    马浩提供

    ClassMethod Xml2Json(pInput As %Stream.Object) As %Stream.Object
    {
    	s sc = $System.Status.OK()
    	try { 
    		s xslt = ..GetXData("XML2JSON")
    		s sc = ##class(%XML.XSLT.Transformer).TransformStream(pInput, xslt, .result)
    		ret result
    	} catch (e) {
    		s tSC =e.AsStatus()
    	}
    
    	d $System.Status.DisplayError(tSC)
    }
    
    ClassMethod GetXData(name) As %Stream.TmpCharacter [ CodeMode = expression ]
    {
    ##class(%Dictionary.XDataDefinition).IDKEYOpen($classname(), name).Data
    }
    
    XData XML2JSON
    {
    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output method="text"/>
     <xsl:template match="/">{
        <xsl:apply-templates select="*"/>}
    </xsl:template>
     <!-- Object or Element Property-->
     <xsl:template match="*">
        "name()"/>" :<xsl:call-template name="Properties">
       <xsl:with-param name="parent" select="'Yes'"> </xsl:with-param>
      </xsl:call-template>
     </xsl:template>
     <!-- Array Element -->
     <xsl:template match="*" mode="ArrayElement">
      <xsl:call-template name="Properties"/>
     </xsl:template>
     <!-- Object Properties -->
     <xsl:template name="Properties">
      <xsl:param name="parent"/>
      <xsl:variable name="childName" select="name(*[1])"/>
      <xsl:choose>
       <xsl:when test="not(*|@*)">
        <xsl:choose>
         <xsl:when test="$parent='Yes'">
          <xsl:text>&quot;</xsl:text>
          <xsl:value-of select="."/>
          <xsl:text>&quot;</xsl:text>
         </xsl:when>
         <xsl:otherwise>"name()"/>":"."/>"</xsl:otherwise>
        </xsl:choose>
       </xsl:when>
       <xsl:when test="count(*[name()=$childName]) > 1">{
    	   ""/>" :[<xsl:apply-templates select="*" mode="ArrayElement"/>] }</xsl:when>
       <xsl:otherwise>{
                <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="*"/>
    	}</xsl:otherwise>
      </xsl:choose>
      <xsl:if test="following-sibling::*">,</xsl:if>
     </xsl:template>
     <!-- Attribute Property -->
     <xsl:template match="@*">"name()"/>" : "."/>",
    </xsl:template>
    </xsl:stylesheet>
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    USER> w ##class(Util.ObjectUtils).Xml2Json(##class(Util.ObjectUtils).Main()).Read()
    {
     
        "Root" :{
     
        "name" :"yx",
        "age" :"18"
            }}
     
    USER> w ##class(Util.ObjectUtils).Xml2Json(##class(Util.ObjectUtils).Main2()).Read()
    {
     
        "Root" :{
     
        "name" :"yx",
        "age" :"18",
        "row" :{
               "rowItem" :[{
                "key" : "0",
     
            },{
                "key" : "1",
     
            },{
                "key" : "2",
     
            }] }
            }}
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    流相关 Util.StreamUtils

    完整读取流

    ClassMethod ReadAllStream()
    {
    	#; 写入最大字符串
    	#dim mStream as %FileCharacterStream = ##class(%FileCharacterStream).%New()
    
    	for i = 1 : 1 : $SYSTEM.SYS.MaxLocalLength() {
    		d mStream.Write(i)
    	}
    	
    	#; 完整读取流
    	d mStream.Rewind()
    	while (mStream.AtEnd = 0) {
    		w mStream.Read(),! 
    	}
    	
    	d mStream.Rewind()
    	w mStream.Read(.len),! 
    	w "读取流最大长度!:" _ len,!
    	w "流字节大小:"_ mStream.FileBinarySize(),!
    	q $$$OK
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    配置相关 Util.ConfigUtils

    未定义变量时不会生成错误

    ClassMethod SetUndefined() As %String
    {
    	s ret = ##class(%SYSTEM.Process).Undefined(2)
    	s yx = b
    	q ret
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    USER>w ##class(Util.ConfigUtils).SetUndefined()
    0
    
    • 1
    • 2

    获取系统配置参数值

    • DATEFORMAT,YEAROPTION,TIMEFORMAT,TIMEPRECISION,NUMERICGROUPSIZE,
    • DECIMALSEPARATOR,NUMERICGROUPSEPARATOR,DATESEPARATOR,TIMESEPARATOR,PLUSSIGN,
    • MINUSSIGN,AM,PM,NOON,MIDNIGHT,
    • MONTHABBR,MONTHNAME,WEEKDAYABBR,WEEKDAYNAME,DATEMINIMUM,
    • DATEMAXIMUM
    ClassMethod GetSystemConfig(params) As %String
    {
    	q ##class(%SYS.NLS.Format).GetFormatItem(params)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    USER>w ##class(Util.ConfigUtils).GetSystemConfig("MinusSign")
    -
    USER>w ##class(Util.ConfigUtils).GetSystemConfig("DecimalSeparator")
    .
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    【谷粒商城 - k8s、devOps专栏】
    图像预处理技术与算法
    企业内部安全与风控管理图解
    新版IDEA内置Docker插件不支持远程Build镜像的环境集成
    关于 Lucene 搜索语法与分词的浅显研究
    面试 — 快手(后端开发)
    解锁电力安全密码:迅软DSE助您保护机密无忧
    智慧公厕建设,要以技术为支撑、体验为目的、业务为驱动
    《OpenCV4快速入门》------函数摘要
    【每日一题Day47】LC1774最接近目标价格的甜点成本 | 回溯 哈希表
  • 原文地址:https://blog.csdn.net/yaoxin521123/article/details/127857851