重要:希望可以和大家共建工具类,有想提供工具方法或共建的可以留言。
分享,开源,利他,创造价值,分享学习,一起成长,相伴前行。
StringUtilsClassMethod GetStringMaxLength() As %Integer
{
q $system.SYS.MaxLocalLength()
}
USER>w ##class(Util.StringUtils).GetStringMaxLength()
3641144
$$$NOClassMethod IsChinese(str As %String) As %Boolean
{
if 1 = $match(str,"(?x)[\u4e00-\u9fa5]*#中文正则表达式") {
q $$$YES
} else {
q $$$NO
}
}
ClassMethod IsChineseChar(str As %String) As %Boolean
{
s asc = $a(str)
if (asc < $zhex("9fa5"))&&(asc > $zhex("4e00")){
q $$$YES
} else {
q $$$NO
}
}
USER> w ##class(Util.StringUtils).IsChinese("姚鑫")
1
USER> w ##class(Util.StringUtils).IsChinese("姚鑫+")
0
ClassMethod Trim(str As %String) As %String
{
q $e(str, $locate(str, "[^\s]"), $locate(str, "\s*$") - 1)
}
ClassMethod Trim1(str As %String) As %String [ Language = basic ]
{
return Trim(str)
}
ClassMethod Trim2(str As %String) As %String
{
q $zstrip(str, "<>", " ")
}
ClassMethod Trim3(str As %String) As %String
{
s target = ""
&sql(
select TRIM(both ' ' from :str) into :target
)
q target
}
USER>w ##class(Util.StringUtils).Trim(" 姚 鑫 ")
姚 鑫
USER>w ##class(Util.StringUtils).Trim1(" 姚 鑫 ")
姚 鑫
USER>w ##class(Util.StringUtils).Trim2(" 姚 鑫 ")
姚 鑫
USER>w ##class(Util.StringUtils).Trim3(" 姚 鑫 ")
姚 鑫
ClassMethod DeleteSpace(str As %String) As %String
{
s str = $lts($lfs(str," "),"")
q str
}
USER>w ##class(Util.StringUtils).DeleteSpace(" 姚 鑫 ")
姚鑫
ClassMethod Repeat(target As %String, num As %Integer) As %String
{
s str = ""
s $p(str, target, num) = target
q str
}
USER>w ##class(Util.StringUtils).Repeat("yx",5)
yxyxyxyxyx
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
}
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
}
USER>w ##class(Util.StringUtils).IsContain("1,11,222,333","1",",")
1
USER>w ##class(Util.StringUtils).IsContain1("1,11,222,333","11",",")
1
ClassMethod PrefixMatch(str As %String, target As %String) As %Boolean
{
if ($locate(str, "^"_target) > 0){
q $$$YES
}
q $$$NO
}
USER>w ##class(Util.StringUtils).PrefixMatch("1123*456xzc","123*")
0
USER>w ##class(Util.StringUtils).PrefixMatch("1123*456xzc","1123*")
1
ClassMethod SuffixMatch(str As %String, target As %String) As %Boolean
{
if ($locate(str, target_"$") > 0){
q $$$YES
}
q $$$NO
}
USER>w ##class(Util.StringUtils).SuffixMatch("1123*456xzc","zxc")
0
USER>w ##class(Util.StringUtils).SuffixMatch("1123*456xzc","xzc")
1
ClassMethod GetTypeOf(str) As %String
{
q [(str)].%GetTypeOf(0)
}
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
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
}
}
USER>w ##class(Util.StringUtils).IsIdentityCard("11111119111111111X")
1
USER>w ##class(Util.StringUtils).IsIdentityCard("11111119111111111a")
0
ClassMethod RemoveLetter(str As %String) As %String
{
s str = $zstrip(str, "*ANP")
q str
}
USER> w ##class(Util.StringUtils).RemoveLetter("2李4lll")
李
USER>w ##class(Util.StringUtils).RemoveLetter("hello world 欢迎世界")
欢迎世界
ClassMethod GetStringOfNumber(str As %String) As %String
{
s str = $zstrip(str, "*E'N")
q str
}
USER>w ##class(Util.StringUtils).GetStringOfNumber("AS1DAS姚鑫1234511A2S")
112345112
ClassMethod UnicodeToString(unicode As %String) As %Boolean
{
s ascii = $zhex(unicode)
q $c(ascii)
}
USER>w ##class(Util.StringUtils).UnicodeToString("59da")
姚
^pinyinGlobalClassMethod 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
}
USER>w ##class(Util.StringUtils).Chinese2Spell("姚鑫")
yaoxin
ClassMethod IsPrefixNum(str As %String) As %Boolean
{
q $isvalidnum($e(str))
}
USER>w ##class(Util.StringUtils).IsPrefixNum("yx")
0
USER>w ##class(Util.StringUtils).IsPrefixNum("1yx")
1
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)
}
USER>w ##class(Util.StringUtils).Angle2HalfAngle("!")
!
USER>w ##class(Util.StringUtils).Angle2HalfAngle(",")
,
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
}
USER>w ##class(Util.StringUtils).GetStringByte("姚鑫1A“”'")
11
USER>w ##class(Util.StringUtils).GetStringByte(".。")
3
1, 其它返回0ClassMethod IsFullAngle(word) As %Boolean
{
/* 汉字范围 */
q:(($a(word) >= 19968) && ($a(word) <= 40869)) $$$OK
q:("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890`!@#$%^&*()_+|\{}[]"'。《》/?:;¥{},!、" [ word) $$$OK
q $$$NO
}
USER> w ##class(Util.StringUtils).IsFullAngle("A")
0
USER>w ##class(Util.StringUtils).IsFullAngle("A")
1
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
}
USER>w ##class(Util.StringUtils).GetStringSplit("全角字母为2个长度",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
}
USER>w ##class(Util.StringUtils).ReplaceStr("1^2^3^4^5", "^", 4, "a")
^^^a^
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
}
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
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
}
USER> w ##class(Util.StringUtils).Camel2Underline("Red1YellowGreen23BlackWhite")
Red1_Yellow_Green23_Black_White
ClassMethod lb2String(lb)
{
q $$Format^%qcr(lb, 1)
}
USER> w ##class(Util.StringUtils).lb2String($lb(1,2,3,,"","yx"))
$lb(1,2,3,,"","yx")
ClassMethod FormatString(string As %String, flags As %Integer = 1, ByRef overflow As %Boolean) As %String
{
q $$Quote^%qcr(string, 0, .overflow, flags)
}
USER>w ##class(Util.StringUtils).FormatString($lb(1,2,3,,"","yx"))
$lb(1,2,3,,"","yx")
ClassMethod Center(str As %String = "", width As %Integer = 80) As %String
{
q $j(str, ($l(str) + width) \ 2)
}
USER> w ##class(Util.StringUtils).Center("yx",4)
yx
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
}
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
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
}
USER>w ##class(Util.StringUtils).IsChineseUtf8($zcvt("姚", "O", "UTF8"))
1
USER>w ##class(Util.StringUtils).IsChineseUtf8("姚")
0
NumberUtilsClassMethod UpInteger(number As %Integer)
{
q ##class(%SYSTEM.SQL).CEILING(number)
}
USER> w ##class(Util.NumberUtils).UpInteger(0.3)
1
ClassMethod DownInteger(number As %Integer)
{
q $normalize(number, -1)
}
ClassMethod DownInteger1(number As %Integer)
{
q $system.SQL.FLOOR(number)
}
USER>w ##class(Util.NumberUtils).DownInteger(32.3)
32
w ##class(Util.NumberUtils).DownInteger1(32.3)
32
- ,.ClassMethod GetNumLen(number As %Integer) As %Integer
{
if ('$isvalidnum(number)){
throw ##class(%Exception.General).%New("不是数字")
}
q $l($zstrip(+number,"*E'N"))
}
USER>w ##class(Util.NumberUtils).GetNumLen(32.3)
3
ClassMethod IsInteger(str As %String) As %Boolean
{
q:'$isvalidnum(str) $$$NO
q:(+str [ ".") $$$NO
q $$$YES
}
ClassMethod IsInteger1(str As %String) As %Boolean
{
q:($number(str, "I") = "") $$$NO
q $$$YES
}
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
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)
}
USER>w ##class(Util.NumberUtils).GetMaxNumber("1,2,3.1,5500.56,6.9,100,100.1")
5500.56
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
}
USER>w ##class(Util.NumberUtils).GetSuffixNumber("abcdef12a1")
12
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
}
USER> w ##class(Util.NumberUtils).IsSame("1^2^3", "3^2^1^0")
0
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)
}
USER>w ##class(Util.NumberUtils).Deci2Fra(0.125)
1/8
N位补0ClassMethod ZeroPadding(target, num)
{
q $tr($j(target, num), " ", "0")
}
USER>w ##class(Util.NumberUtils).ZeroPadding(1234,9)
000001234
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
}
ClassMethod ConvertMoneyFomat1(num, zeroNum)
{
q $fn(num, ",", zeroNum)
}
USER>w ##class(Util.NumberUtils).ConvertMoneyFomat(200000,2)
200,000.00
USER>w ##class(Util.NumberUtils).ConvertMoneyFomat1(200000,2)
200,000.00
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
}
USER>w ##class(Util.NumberUtils).Num2Rmb("1119876543210.123456789")
壹万壹仟壹佰玖拾捌亿柒仟陆佰伍拾肆万叁仟贰佰壹拾零元贰角壹分
USER>w ##class(Util.NumberUtils).Num2Rmb("-111980000.01")
负壹亿壹仟壹佰玖拾捌万壹分
USER>w ##class(Util.NumberUtils).Num2Rmb("100")
壹佰整
周志强提供
ClassMethod Root(num, power)
{
q +$fn(num ** (1 / power), "N", 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
隋国阳提供
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
}
USER>w ##class(Util.NumberUtils).Root1(27,3)
3
USER>w ##class(Util.NumberUtils).Root1(81,4)
3
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)
}
USER>w ##class(Util.NumberUtils).Root2(8,3)
2
USER>w ##class(Util.NumberUtils).Root2(1024,10)
2
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
}
USER>w ##class(Util.NumberUtils).BigNumAdd(102411111111111111111,108099999999999999999)
00-6311111111111111100
ClassMethod GenCryptToken()
{
q ##class(%SYSTEM.Encryption).GenCryptToken()
}
USER>w ##class(Util.NumberUtils).GenCryptToken()
96718613
Util.DateUtilsClassMethod GetCurrentAge(date As %Date = "") As %Integer
{
s age = $s(date = "" : "", 1 : ($zd($h, 8) - $ZD(date, 8) \ 10000))
q age
}
USER>w ##class(Util.DateUtils).GetCurrentAge((+$h-3650))
9
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
}
USER>w ##class(Util.DateUtils).GetMonthsAge("1990-04-25")
391
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
}
USER> w ##class(Util.DateUtils).GetDaysAge("1990-04-25")
11890
ClassMethod GetDiffSecond(date1 As %DateTime, date2 As %DateTime) As %Integer
{
s num = $SYSTEM.SQL.DATEDIFF("second", date1, date2)
q num
}
USER>w ##class(Util.DateUtils).GetDiffSecond("1990-04-25 21:00:00","1990-04-25 21:00:10")
10
ClassMethod GetDiffMinute(date1 As %DateTime, date2 As %DateTime) As %Integer
{
s num = $SYSTEM.SQL.DATEDIFF("mi", date1, date2)
q num
}
USER>w ##class(Util.DateUtils).GetDiffMinute("1990-04-25 21:00:10","1990-04-26 21:00:20")
1440
ClassMethod GetLastDay(date As %Date) As %Integer
{
s date = $SYSTEM.SQL.LASTDAY(date)
q $zd(date, 3)
}
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
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
}
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
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
}
USER>w ##class(Util.DateUtils).DateTime2Timestamp(0)
1668340100
USER>w ##class(Util.DateUtils).DateTime2Timestamp()
1668340101867
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)
}
USER 2e1>zw ##class(Util.DateUtils).GetBeforeMothday()
$lb("2022-10-01","2022-10-31")
ClassMethod GetLastMonthToday() As %String
{
q $SYSTEM.SQL.DATEADD("mm", -1, +$h)
}
USER>w ##class(Util.DateUtils).GetLastMonthToday()
2022-10-13 00:00:00
ClassMethod GetMonthDay() As %String
{
q $SYSTEM.SQL.DAYOFMONTH(+$H)
}
USER>w ##class(Util.DateUtils).GetMonthDay()
13
N个小时ClassMethod GetAddHour(hour) As %String
{
q $SYSTEM.SQL.DATEADD("hh", hour, $h)
}
USER>w ##class(Util.DateUtils).GetAddHour(1)
2022-11-13 20:55:59
ClassMethod GetWeekOfYear(date) As %String
{
q $SYSTEM.SQL.WEEK(date)
}
USER> w ##class(Util.DateUtils).GetWeekOfYear("2020-01-01")
1
USER>w ##class(Util.DateUtils).GetWeekOfYear(+$h)
47
ClassMethod FormatDate(date, toFormat, fromFormt)
{
s fDate = $system.SQL.TODATE(date, toFormat)
s tDate = $system.SQL.TOCHAR(fDate, fromFormt)
q tDate
}
USER>w ##Class(Util.DateUtils).FormatDate("20/04/2022", "DD/MM/YYYY", "YYYY/MM/DD")
2022/04/2
ClassMethod IsValidDate(date, toFormat, fromFormt) As %Boolean
{
s sc = ##class(%Library.TimeStamp).IsValid(date)
q:($$$ISERR(sc)) $$$NO
q $$$YES
}
USER>w ##Class(Util.DateUtils).IsValidDate("2022-04-25")
1
USER>w ##Class(Util.DateUtils).IsValidDate("20/04/2022")
0
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 ""
}
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
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
}
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"}]
SQL相关 Util.SqlUtlsClassMethod IsIntrans() As %Boolean
{
n SQLCODE
&sql(%INTRANSACTION)
q:'SQLCODE $$$YES
q $$$NO
}
USER>w ##class(Util.SqlUtls).IsIntrans()
0
USER>ts
TL1:USER>w ##class(Util.SqlUtls).IsIntrans()
1
TL1:
IDClassMethod GetMaxID(table)
{
&sql(SELECT MAX(%ID) INTO :maxID FROM Sample.Person )
q maxID
}
USER>w ##class(Util.SqlUtls).GetMaxID()
215
ClassMethod ValidateIndices()
{
s sc = ##class(Sample.Person).%ValidateIndices("",1,2,1)
if sc=1 {
w !,"成功索引验证/更正"
} else {
w !,"索引验证/更正失败",!
d $System.Status.DisplayError(sc)
}
q ""
}
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
...
成功索引验证/更正
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 ""
}
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
ClassMethod IsTableExists(table)
{
q ##class(%SYSTEM.SQL.Schema).TableExists(table)
}
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 _" 是有效的表名称"
}
}
USER>w ##class(Util.SqlUtls).IsValidTableName("#asdasasdas")
表名包含无效字符
USER>w ##class(Util.SqlUtls).IsValidTableName("asdasasdas")
asdasasdas 是有效的表名称
ClassMethod GetFieldMaxVal(integer, decimal)
{
q $$maxval^%apiSQL(integer, decimal)
}
USER> w ##class(Util.SqlUtls).GetFieldMaxVal(6,2)
9999.99
ClassMethod GetFieldMinVal(integer, decimal)
{
q $$minval^%apiSQL(integer, decimal)
}
USER>w ##class(Util.SqlUtls).GetFieldMinVal(6,2)
-9999.99
Query变成表ClassMethod QueryToTable(query, tablename)
{
d $SYSTEM.SQL.QueryToTable(query, tablename ,0)
}
UUIDClassMethod CreateUUID()
{
q $System.Util.CreateGUID()
}
sql表名ClassMethod GetTableName(className As %String) As %String
{
q ##class(%Dictionary.ClassDefinition).%OpenId(className).SqlTableName
}
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
}
USER> w ##class(Util.MethodUtils).GetTableName("User.Person")
BS_Person
USER>w ##class(Util.MethodUtils).GetTableNameBySQLUser("User.Person")
BS_Person
李高提供
ClassMethod StreamLike()
{
&sql(select SUBSTRING(Notes,0) ,* from Sample.MyTable where SUBSTRING(Notes,0) like '%yx%')
}
Util.ProcessUtilsBreak断点ClassMethod StopBreak()
{
d ##class(%SYSTEM.Process).BreakMode(0)
}
Break断点ClassMethod StartBreak()
{
d ##class(%SYSTEM.Process).BreakMode(1)
}
ClassMethod GetAllNameSpace()
{
d ##class(%SYS.Namespace).ListAll(.result)
zw result
}
Util.NetUtilsUrlClassMethod 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
}
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"
Util.NamespaceUtilsClassMethod IsNamespaceExist(name) As %Boolean
{
q ##class(%SYS.Namespace).Exists(name)
}
USER>w ##class(Util.NamespaceUtils).IsNamespaceExist("user1")
0
USER>w ##class(Util.NamespaceUtils).IsNamespaceExist("user")
1
Util.ClassUtilsClassMethod GetParamsNum(className As %String, methodName As %String) As %Integer
{
s methodParams = $g(^oddCOM(className, "m", methodName, 60))
s paramsNum = $ll(methodParams)
q paramsNum
}
ClassMethod GetNowParamsNum(arg...) As %Integer
{
w arg,!
q $zutil(141)
}
USER> w ##class(Util.ClassUtils).GetParamsNum("Util.ClassUtils","GetParamsNum")
2
USER>w ##class(Util.ClassUtils).GetNowParamsNum("Util.ClassUtils","GetParamsNum","2","3")
4
4
ClassMethod IsHasMethod(className As %String, methodName As %String) As %Boolean
{
q:($d(^oddCOM(className, "m", methodName))) $$$YES
q $$$NO
}
ClassMethod IsHasMethod1(className As %String, methodName As %String) As %Boolean
{
q:(##class(%Dictionary.MethodDefinition).%ExistsId(className _ "||" _ methodName)) $$$YES
q $$$NO
}
USER>w ##class(Util.ClassUtils).IsHasMethod("Util.ClassUtils","IsHasMethod")
1
USER>w ##class(Util.ClassUtils).IsHasMethod("Util.ClassUtils","IsHasMethod1")
1
ClassMethod IsPropExist(className As %String, prop As %String) As %Boolean
{
q:($d(^oddCOM(className, "a", prop))) $$$YES
q $$$NO
}
ClassMethod IsPropExist1(className As %String, prop As %String) As %Boolean
{
q:(##class(%Dictionary.PropertyDefinition).%ExistsId(className _ "||" _ prop)) $$$YES
q $$$NO
}
USER>w ##class(Util.ClassUtils).IsPropExist("Util.ClassUtils","Name")
1
USER>w ##class(Util.ClassUtils).IsPropExist1("Util.ClassUtils","Name1")
0
ClassMethod IsExistsCls(cls As %String) As %Boolean
{
if '##class(%Dictionary.CompiledClass).%ExistsId(cls) {
q $$$NO
}
q $$$OK
}
USER>w ##class(Util.ClassUtils).IsExistsCls("Util.ClassUtils")
1
USER>w ##class(Util.ClassUtils).IsExistsCls("Util.ClassUtils1")
0
ClassMethod IsExtendCls(cls As %String, parentCls As %String) As %Boolean
{
Set check = $classmethod(cls, "%Extends", parentCls)
If 'check {
q $$$NO
}
q $$$OK
}
USER> w ##class(Util.ClassUtils).IsExtendCls("IMP.LOCK.BIZ","IMP.LOCK.Base")
1
ClassMethod GetTableNameByClassName(className)
{
&sql(SELECT SqlQualifiedNameQ into :tableName FROM %Dictionary.CompiledClass WHERE ID = :className)
q tableName
}
USER>w ##class(Util.ClassUtils).GetTableNameByClassName("M.T.PERSON")
M.T_Person
ClassMethod GetViewText(sqlViewName)
{
&sql(SELECT SqlQuery into :text FROM %Dictionary.QueryDefinition WHERE SqlView =1 AND SqlViewName = :sqlViewName)
q text
}
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
ClassMethod GetClassDesc(className)
{
&sql(SELECT Description into :desc FROM %Dictionary.ClassDefinition WHERE ID = :className )
q $g(desc)
}
USER>w ##class(Util.ClassUtils).GetClassDesc("M.M79")
author:姚鑫
ClassMethod GetMethodDesc(className, methodName)
{
s ID = className _ "||" _ methodName
&sql(SELECT Description into :desc FROM %Dictionary.MethodDefinition WHERE ID = :ID )
q $g(desc)
}
USER>w ##class(Util.ClassUtils).GetMethodDesc("M.M79","WaitLock")
desc:加锁
d ##class(M.M79).WaitLock()
ClassMethod GetKeywordDesc(keyWord, flag, name)
{
q $$FindDesc^%occName(keyWord, flag ,name)
}
USER>w ##class(Util.ClassUtils).GetKeywordDesc("M.M79","m","WaitLock")
desc:加锁
d ##class(M.M79).WaitLock()
ClassMethod GetParamsList(className, methodName)
{
s method = className _ "||" _ methodName
&SQL(
SELECT FormalSpecParsed INTO :formalSpecParsed
FROM %Dictionary.CompiledMethod
WHERE ID1 = :method
)
q formalSpecParsed
}
USER>zw ##class(Util.ClassUtils).GetParamsList("M.M79","WaitLock")
$lb($lb("name","%Library.String","",""),$lb("age","%Library.String","",""))
ClassMethod IsValidMethodName(name) As %Boolean
{
q $zname(name)
}
USER> w ##class(Util.ClassUtils).IsValidMethodName("%M79")
1
USER>w ##class(Util.ClassUtils).IsValidMethodName("#M79")
0
ClassMethod GetClassCreatedDateTime(className)
{
&sql(SELECT TimeCreated into :TimeCreated FROM %Dictionary.ClassDefinition WHERE ID = :className)
q $zdt(TimeCreated,3)
}
USER>w ##class(Util.ClassUtils).GetClassCreatedDateTime("User.Person")
2011-08-12 19:54:41
Util.LockUtilsClassMethod IsLockExist(lockname) As %Boolean
{
q:($d(^$lock(lockname))) $$$YES
q $$$NO
}
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
IDClassMethod GetLockPid(lockname) As %Boolean
{
q ^$lock(lockname, "OWNER")
}
USER>w ##class(Util.LockUtils).GetLockPid("^yx(1,1)")
3544
ClassMethod GetLockType(lockname) As %Boolean
{
q ^$lock(lockname, "MODE")
}
USER> w ##class(Util.LockUtils).GetLockType("^yx(1,1)")
X
ClassMethod GetLockFlag(lockname) As %Boolean
{
q ^$lock(lockname, "FLAGS")
}
ClassMethod DeleteAllLock(namespace) As %Boolean
{
s ret = 0
do
.n $namespace
.s $namespace = "%sys"
.s ret = ##Class(SYS.Lock).DeleteAllLocks()
q ret
}
pid相关锁ClassMethod DeleteLockByPid(pid) As %Boolean
{
s ret = 0
do
.n $namespace
.s $namespace = "%sys"
.s ret = ##Class(SYS.Lock).DeleteAllLocks(pid)
q ret
}
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
}
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"),!
}
}
ClassMethod QueryLock(namespace) As %Boolean
{
s lockname=""
for i = 1 : 1 {
s lockname = $o(^$|namespace|lock(lockname))
q:lockname=""
w lockname,!
}
q ""
}
USER>w ##class(Util.LockUtils).QueryLock("%sys")
^%SYS("CSP","Daemon")
^ISC.LMFMON("License Monitor")
^ISC.Monitor.System
^TASKMGR
Util.FunctionUtilsHostNameClassMethod GetHostName() As %String
{
s str = ##class(%Library.Function).HostName()
q str
}
ClassMethod GetHostName1() As %String
{
s x = ##class(%SYS.System).GetNodeName()
q x
}
USER>w ##class(Util.FunctionUtils).GetHostName()
LAPTOP-ARLL3DSO
USER>w ##class(Util.FunctionUtils).GetHostName1()
LAPTOP-ARLL3DSO
IPClassMethod GetOutLocalIP() As %String
{
q ##class(%SYSTEM.Process).ClientIPAddress()
}
USER>w ##class(Util.FunctionUtils).GetOutLocalIP()
127.0.0.1
IPClassMethod GetInLocalIP() As %String
{
q $p($zu(54,13,$zu(54,0)),",",1 )
}
USER>w ##class(Util.FunctionUtils).GetInLocalIP()
192.168.18.4
ClassMethod GetNameSpacePath() As %String
{
q ##class(%Library.File).NormalizeDirectory("")
}
USER>w ##class(%Library.File).NormalizeDirectory("")
C:\InterSystems\Cache\mgr\user\
ClassMethod IsChineseLocale() As %Boolean
{
s nls = ##class(%SYS.NLS.Locale).%New()
q:(nls.Language [ "Chinese") $$$OK
q $$$NO
}
USER>w ##class(Util.FunctionUtils).IsChineseLocale()
1
License信息ClassMethod ShowLicenseInfo() As %Boolean
{
d ##class(%SYSTEM.License).ShowCounts()
}
USER> d ##class(Util.FunctionUtils).ShowLicenseInfo()
本地软件许可使用视图.
300 授权的总数量 LU
299 当前可用 LU
299 最小可用 LU
1 当前用户处于活动状态
1 处于活动状态的最大用户数
0 当前 CSP 用户处于活动状态
0 处于活动状态的最大 CSP 用户数
0 当前 CSP 会话处于宽限期
0 处于宽限期的最大 CSP 会话数
ClassMethod GetMaxAvailableLicense() As %Boolean
{
q $SYSTEM.License.LUMinAvailable()
}
USER> w ##class(Util.FunctionUtils).GetMaxAvailableLicense()
299
刘小明 提供
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
}
}
USER> d ##class(Util.FunctionUtils).InitMultiVar("yx",3)
0
0
0
ClassMethod GetRunTime(className, methodName, params...) As %Boolean
{
s t1 = $zh
d $classmethod(className, methodName, params...)
q $zh - t1
}
USER> w ##class(Util.FunctionUtils).GetRunTime("Util.FunctionUtils","InitMultiVar","yx",3)
.000028
ClassMethod ExportAllProcessPrivateGlobal2Csv(path) As %Boolean
{
do
.s $namespace = "%sys"
.d ^GETPPGINFO("*", "MNN", path)
}
d ##class(Util.FunctionUtils).ExportAllProcessPrivateGlobal2Csv("E:/m/ppg.csv")
ClassMethod GetIntFileMethod(className, methodName)
{
for {
s str = "z" _ methodName _ "+" _ ($i(line) - 1) _ "^" _ className _ ".1"
s code = $text(@str)
q:(code = "")
w code,!
}
}
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,!
} }
ClassMethod GetIntFileContent(className)
{
for {
s str = "+" _ ($i(line) - 1) _ "^" _ className _ ".1"
s code = $text(@str)
q:(code = "")
w code,!
}
}
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()
}
ClassMethod IsEnableCtrlC() As %Boolean
{
q:($zjob\4#2 = 1) $$$OK
q $$$NO
}
USER> w ##class(Util.FunctionUtils).IsEnableCtrlC()
299
ClassMethod CheckSyntax(str) As %Boolean
{
s ret = ##class(%Library.Routine).CheckSyntax(str)
q:($$$ISERR(ret)) $$$NO
q $$$YES
}
USER>w ##class(Util.FunctionUtils).CheckSyntax(" s ^yx(""Xecute"") = 3")
1
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()
}
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
ClassMethod SingleStepDebug(className, methodName, params...)
{
b "L+"
s ret = $classmethod(className, methodName, params...)
b "off"
q ret
}
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
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
}
USER>w ##class(Util.FunctionUtils).CallOtherNameSpaceMethod("IMP","M.M91","TransactionFeature2","y","x")
y 与 x
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"
}
USER> w ##class(Util.FunctionUtils).GetOsName()
WINDOWS
Util.BitUtilClassMethod 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
}
USER>w ##class(Util.BitUtil).LogicalToDisplay(1)
1
USER>w ##class(Util.BitUtil).LogicalToDisplay(16)
00001
USER>w ##class(Util.BitUtil).LogicalToDisplay(15)
1111
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
}
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
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
}
USER> w ##class(Util.BitUtil).bit2Decimal($factor(10))
10
ClassMethod GetBit(ascii)
{
q $factor(ascii)
}
USER>zw ##class(Util.BitUtil).GetBit(10)
$zwc(128,4)_$c(10,0,0,0)/*$bit(2,4)*/
ClassMethod String2Bit(str)
{
q $factor($ascii(str))
}
USER> zw ##class(Util.BitUtil).String2Bit("姚")
$zwc(128,4)_$c(218,89,0,0)/*$bit(2,4,5,7..9,12,13,15)*/
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)
}
}
}
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)*/
ClassMethod Offset2Num(char, offset)
{
s bit = ..Offset(char, offset)
q ..bit2Decimal(bit)
}
USER>w ##class(Util.BitUtil).Offset2Num($factor(16),2)
4
USER>w ##class(Util.BitUtil).Offset2Num($factor(16),-2)
64
Util.EncryptionUtilsMD5加密以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解密FileUtilsClassMethod IsDirectoryExists(filePath) As %Boolean
{
q ##class(%File).DirectoryExists(filePath)
}
USER>w ##class(Util.FileUtils).IsDirectoryExists("E:\m\cls\")
1
ClassMethod CreateNotExistDir(filePath) As %Boolean
{
if ('..IsDirectoryExists(filePath)){
d ##class(%File).CreateNewDir(filePath, "")
}
}
USER>d ##class(Util.FileUtils).CreateNotExistDir("E:\m\cls\")
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
}
USER>w ##class(Util.FileUtils).Byte2MaxUnit("1048577")
1.0MB
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
}
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
}
赵新龙提供
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
}
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
}
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
}
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
}
USER>w ##class(Util.FileUtils).Base642File(##class(Util.FileUtils).File2Base64("E:\m\CsvFile.csv"),"E:\m\CsvFile5.csv")
1
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
}
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
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
}
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
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
}
USER>d ##class(Util.FileUtils).QueryDrives()
c:\
d:\
e:\
f:\
g:\
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
}
USER>d ##class(Util.FileUtils).ProcessFile("E:\m\input.txt","E:\m\output.txt")
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()
#; 根据Session,License,加密,不同浏览器不互通。使用对称加密算法
s str = ##class(%CSP.Page).Encrypt(oid)
q str
}
w ##class(Util.FileUtils).DownloadStream("E:\temp\test\yx.xml.xml","yx.xml","")
ClassMethod CreateFile(filename)
{
s fileObj = ##class(%File).%New(filename)
s sc = fileObj.Open("SN")
$$$ThrowOnError(sc)
q fileObj
}
w ##class(Util.FileUtils).CreateFile("E:\temp\test\yx.abc")
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
}
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\\"}]
JSONUtilsClassMethod ReverseArrayJson(array)
{
s newArr = []
for i = (array.%Size() - 1) : -1 : 0 {
s obj = array.%Get(i)
d newArr.%Push(obj)
}
q newArr
}
USER>w ##class(Util.JsonUtils).ReverseArrayJson([{"name":"yx1"},{"name":"yx2"}]).%ToJSON()
[{"name":"yx2"},{"name":"yx1"}]
马浩提供
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
}
/// 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
}
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>
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
}
USER>w ##class(Util.JsonUtils).ConcatArrays([1,2],[3,4],[3,4,5,6]).%ToJSON()
[1,2,3,4,3,4,5,6]
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
}
USER>w ##class(Util.JsonUtils).SetArrays([1,2],[3,4],[3,4,5,6]).%ToJSON()
[1,2,3,4,5,6]
ClassMethod Array2String(array, del = ",") As %String
{
s str = array.%ToJSON()
s str = $e(str, 2, * - 1)
s list = $lfs(str)
q $lts(list, del)
}
USER>w ##class(Util.JsonUtils).Array2String([1, 2, 3], "^")
1^2^3
ClassMethod List2String(list, del = ",") As %String
{
q $lts(list, del)
}
USER>w ##class(Util.JsonUtils).List2String($lb(1,2,3), "^")
1^2^3
XmlUtils马浩提供
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>"</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</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>
}
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",
}] }
}}
Util.StreamUtilsClassMethod 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
}
Util.ConfigUtils错误ClassMethod SetUndefined() As %String
{
s ret = ##class(%SYSTEM.Process).Undefined(2)
s yx = b
q ret
}
USER>w ##class(Util.ConfigUtils).SetUndefined()
0
ClassMethod GetSystemConfig(params) As %String
{
q ##class(%SYS.NLS.Format).GetFormatItem(params)
}
USER>w ##class(Util.ConfigUtils).GetSystemConfig("MinusSign")
-
USER>w ##class(Util.ConfigUtils).GetSystemConfig("DecimalSeparator")
.