├── .DS_Store ├── .gitignore ├── LICENSE ├── README.md ├── READMEQL.md ├── README_QL.md ├── cmd ├── comp.go ├── embed.go ├── go.mod ├── go.sum ├── gui.go ├── main.go └── noGui.go ├── docs ├── calculatorss.png ├── goxeditor.png ├── goxeditor2.png ├── goxfavicon.ico ├── goxhomepageS.png ├── goxlogo2s.jpg ├── goxlogo2xs.jpg ├── goxlogos.jpg └── lclgui.png ├── go.mod ├── go.sum ├── gox.go ├── magic └── 18.gox ├── res.go ├── scripts ├── Fib.class ├── Fib.java ├── Performance.java ├── anonymousFunc.gox ├── anyQueue.gox ├── array.gox ├── arrayContains.gox ├── arrayList.gox ├── auto.gox.bac ├── auto.gxb.bac ├── basic.gox ├── basic.goxe ├── basicPlot.gox ├── basicPlotDualGUI.gox ├── basicPlotGUI.gox ├── basicPlotWeb.gox ├── binCompare.gox ├── bitwise.gox ├── bmi.gox ├── bmi1.gox ├── byteQueue.gox ├── calCosineSimilarity.gox ├── calCosineSimilarityBig.gox ├── calculator.gox ├── calculatorGUI.gox ├── call.gox ├── chan.gox ├── charOracle.gox ├── charms.gox ├── checkErrf.gox ├── class1.gox ├── class2.gox ├── class3.gox ├── class4.gox ├── cmd.gox ├── commandLine.gox ├── commandLineCN.gox ├── comment.gox ├── concurrent.gox ├── dataTypeConversion.gox ├── dataTypes.gox ├── debug.gox ├── debug2.gox ├── debug3.gox ├── deep.gox ├── deepClone.gox ├── defer.gox ├── dialogs.gox ├── downloadFile1.gox ├── downloadFile2.gox ├── editFile.gox ├── editFileCN.gox ├── editFileSciter.gox ├── editFileSciter.st ├── editFileSciter1.html ├── encodingConvertorCN.gox ├── encryptDataWithHead.gox ├── enlargeImage.gox ├── evalx.gox ├── excelRead.gox ├── excelToCSV.gox ├── fib.char ├── fib.go ├── fib.gox ├── fib.py ├── fibFlat.gox ├── findStringDiffPos.gox ├── funcArg.gox ├── funcVar.gox ├── functionType.gox ├── generateImport.gox ├── generategoxc.gox ├── generategoxct.gox ├── generategoxt.gox ├── getChar.gox ├── getCurrentTime.gox ├── getFileList.gox ├── getLines.gox ├── ggBasicDrawingCN.gox ├── ggImageInSciter.gox ├── grep.gox ├── guiG.gox ├── guiInfo.gox ├── helloworld.gox ├── hexToInt.gox ├── htmlKeyWV2.gox ├── httpGet.gox ├── httpPost1.gox ├── httpServer.gox ├── if.gox ├── imageServer.gox ├── infoErrConfirm.gox ├── input.gox ├── intfloat.gox ├── joinTextFile.gox ├── json.gox ├── limitStr.gox ├── localVar.gox ├── localVar2.gox ├── localVsGlobal.gox ├── loginDialog.gox ├── loginDialogLinux.gox ├── loopAndIf.gox ├── map.gox ├── mapCN.gox ├── mapIndex.gox ├── memfs.gox ├── memtar.gox ├── module.gox ├── newObject.gox ├── nosql.gox ├── not.gox ├── operators.gox ├── oracle.gox ├── orderedMap.gox ├── perf.cpp ├── performance.go ├── performance.gox ├── performance.js ├── performance.py ├── performance.tg ├── pointer.gox ├── pointerCN.gox ├── portForward1.gox ├── portForward1Compact.gox ├── portForward2.gox ├── portForward2Compact.gox ├── qexports.gox ├── regexpx.gox ├── replaceGoxn.gox ├── replaceTextInFiles.gox ├── runXie.gox ├── sciter.gox ├── sciter01.gox ├── sciter02.gox ├── sciter03.gox ├── sciter04.gox ├── sciter05img.gox ├── screenShot.gox ├── screenShotToImage.gox ├── script.gox ├── selectFile.gox ├── sendAliyunSMS.gox ├── seq.gox ├── smtp.gox ├── soap.gox ├── socket.gox ├── socksClient.gox ├── socksClientCompact.gox ├── socksServer.gox ├── socksServerCompact.gox ├── sortByFunc.gox ├── sortX.gox ├── sqlite.gox ├── sqliteMem.gox ├── sqliteOrdered.gox ├── ssh.gox ├── stack.gox ├── string.gox ├── stringRing.gox ├── struct1.gox ├── struct1CN.gox ├── sync.gox ├── term.gox ├── test.gox ├── testAll.gox ├── testCharlang.gox ├── testWebView2.gox ├── tmp.gox ├── toFromXml.gox ├── undefined.gox ├── urlValues.gox ├── uselib.gox ├── varInGoroutine.gox ├── variable.gox ├── viewLines.gox ├── webServer.gox ├── webServerCompact.gox ├── webServerStatic.gox ├── webView.gox ├── xie1.gox └── xml.gox ├── sysspec_nonwindows.go ├── sysspec_windows.go ├── tutorial ├── anonymfn │ └── anonym.ql ├── calc │ ├── calc.ql │ └── main.ql ├── chan │ └── chan.ql ├── closure │ └── closure.ql ├── defer │ └── file.ql ├── flowctrl │ └── flowctrl.ql ├── for_range │ └── for_range.ql ├── goroutine │ └── goroutine.ql ├── http │ └── httpserver.ql ├── if │ └── if.ql ├── include │ ├── a │ │ ├── foo.ql │ │ └── main.ql │ ├── b.ql │ ├── bar.ql │ └── run.sh ├── maxprime │ ├── maxprime.py │ └── maxprime.ql ├── module │ ├── c.ql │ ├── internal │ │ └── a │ │ │ ├── foo.ql │ │ │ └── main.ql │ └── run.sh ├── qlang │ ├── main.ql │ └── qlang.ql ├── shell │ └── shell.ql ├── sync │ └── sync.ql └── terminal │ ├── calc.ql │ └── qlang.ql ├── webview2_nonwindows.go └── webview2_windows.go /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 TopXeQ 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /READMEQL.md: -------------------------------------------------------------------------------- 1 | Q Language - A script language for Go 2 | ======== 3 | 4 | [![Build Status](https://travis-ci.org/qiniu/qlang.png?branch=master)](https://travis-ci.org/qiniu/qlang) [![GoDoc](https://godoc.org/github.com/qiniu/qlang?status.svg)](https://godoc.org/github.com/qiniu/qlang) [![Go Report Card](https://goreportcard.com/badge/github.com/qiniu/qlang)](https://goreportcard.com/report/github.com/qiniu/qlang) 5 | 6 | [![Qiniu Logo](http://open.qiniudn.com/logo.png)](http://www.qiniu.com/) 7 | 8 | ## 语言特色 9 | 10 | * 与 Go 语言有最好的互操作性。可不进行任何包装即可直接使用 Go 语言的函数、类及其成员变量和方法。 11 | * 有赖于 Go 语言的互操作性,这门语言直接拥有了一套非常完整且您十分熟悉的标准库,无额外学习成本。 12 | * 与 Go 十分相近的语法,降低您的学习成本。 13 | * 支持 Go 绝大部分语言特性,包括:for range, string, slice, map, chan, goroutine, defer, etc。 14 | * 微内核:语言的核心只有大约 1200 行代码。所有功能以可插拔的 module 方式提供。 15 | 16 | 预期的商业场景: 17 | 18 | * 由于与 Go 语言的无缝配合,qlang 在嵌入式脚本领域有 lua、python、javascript 所不能比拟的优越性。比如:网络游戏中取代 lua 的位置。 19 | * 作为编译原理的教学语言。由于 qlang 的 Compiler 代码极短,便于阅读和理解,非常方便教学实践之用。 20 | 21 | 22 | ## 快速入门 23 | 24 | ### 在您的 Go 代码中整合 qlang 25 | 26 | ```go 27 | import ( 28 | "fmt" 29 | "log" 30 | "strings" 31 | 32 | "github.com/topxeq/qlang" 33 | _ "github.com/topxeq/qlang/lib/builtin" // 导入 builtin 包 34 | ) 35 | 36 | var strings_Exports = map[string]interface{}{ 37 | "replacer": strings.NewReplacer, 38 | } 39 | 40 | func main() { 41 | 42 | qlang.Import("strings", strings_Exports) // 导入一个自定义的包,叫 strings(和标准库同名) 43 | ql := qlang.New() 44 | 45 | err := ql.SafeEval(`x = strings.replacer("?", "!").replace("hello, world???")`) 46 | if err != nil { 47 | log.Fatal(err) 48 | return 49 | } 50 | 51 | fmt.Println("x:", ql.Var("x")) // 输出 x: hello, world!!! 52 | } 53 | ``` 54 | 55 | 这是一个功能最精简功能的迷你版 qlang。 56 | 57 | 想要了解更多,可参考“[定制 qlang](README_QL.md#定制-qlang)”相关内容。实际项目中你也可以参考代码: 58 | 59 | * [qshell.go](cmd/qshell/qshell.go) 60 | * [qlang/main.go](cmd/qlang/main.go) 61 | 62 | ### 非嵌入式场景下使用 qlang 63 | 64 | 尽管我们认为 qlang 的优势领域是在与 Go 配合的嵌入式场景,但您也可以把 qlang 语言用于非嵌入式脚本领域。 65 | 66 | 您可以直接通过 `qlang` 命令行程序来执行 *.ql 的代码。如下: 67 | 68 | ``` 69 | qlang xxx.ql ... 70 | ``` 71 | 72 | 为了方便学习 qlang 工作机理,我们支持导出 qlang 编译的 “汇编指令”: 73 | 74 | ``` 75 | QLANG_DUMPCODE=1 qlang xxx.ql ... 76 | ``` 77 | 78 | 在 Unix 系的操作系统下,您可以在 xxx.ql 文件开头加上: 79 | 80 | ``` 81 | #!/usr/bin/env qlang 82 | ``` 83 | 84 | 并给 xxx.ql 文件加上可执行权限,即可直接运行 xxx.ql 脚本。 85 | 86 | ### 使用 qlang shell 87 | 88 | 命令行下输入 `qlang` 命令(不带参数),直接进入 qlang shell。 89 | 90 | 您同样也可以设置 QLANG_DUMPCODE 环境变量来学习 qlang 的工作机理: 91 | 92 | ``` 93 | QLANG_DUMPCODE=1 qlang 94 | ``` 95 | 96 | ### 学习 qlang 语言特性 97 | 98 | * [Q 语言手册](README_QL.md): 这里有语言特性的详细介绍。 99 | * [Qlang Tutorials](tutorial): 这里是一些 qlang 的样例代码,供您学习 qlang 时参考。 100 | 101 | 102 | ## 下载 103 | 104 | ### 发行版本 105 | 106 | * https://github.com/qiniu/qlang/releases 107 | 108 | ### 最新版本 109 | 110 | ``` 111 | go get github.com/qiniu/qlang 112 | ``` 113 | 114 | ## 社区资源 115 | 116 | ### Embedded qlang (eql) 117 | 118 | * [eql](cmd/eql): 全称 [embedded qlang](cmd/eql),是类似 erubis/erb 的东西。结合 go generate 可很方便地让 Go 支持模板(不是 html template,是指泛型)。 119 | 120 | ### 为 Go package 导出 qlang module 121 | 122 | * [qexport](cmd/qexport): 可为 Go 语言的标准库或者你自己写的 Go Package 自动导出相应的 qlang module。 123 | 124 | ### Qlang Modules 125 | 126 | * 准官方库: https://github.com/qlangio/libs 127 | * 第三方库: https://github.com/qlang-libs 128 | 129 | ### IDE 插件 130 | 131 | * liteide - https://github.com/visualfc/liteide 132 | * sublime - https://github.com/damonchen/sublime-qlang 133 | * vim - https://github.com/simon-xia/vim-qlang 134 | * atom - https://github.com/bingohuang/atom-language-q 135 | -------------------------------------------------------------------------------- /cmd/embed.go: -------------------------------------------------------------------------------- 1 | //go:build embed 2 | // +build embed 3 | 4 | package main 5 | 6 | func init() { 7 | CodeTextG = `pln("Embeded code test!")` 8 | } 9 | -------------------------------------------------------------------------------- /cmd/noGui.go: -------------------------------------------------------------------------------- 1 | //go:build linux 2 | // +build linux 3 | 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | ) 9 | 10 | func guiHandler(actionA string, objA interface{}, dataA interface{}, paramsA ...interface{}) interface{} { 11 | return fmt.Errorf("GUI engined disabled") 12 | } 13 | -------------------------------------------------------------------------------- /docs/calculatorss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/docs/calculatorss.png -------------------------------------------------------------------------------- /docs/goxeditor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/docs/goxeditor.png -------------------------------------------------------------------------------- /docs/goxeditor2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/docs/goxeditor2.png -------------------------------------------------------------------------------- /docs/goxfavicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/docs/goxfavicon.ico -------------------------------------------------------------------------------- /docs/goxhomepageS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/docs/goxhomepageS.png -------------------------------------------------------------------------------- /docs/goxlogo2s.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/docs/goxlogo2s.jpg -------------------------------------------------------------------------------- /docs/goxlogo2xs.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/docs/goxlogo2xs.jpg -------------------------------------------------------------------------------- /docs/goxlogos.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/docs/goxlogos.jpg -------------------------------------------------------------------------------- /docs/lclgui.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/docs/lclgui.png -------------------------------------------------------------------------------- /magic/18.gox: -------------------------------------------------------------------------------- 1 | pln("Calculator by TopXeQ V0.9a") 2 | 3 | paraT = trim(getParameter(os.Args, 2, "")) 4 | 5 | if paraT != "" { 6 | expression = paraT 7 | } else { 8 | expression = getInputf("Please enter the expression: ") 9 | } 10 | 11 | result = eval(expression) 12 | 13 | println("result:", result) 14 | 15 | pass() -------------------------------------------------------------------------------- /scripts/Fib.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/topxeq/gox/6901b403e3cd28b8a2f435a623523e036cf444ec/scripts/Fib.class -------------------------------------------------------------------------------- /scripts/Fib.java: -------------------------------------------------------------------------------- 1 | public class Fib { 2 | 3 | public static double calPi(int pointCount) { 4 | int inCircleCount = 0; 5 | 6 | double x, y; 7 | double Pi; 8 | 9 | for (int i = 0; i < pointCount; i++) { 10 | x = Math.random(); 11 | y = Math.random(); 12 | 13 | if (x * x + y * y < 1) { 14 | inCircleCount++; 15 | } 16 | } 17 | 18 | Pi = (4.0 * inCircleCount) / pointCount; 19 | 20 | return Pi; 21 | } 22 | 23 | public static double cal(double a, double b, double c) { 24 | return a * b / (c + 1) + a; 25 | } 26 | 27 | public static long fibonacci(long c) { 28 | if (c < 2) 29 | return c; 30 | return fibonacci(c - 2) + fibonacci(c - 1); 31 | } 32 | 33 | public static long fibonacciFlat(long c) { 34 | if (c < 2) { 35 | return c; 36 | } 37 | 38 | long fibo = 1; 39 | long fiboPrev = 1; 40 | for (long i = 2; i < c; i++) { 41 | long temp = fibo; 42 | fibo += fiboPrev; 43 | fiboPrev = temp; 44 | } 45 | 46 | return fibo; 47 | } 48 | 49 | public static void main(String[] args) { 50 | 51 | System.out.println("Test 1"); 52 | 53 | long startTime = System.currentTimeMillis(); 54 | 55 | double result = 0.0; 56 | 57 | // for (double i = 0.0; i < 1000000000; i = i + 1) { 58 | // result += i * i; 59 | // } 60 | 61 | long endTime = System.currentTimeMillis(); 62 | 63 | float duration = (float) (endTime - startTime) / 1000; 64 | 65 | // System.out.println("Result: " + result); 66 | // System.out.println("Duration: " + duration + " s"); 67 | 68 | // System.out.println("Test 2"); 69 | 70 | // startTime = System.currentTimeMillis(); 71 | 72 | // long resultInt = fibonacciFlat(10000000000L); 73 | 74 | // endTime = System.currentTimeMillis(); 75 | 76 | // duration = (float) (endTime - startTime) / 1000; 77 | 78 | // System.out.println("Result: " + resultInt); 79 | // System.out.println("Duration: " + duration + " s"); 80 | 81 | System.out.println("Test 2r"); 82 | 83 | startTime = System.currentTimeMillis(); 84 | 85 | long resultInt = fibonacci(35); 86 | 87 | endTime = System.currentTimeMillis(); 88 | 89 | duration = (float) (endTime - startTime) / 1000; 90 | 91 | System.out.println("Result: " + resultInt); 92 | System.out.println("Duration: " + duration + " s"); 93 | 94 | // System.out.println("Test 3"); 95 | 96 | // startTime = System.currentTimeMillis(); 97 | 98 | // result = 0.0; 99 | 100 | // for (double i = 0; i < 100000000; i = i + 1) { 101 | // result += Math.random(); 102 | // } 103 | 104 | // endTime = System.currentTimeMillis(); 105 | 106 | // duration = (float) (endTime - startTime) / 1000; 107 | 108 | // System.out.println("Result: " + result); 109 | // System.out.println("Duration: " + duration + " s"); 110 | 111 | // System.out.println("Test 4"); 112 | 113 | // startTime = System.currentTimeMillis(); 114 | 115 | // result = calPi(100000000); 116 | 117 | // endTime = System.currentTimeMillis(); 118 | 119 | // duration = (float) (endTime - startTime) / 1000; 120 | 121 | // System.out.println("Result: " + result); 122 | // System.out.println("Duration: " + duration + " s"); 123 | 124 | } 125 | } -------------------------------------------------------------------------------- /scripts/Performance.java: -------------------------------------------------------------------------------- 1 | public class Performance { 2 | 3 | public static double calPi(int pointCount) { 4 | int inCircleCount = 0; 5 | 6 | double x, y; 7 | double Pi; 8 | 9 | for (int i = 0; i < pointCount; i++) { 10 | x = Math.random(); 11 | y = Math.random(); 12 | 13 | if (x * x + y * y < 1) { 14 | inCircleCount++; 15 | } 16 | } 17 | 18 | Pi = (4.0 * inCircleCount) / pointCount; 19 | 20 | return Pi; 21 | } 22 | 23 | public static double cal(double a, double b, double c) { 24 | return a * b / (c + 1) + a; 25 | } 26 | 27 | public static long fibonacci(long c) { 28 | if (c < 2) 29 | return c; 30 | return fibonacci(c - 2) + fibonacci(c - 1); 31 | } 32 | 33 | public static long fibonacciFlat(long c) { 34 | if (c < 2) { 35 | return c; 36 | } 37 | 38 | long fibo = 1; 39 | long fiboPrev = 1; 40 | for (long i = 2; i < c; i++) { 41 | long temp = fibo; 42 | fibo += fiboPrev; 43 | fiboPrev = temp; 44 | } 45 | 46 | return fibo; 47 | } 48 | 49 | public static void main(String[] args) { 50 | 51 | System.out.println("Test 1"); 52 | 53 | long startTime = System.currentTimeMillis(); 54 | 55 | double result = 0.0; 56 | 57 | for (double i = 0.0; i < 1000000000; i = i + 1) { 58 | result += i * i; 59 | } 60 | 61 | long endTime = System.currentTimeMillis(); 62 | 63 | float duration = (float) (endTime - startTime) / 1000; 64 | 65 | System.out.println("Result: " + result); 66 | System.out.println("Duration: " + duration + " s"); 67 | 68 | System.out.println("Test 2"); 69 | 70 | startTime = System.currentTimeMillis(); 71 | 72 | long resultInt = fibonacciFlat(10000000000L); 73 | 74 | endTime = System.currentTimeMillis(); 75 | 76 | duration = (float) (endTime - startTime) / 1000; 77 | 78 | System.out.println("Result: " + resultInt); 79 | System.out.println("Duration: " + duration + " s"); 80 | 81 | System.out.println("Test 2r"); 82 | 83 | startTime = System.currentTimeMillis(); 84 | 85 | resultInt = fibonacci(50); 86 | 87 | endTime = System.currentTimeMillis(); 88 | 89 | duration = (float) (endTime - startTime) / 1000; 90 | 91 | System.out.println("Result: " + resultInt); 92 | System.out.println("Duration: " + duration + " s"); 93 | 94 | System.out.println("Test 3"); 95 | 96 | startTime = System.currentTimeMillis(); 97 | 98 | result = 0.0; 99 | 100 | for (double i = 0; i < 100000000; i = i + 1) { 101 | result += Math.random(); 102 | } 103 | 104 | endTime = System.currentTimeMillis(); 105 | 106 | duration = (float) (endTime - startTime) / 1000; 107 | 108 | System.out.println("Result: " + result); 109 | System.out.println("Duration: " + duration + " s"); 110 | 111 | System.out.println("Test 4"); 112 | 113 | startTime = System.currentTimeMillis(); 114 | 115 | result = calPi(100000000); 116 | 117 | endTime = System.currentTimeMillis(); 118 | 119 | duration = (float) (endTime - startTime) / 1000; 120 | 121 | System.out.println("Result: " + result); 122 | System.out.println("Duration: " + duration + " s"); 123 | 124 | } 125 | } -------------------------------------------------------------------------------- /scripts/anonymousFunc.gox: -------------------------------------------------------------------------------- 1 | // define a complex anonymous function 2 | // 定义一个复杂的匿名函数 3 | fn(x) { 4 | return fn(y) { 5 | x(y) 6 | } 7 | }(fn(z) { 8 | println("Hi!", z) 9 | })("Nice to see you.") 10 | 11 | // anonymous function to test variable "count" 12 | // 测试闭包的函数,用于将count进行计算 13 | NewAddFunc = fn() { 14 | count = 0 15 | 16 | return fn(n) { 17 | count += n 18 | 19 | return count 20 | } 21 | } 22 | 23 | main { 24 | 25 | println("count=", count) 26 | 27 | // 通过闭包操作count,可以发现count是在变化的 28 | f2 = NewAddFunc() 29 | 30 | println(f2(3)) 31 | 32 | println(f2(5)) 33 | 34 | println(f2(9)) 35 | 36 | // should panic here, since count is nil/undefined 37 | // It also indicates that the global variable "count" is not the same as the "count" variable in the closure 38 | // 此处程序会崩溃,因为count未经定义 39 | // 也说明全局变量count与闭包中的count变量并非同一个 40 | count += 20 41 | 42 | println("count=", count) 43 | 44 | } 45 | 46 | 47 | -------------------------------------------------------------------------------- /scripts/anyQueue.gox: -------------------------------------------------------------------------------- 1 | // 本例演示对象anyQueue的用法,可以用于存储处理一个可包含任意类型值的队列 2 | 3 | b1 = newObj("anyQueue", 6) 4 | 5 | pl("[%v] %#v %v", -1, b1, b1) 6 | 7 | for j = 0; j < b1.Size(); j++ { 8 | item1 = b1.Get(j) 9 | prf(" %v", item1) 10 | } 11 | 12 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 13 | 14 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 15 | 16 | pln("remove 0:", b1.Remove(0)) 17 | 18 | pln("remove last:", b1.Remove(b1.Size())) 19 | 20 | pln("remove 3:", b1.Remove(3)) 21 | 22 | for i = 20000; i < 20022; i++ { 23 | b1.Push(int(i)) 24 | 25 | pl("[%v] %#v %v", i, b1, b1) 26 | 27 | for j = 0; j < b1.Size(); j++ { 28 | item1 = b1.Get(j) 29 | prf(" %v", item1) 30 | } 31 | 32 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 33 | 34 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 35 | 36 | } 37 | 38 | b1.Insert(0, byte(100)) 39 | 40 | pl("-1 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 41 | 42 | for j = 0; j < b1.Size(); j++ { 43 | item1 = b1.Get(j) 44 | prf(" %v", item1) 45 | } 46 | 47 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 48 | 49 | b1.Insert(3, float64(103)) 50 | 51 | pl("-2 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 52 | 53 | for j = 0; j < b1.Size(); j++ { 54 | item1 = b1.Get(j) 55 | prf(" %v", item1) 56 | } 57 | 58 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 59 | 60 | b1.Insert(b1.Size()-1, byte(109)) 61 | 62 | pl("-3 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 63 | 64 | for j = 0; j < b1.Size(); j++ { 65 | item1 = b1.Get(j) 66 | prf(" %v", item1) 67 | } 68 | 69 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 70 | 71 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 72 | 73 | // remove 0 74 | b1.Remove(0) 75 | 76 | pl("remove0 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 77 | 78 | for j = 0; j < b1.Size(); j++ { 79 | item1 = b1.Get(j) 80 | prf(" %v", item1) 81 | } 82 | 83 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 84 | 85 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 86 | 87 | // remove last 88 | b1.Remove(b1.Size() - 1) 89 | 90 | pl("removeLast [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 91 | 92 | for j = 0; j < b1.Size(); j++ { 93 | item1 = b1.Get(j) 94 | prf(" %v", item1) 95 | } 96 | 97 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 98 | 99 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 100 | 101 | // remove 2 102 | b1.Remove(2) 103 | 104 | pl("remove2 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 105 | 106 | for j = 0; j < b1.Size(); j++ { 107 | item1 = b1.Get(j) 108 | prf(" %v", item1) 109 | } 110 | 111 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 112 | 113 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 114 | 115 | // // pop 116 | 117 | // cnt1 = 0 118 | // for { 119 | // a1 = b1.Pop() 120 | 121 | // if isErrX(a1) { 122 | // exit() 123 | // } 124 | 125 | // cnt1++ 126 | 127 | // pl("got %v", a1) 128 | 129 | // pl("[%v] %v S: %v", cnt1, b1, b1.Size()) 130 | 131 | // } 132 | 133 | // pick 134 | 135 | cnt1 = 0 136 | for { 137 | a1 = b1.Pick() 138 | 139 | if isErrX(a1) { 140 | exit() 141 | } 142 | 143 | cnt1++ 144 | 145 | pl("got %v", a1) 146 | 147 | pl("[%v] %v S: %v", cnt1, b1, b1.Size()) 148 | 149 | } -------------------------------------------------------------------------------- /scripts/array.gox: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3, "abc", 12.3] 2 | 3 | println("a:", a) 4 | 5 | println("a[2]:", a[2]) 6 | 7 | println("length of a:", len(a)) 8 | 9 | a = []var {1, 2} 10 | 11 | a = append(a, "abc") 12 | a = append(a, ["xyz", 16]...) 13 | 14 | pv("a") 15 | 16 | a[0]++ 17 | 18 | a[1] = [3.2, 16] 19 | 20 | // a[6] = "5th" // will index out of range 21 | 22 | a[4] = 1000 23 | 24 | a[len(a) - 1] = "last" 25 | 26 | pv("a") 27 | 28 | pl("a[1][1] = %v", a[1][1]) 29 | 30 | b = [19, 19] 31 | 32 | pl("a + b = %v", append(a, b...)) 33 | 34 | c = append(append([a], [b]...), b...) 35 | 36 | pv("c") 37 | 38 | d = a[3:5] 39 | 40 | pv("d") 41 | 42 | e = remove(a, 1, 3) 43 | 44 | pv("e") 45 | 46 | f = make([][]bool, 1) 47 | 48 | f[0] = make([]bool, 2) 49 | f[0][0] = false 50 | f[0][1] = true 51 | 52 | pv("f") 53 | 54 | g = []float64{1.2, 3, 56} 55 | 56 | pv("g") 57 | 58 | for i, v = range c { 59 | pl("i: %v, v: %v", i, v) 60 | } 61 | 62 | for i = 0; i < len(c); i ++ { 63 | pl("i: %v, v: %v", i, c[i]) 64 | } -------------------------------------------------------------------------------- /scripts/arrayContains.gox: -------------------------------------------------------------------------------- 1 | ary1 = ["abc", 123, 2.58] 2 | 3 | plv(arrayContains(ary1, "abc")) 4 | 5 | plv(arrayContains(ary1, "abcd")) 6 | 7 | plv(arrayContains(ary1, 123)) 8 | 9 | plv(arrayContains(ary1, 1234)) 10 | 11 | plv(arrayContains(ary1, 2.58)) 12 | 13 | plv(arrayContains(ary1, 2.589)) 14 | 15 | 16 | plv(arrayContains(argsG, "-verbose")) 17 | 18 | plv(arrayContains(argsG, 123)) 19 | 20 | -------------------------------------------------------------------------------- /scripts/arrayList.gox: -------------------------------------------------------------------------------- 1 | utils = github_topxeq_gods_utils 2 | 3 | list := newObject("arrayList") 4 | 5 | list.Add("a") // ["a"] 6 | list.Add("c", "b") // ["a","c","b"] 7 | 8 | pln(list) 9 | 10 | list.Sort(utils.StringComparator) // ["a","b","c"] 11 | 12 | pln(list) 13 | 14 | r1, r2 = list.Get(0) // "a",true 15 | pln(r1, r2) 16 | 17 | r1, r2 = list.Get(100) // nil,false 18 | pln(r1, r2) 19 | 20 | pln(list.Contains("a", "b", "c")) // true 21 | pln(list.Contains("a", "b", "c", "d")) // false 22 | 23 | list.Swap(0, 1) // ["b","a","c"] 24 | pln(list) 25 | 26 | list.Remove(2) // ["b","a"] 27 | pln(list) 28 | 29 | list.Remove(1) // ["b"] 30 | pln(list) 31 | 32 | list.Remove(0) // [] 33 | pln(list) 34 | 35 | list.Remove(0) // [] (ignored) 36 | pln(list) 37 | 38 | pln(list.Empty()) // true 39 | pln(list.Size()) // 0 40 | 41 | list.Add("a") // ["a"] 42 | pln(list) 43 | 44 | list.Clear() 45 | pln(list) 46 | -------------------------------------------------------------------------------- /scripts/auto.gox.bac: -------------------------------------------------------------------------------- 1 | pln(19 * 13) 2 | 3 | return -------------------------------------------------------------------------------- /scripts/auto.gxb.bac: -------------------------------------------------------------------------------- 1 | // gxb 2 | basic.gox 3 | 18 4 | basic.gox 5 | -------------------------------------------------------------------------------- /scripts/basic.gox: -------------------------------------------------------------------------------- 1 | // do simple add operation 2 | x = 1.2 3 | y = x + 1 4 | 5 | println(x + y) 6 | 7 | pass() -------------------------------------------------------------------------------- /scripts/basic.goxe: -------------------------------------------------------------------------------- 1 | //TXDEF#2B39BECB8EA54650606D549AAE6CAAADA7ACB1B75DABA4A66BC7B3B5B8A9C5C7B8C45958CF848C7C83828F775FDB789783E87B937E9176806E78D4D8D8EADBE0D894EDADE6A37D7C -------------------------------------------------------------------------------- /scripts/basicPlot.gox: -------------------------------------------------------------------------------- 1 | // 导入imagetk包 2 | itk = imagetk.NewImageTK() 3 | 4 | // 创建一个绘制上下文环境 5 | p, _ = plot.New() 6 | 7 | // 设置图表的抬头标题 8 | // 注意Gox语言中取得成员变量的指针需要用@操作符 9 | p@Title.Text = "Gonum Plot Example" 10 | 11 | // 设置图标X、Y坐标的文字 12 | p@X@Label.Text = "X" 13 | p@Y@Label.Text = "Y" 14 | 15 | // 创建一组准备绘制的坐标点(4个点) 16 | points = make(plot_plotter.XYs, 4) 17 | 18 | // 创建并为第一个点赋值X、Y坐标 19 | tmpXY = new(plot_plotter.XY) 20 | tmpXY.X = 0.0 21 | tmpXY.Y = 0.0 22 | 23 | points[0] = *tmpXY 24 | 25 | // 采用简便的方法创建第2、3、4个点 26 | points[1] = itk.NewPlotXY(1.0, 1.0) 27 | points[2] = itk.NewPlotXY(2.0, 4.0) 28 | points[3] = itk.NewPlotXY(3.0, 9.0) 29 | 30 | // 在图表中加入这些点,并给相应的曲线设定图例的名字 31 | plot_plotutil.AddLinePoints(p, "y = x * x", points) 32 | 33 | // 将折线图保存为4英寸见方大小的图片points.png, 34 | // 需要确保c:\test目录已经存在 35 | p.Save(4*plot_vg.Inch.Points(), 4*plot_vg.Inch.Points(), `c:\test\points.png`) 36 | 37 | -------------------------------------------------------------------------------- /scripts/basicPlotDualGUI.gox: -------------------------------------------------------------------------------- 1 | // 导入imagetk包 2 | itk = imagetk.NewImageTK() 3 | 4 | // 创建一个绘制上下文环境 5 | p, _ = plot.New() 6 | 7 | // 设置图表的抬头标题 8 | p@Title.Text = "Gonum Plot Example" 9 | 10 | // 设置图标X、Y坐标的文字 11 | p@X@Label.Text = "X" 12 | p@Y@Label.Text = "Y" 13 | 14 | // 创建一组准备绘制的坐标点(4个点) 15 | points = make(plot_plotter.XYs, 4) 16 | 17 | // 创建并为第一个点赋值X、Y坐标 18 | tmpXY = new(plot_plotter.XY) 19 | tmpXY.X = 0.0 20 | tmpXY.Y = 0.0 21 | 22 | points[0] = *tmpXY 23 | 24 | // 采用简便的方法创建第2、3、4个点 25 | points[1] = itk.NewPlotXY(1.0, 1.0) 26 | points[2] = itk.NewPlotXY(2.0, 4.0) 27 | points[3] = itk.NewPlotXY(3.0, 9.0) 28 | 29 | // 在图表中加入这些点,并给相应的曲线设定图例的名字 30 | plot_plotutil.AddLinePoints(p, "y = x * x", points) 31 | 32 | // 在内存中生成一个基于plot绘制图的图形对象 33 | rgbaT, errT = itk.LoadPlotImage(p, 4*plot_vg.Inch.Points(), 4*plot_vg.Inch.Points()) 34 | 35 | checkError(errT, nil) 36 | 37 | // 将折线图保存为4英寸见方大小的图片points.png, 38 | // 需要确保c:\test目录已经存在 39 | p.Save(4*plot_vg.Inch.Points(), 4*plot_vg.Inch.Points(), `c:\test\points.png`) 40 | 41 | dataT = loadBytes(`c:\test\points.png`) 42 | 43 | checkError(dataT) 44 | 45 | base64StrT := tk.EncodeToBase64(dataT) 46 | 47 | // 设置Sciter格式的HTML网页字符串 48 | // 此处非常简单,就是一个网页框架 49 | // 后续DOM操作将由Gox代码来进行 50 | // 注意,为了正确在Sciter中显示中文,最好加上两种meta定义utf-8编码 51 | htmlT := ` 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | ` 62 | 63 | // 锁定GUI线程,理论上GUI编程都要求在同一线程中更新界面元素 64 | runtime.LockOSThread() 65 | 66 | // 创建Sciter窗口,并指定窗口区域位置及大小 67 | w, err := sciterWindow.New(sciter.DefaultWindowCreateFlag, sciter.NewRect(0, 0, 900, 600)) 68 | 69 | checkError(err) 70 | 71 | // 设置该窗口的一些属性 72 | w.SetOption(sciter.SCITER_SET_SCRIPT_RUNTIME_FEATURES, sciter.ALLOW_FILE_IO | sciter.ALLOW_SOCKET_IO | sciter.ALLOW_EVAL | sciter.ALLOW_SYSINFO) 73 | 74 | // 载入HTML页面框架 75 | // 第二个参数是基URL(base url),我们一般不用 76 | w.LoadHtml(htmlT, "") 77 | 78 | // 设置窗口标题,注意是中文的 79 | w.SetTitle("并列点线图") 80 | 81 | // 获取Sciter页面的根元素 82 | rootT, _ := w.GetRootElement() 83 | 84 | // 获取body元素 85 | bodyT, _ := rootT.SelectFirst("body") 86 | 87 | // 创建一个div,其中文本为空(第二个参数) 88 | divT, _ := sciter.CreateElement("div", "") 89 | 90 | // 在body元素中插入div,第二个参数是插入的位置 91 | _ := bodyT.Insert(divT, 0) 92 | 93 | // 设置div的innerHTML 94 | // 第二个标志SIH_REPLACE_CONTENT表示替换innerHTML的全部 95 | // 还有可用的标志位有SIH_INSERT_AT_START、SIH_APPEND_AFTER_LAST 96 | // SOH_REPLACE、SOH_INSERT_BEFORE、SOH_INSERT_AFTER,看名字即可知道大意 97 | divT.SetHtml(`演示图片`, sciter.SIH_REPLACE_CONTENT) 98 | 99 | // 设置div的id属性 100 | divT.SetAttr("id", "mainDivID") 101 | 102 | // 设置div的style属性(即CSS) 103 | divT.SetStyle("margin-bottom", "10px") 104 | 105 | // 获取我们之前定义的span标签 106 | // 这是在设置div的HTML中用文本定义的 107 | // 注意选择器的快捷写法 108 | spanT, _ := bodyT.SelectFirst("span#titleTextID") 109 | 110 | // 设置文字颜色为红色 111 | spanT.SetStyle("color", "#ff0000") 112 | 113 | 114 | // 再创建一个img元素准备装载图片 115 | imgT, _ := sciter.CreateElement("img", "") 116 | 117 | // 在body中插入元素,序号为1,也就是第二个元素,即在前面的div之后 118 | _ := bodyT.Insert(imgT, 1) 119 | 120 | // 设置该元素的src属性为BASE64格式的图片 121 | // imgT.SetAttr("src", `data:image/png;base64,`+base64StrT) 122 | imgT.SetAttr("src", `C:\test\points.png`) 123 | 124 | // 再创建一个img元素准备装载Base64编码格式的图片 125 | img2T, _ := sciter.CreateElement("img", "") 126 | 127 | // 在body中插入元素,序号为2,也就是第二个元素,即在前面的div之后 128 | _ := bodyT.Insert(img2T, 2) 129 | 130 | // 设置该元素的src属性为BASE64格式的图片 131 | img2T.SetAttr("src", `data:image/png;base64,`+base64StrT) 132 | 133 | // 输出目前的根节点的HTML文本以供参考 134 | // 第二个参数为true表示是outerHTML,否则是innerHTML 135 | plv(rootT.Html(true)) 136 | 137 | // 显示窗口并运行GUI图形界面 138 | w.Show() 139 | w.Run() 140 | 141 | // onButtonClick = func() { 142 | // exit() 143 | // } 144 | 145 | // textureT = nil 146 | 147 | // flagT = 0 148 | 149 | // f = func() { 150 | // if flagT != 0 { 151 | // return 152 | // } 153 | 154 | // flagT = 1 155 | 156 | // textureT, errT = giu.NewTextureFromRgba(rgbaT) 157 | 158 | // if errT != nil { 159 | // plerr(errT) 160 | // return 161 | // } 162 | // } 163 | 164 | // loop = func() { 165 | // go f() 166 | 167 | // layoutT = []giu.Widget{ 168 | // giu.ImageWithFile(`c:\test\points.png`, 300, 300), 169 | // giu.Custom(func() { 170 | // if textureT != nil { 171 | // giu.Image(textureT, 348, 348).Build() 172 | // } 173 | // }), 174 | // giu.Button("Close", onButtonClick), 175 | // } 176 | 177 | // giu.SingleWindow("Plot Diagram", layoutT) 178 | // } 179 | 180 | // mainWindow = giu.NewMasterWindow("Plot Diagram", 400, 750, giu.MasterWindowFlagsNotResizable, nil) 181 | 182 | // mainWindow.Main(loop) 183 | 184 | 185 | 186 | -------------------------------------------------------------------------------- /scripts/basicPlotGUI.gox: -------------------------------------------------------------------------------- 1 | // 导入imagetk包 2 | itk = imagetk.NewImageTK() 3 | 4 | // 创建一个绘制上下文环境 5 | p, _ = plot.New() 6 | 7 | // 设置图表的抬头标题 8 | p@Title.Text = "Gonum Plot Example" 9 | 10 | // 设置图标X、Y坐标的文字 11 | p@X@Label.Text = "X" 12 | p@Y@Label.Text = "Y" 13 | 14 | // 创建一组准备绘制的坐标点(4个点) 15 | points = make(plot_plotter.XYs, 4) 16 | 17 | // 创建并为第一个点赋值X、Y坐标 18 | tmpXY = new(plot_plotter.XY) 19 | tmpXY.X = 0.0 20 | tmpXY.Y = 0.0 21 | 22 | points[0] = *tmpXY 23 | 24 | // 采用简便的方法创建第2、3、4个点 25 | points[1] = itk.NewPlotXY(1.0, 1.0) 26 | points[2] = itk.NewPlotXY(2.0, 4.0) 27 | points[3] = itk.NewPlotXY(3.0, 9.0) 28 | 29 | // 在图表中加入这些点,并给相应的曲线设定图例的名字 30 | plot_plotutil.AddLinePoints(p, "y = x * x", points) 31 | 32 | // 将折线图保存为4英寸见方大小的图片points.png, 33 | // 需要确保c:\test目录已经存在 34 | p.Save(4*plot_vg.Inch.Points(), 4*plot_vg.Inch.Points(), `c:\test\points.png`) 35 | 36 | // 设置Sciter格式的HTML网页字符串 37 | // 此处非常简单,就是一个网页框架 38 | // 后续DOM操作将由Gox代码来进行 39 | // 注意,为了正确在Sciter中显示中文,最好加上两种meta定义utf-8编码 40 | htmlT := ` 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | ` 51 | 52 | // 锁定GUI线程,理论上GUI编程都要求在同一线程中更新界面元素 53 | runtime.LockOSThread() 54 | 55 | // 创建Sciter窗口,并指定窗口区域位置及大小 56 | w, err := sciterWindow.New(sciter.DefaultWindowCreateFlag, sciter.NewRect(0, 0, 480, 480)) 57 | 58 | checkError(err) 59 | 60 | // 设置该窗口的一些属性 61 | w.SetOption(sciter.SCITER_SET_SCRIPT_RUNTIME_FEATURES, sciter.ALLOW_FILE_IO) 62 | 63 | // 载入HTML页面框架 64 | // 第二个参数是基URL(base url),我们一般不用 65 | w.LoadHtml(htmlT, "") 66 | 67 | // 设置窗口标题,注意是中文的 68 | w.SetTitle("展示文件点线图") 69 | 70 | // 获取Sciter页面的根元素 71 | rootT, _ := w.GetRootElement() 72 | 73 | // 获取body元素 74 | bodyT, _ := rootT.SelectFirst("body") 75 | 76 | // 创建一个div,其中文本为空(第二个参数) 77 | divT, _ := sciter.CreateElement("div", "") 78 | 79 | // 在body元素中插入div,第二个参数是插入的位置 80 | _ := bodyT.Insert(divT, 0) 81 | 82 | // 设置div的innerHTML 83 | // 第二个标志SIH_REPLACE_CONTENT表示替换innerHTML的全部 84 | // 还有可用的标志位有SIH_INSERT_AT_START、SIH_APPEND_AFTER_LAST 85 | // SOH_REPLACE、SOH_INSERT_BEFORE、SOH_INSERT_AFTER,看名字即可知道大意 86 | divT.SetHtml(`演示图片`, sciter.SIH_REPLACE_CONTENT) 87 | 88 | // 设置div的id属性 89 | divT.SetAttr("id", "mainDivID") 90 | 91 | // 设置div的style属性(即CSS) 92 | divT.SetStyle("margin-bottom", "10px") 93 | 94 | // 获取我们之前定义的span标签 95 | // 这是在设置div的HTML中用文本定义的 96 | // 注意选择器的快捷写法 97 | spanT, _ := bodyT.SelectFirst("span#titleTextID") 98 | 99 | // 设置文字颜色为红色 100 | spanT.SetStyle("color", "#ff0000") 101 | 102 | // 再创建一个img元素准备装载图片 103 | imgT, _ := sciter.CreateElement("img", "") 104 | 105 | // 在body中插入元素,序号为1,也就是第二个元素,即在前面的div之后 106 | _ := bodyT.Insert(imgT, 1) 107 | 108 | // 设置该元素的src属性为BASE64格式的图片 109 | // imgT.SetAttr("src", `data:image/png;base64,`+base64StrT) 110 | imgT.SetAttr("src", `C:\test\points.png`) 111 | 112 | // 输出目前的根节点的HTML文本以供参考 113 | // 第二个参数为true表示是outerHTML,否则是innerHTML 114 | plv(rootT.Html(true)) 115 | 116 | // 显示窗口并运行GUI图形界面 117 | w.Show() 118 | w.Run() 119 | -------------------------------------------------------------------------------- /scripts/basicPlotWeb.gox: -------------------------------------------------------------------------------- 1 | // 导入imagetk包 2 | itk = imagetk.NewImageTK() 3 | 4 | // 创建一个绘制上下文环境 5 | p, _ = plot.New() 6 | 7 | // 设置图表的抬头标题 8 | // 注意Gox语言中取得成员变量的指针需要用@操作符 9 | p@Title.Text = "Gonum Plot Example" 10 | 11 | // 设置图标X、Y坐标的文字 12 | p@X@Label.Text = "X" 13 | p@Y@Label.Text = "Y" 14 | 15 | // 创建一组准备绘制的坐标点(4个点) 16 | points = make(plot_plotter.XYs, 4) 17 | 18 | // 创建并为第一个点赋值X、Y坐标 19 | tmpXY = new(plot_plotter.XY) 20 | tmpXY.X = 0.0 21 | tmpXY.Y = 0.0 22 | 23 | points[0] = *tmpXY 24 | 25 | // 采用简便的方法创建第2、3、4个点 26 | points[1] = itk.NewPlotXY(1.0, 1.0) 27 | points[2] = itk.NewPlotXY(2.0, 4.0) 28 | points[3] = itk.NewPlotXY(3.0, 9.0) 29 | 30 | // 在图表中加入这些点,并给相应的曲线设定图例的名字 31 | plot_plotutil.AddLinePoints(p, "y = x * x", points) 32 | 33 | // 将折线图保存为4英寸见方大小的图片points.png, 34 | // 需要确保c:\test目录已经存在 35 | p.Save(4*plot_vg.Inch.Points(), 4*plot_vg.Inch.Points(), `c:\test\points.png`) 36 | 37 | // 设定net/http包的简称 38 | http = net_http 39 | 40 | // 设定网页内容 41 | // img标签中的src属性是准备在后面代码中替换为BASE64编码的图片数据的 42 | htmlT = ` 43 | 44 | 45 | 46 | 47 | 48 | 加载图像 49 | 50 | 51 | 52 | 53 | 54 | ` 55 | 56 | // 处理HTTP请求的函数 57 | // 读取前面保存的图片 58 | // 将其转换为BASE64格式的文本 59 | // 然后将其设置到img标签的src属性中 60 | func httpHandler(w, req) { 61 | // 载入图片数据 62 | imgDataT := loadBytes(`c:\test\points.png`) 63 | 64 | checkError(imgDataT) 65 | 66 | // 将图片数据转换为BASE64编码的文本 67 | base64DataT = base64Encode(imgDataT) 68 | 69 | // 将img标签的src属性替换为BASE64格式的表达 70 | htmlT = strReplace(htmlT, "TX_IMG_XT", `data:image/jpg;base64,`+base64DataT) 71 | 72 | // 写HTTP响应头 73 | w.WriteHeader(http.StatusOK) 74 | 75 | // 输出HTML页面 76 | w.Write([]byte(htmlT)) 77 | } 78 | 79 | // 设置服务器处理 80 | muxG = http.NewServeMux() 81 | 82 | // 处理网页根路径的处理函数 83 | muxG.HandleFunc("/", httpHandler) 84 | 85 | // 启动WEB服务器的函数,如果成功将是阻塞的 86 | func startServer() { 87 | errT := http.ListenAndServe(":7488", muxG) 88 | 89 | if errT != nil { 90 | pl("启动服务器失败:%v", errT) 91 | } 92 | } 93 | 94 | // 因为监听WEB服务是阻塞的,因此在线程内启动 95 | go startServer() 96 | 97 | // 打开系统中默认浏览器并访问本WEB服务器网址 98 | // 注意这里是Windows下的方法,Linux和Mac下要改成响应的命令行 99 | systemCmd("cmd", "/c", "start", "http://127.0.0.1:7488") 100 | // systemCmd("rundll32", "url.dll,FileProtocolHandler", "http://127.0.0.1:7488") 101 | 102 | // 启动无限循环,否则程序退出后,WEB服务器也将中止(主进程退出后,线程会终止) 103 | for true { 104 | sleep(1) 105 | } 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /scripts/binCompare.gox: -------------------------------------------------------------------------------- 1 | // gox -gopath binCompare.gox d:\tmpx\demo1.html d:\tmpx\demo2.html -limit=10 2 | 3 | argsT := getParams(argsG) 4 | 5 | if len(argsT) < 3 { 6 | fatalf("not enough parameters") 7 | } 8 | 9 | file1 = trim(argsT[1]) 10 | 11 | if file1 == "" { 12 | fatalf("file1 empty") 13 | } 14 | 15 | file2 = trim(argsT[2]) 16 | 17 | if file2 == "" { 18 | fatalf("file2 empty") 19 | } 20 | 21 | pl("compare %v -> %v", file1, file2) 22 | 23 | buf1 = loadBytes(file1) 24 | 25 | if isError(buf1) { 26 | fatalf("failed to read file1") 27 | } 28 | 29 | buf2 = loadBytes(file2) 30 | 31 | if isError(buf2) { 32 | fatalf("failed to read file2") 33 | } 34 | 35 | limit = getIntSwitch(argsG, "-limit=", 0) 36 | 37 | compareResult = tk.CompareBytes(buf1, buf2, limit) 38 | 39 | for i, v = range compareResult { 40 | pl("[%v] pos: %v %v/%v(%v) - %v/%X(%v)", i+1, v[0], v[1], toHex(v[1]), strQuote(spr("%c", v[1])), v[2], v[2], strQuote(spr("%c", v[2]))) 41 | } 42 | 43 | -------------------------------------------------------------------------------- /scripts/bitwise.gox: -------------------------------------------------------------------------------- 1 | // Create a new byte pointer 2 | // The new/newEx function also allocates space for it 3 | // Therefore, it can be assigned a value 4 | a := new(byte) 5 | 6 | setValueByRef(a, 3) 7 | 8 | plt(*a, unref(a), toHex(unref(a))) 9 | 10 | // The sscanf function is similar to the sscanf function in other languages 11 | // Will scan from the first parameter (here is the string "a3") to match 12 | // The content of the second parameter '% x' format character is placed in the following variable a 13 | // Since a is a pointer of type byte, a3 is considered a byte integer in hexadecimal lowercase, i.e. 163 14 | 15 | rs := sscanf("a3", "%x", a) 16 | 17 | plt(rs, *a, unref(a)) 18 | 19 | // Dereference the value in variable a and place it in variable b 20 | b := unref(a) 21 | 22 | // Output the numbers in b as values, hexadecimal values, and binary values respectively 23 | pl("%v -> %x -> %b", b, b, b) 24 | 25 | // Invert the data in b bit by bit and place it in variable c 26 | c := byteBitNot(b) 27 | 28 | // // Output the numbers in c as values, hexadecimal values, and binary values respectively 29 | // // %08b represents the output of binary values. If there are less than 8 bits, 0 will be added before it 30 | pl("%v -> %X -> %08b", c, c, c) 31 | 32 | // Calculate and output the data in c and hexadecimal 0F (that is, 15 in Decimal, 00001111 in binary) bit by bit 33 | // Complex expression calculation is used here 34 | // The unhex instruction will decode a string into a byte list in hexadecimal format 35 | // Use the getItem instruction to retrieve the value of the first byte (with sequence number 0) in the list 36 | // Since 0F is a byte, the first byte is the value of the entire number 37 | tmp := unhex("0F") 38 | 39 | pl("%08b", c&tmp[0]) 40 | 41 | // The data in c and hexadecimal 0F (that is, 15 in Decimal, 00001111 in binary) are bitwise or calculated and output 42 | pl("%08b", c|tmp[0]) 43 | 44 | // The data in c and hexadecimal 0F (that is, 15 in Decimal, 00001111 in binary) are calculated by bit XOR and output 45 | pl("%08b", c^tmp[0]) 46 | -------------------------------------------------------------------------------- /scripts/bmi.gox: -------------------------------------------------------------------------------- 1 | H = toFloat(getParam(argsG, 1)) 2 | W = toFloat(getParam(argsG, 2)) 3 | 4 | pl("身高: %.2f", H) 5 | pl("体重: %.2f", W) 6 | 7 | BMI = W / (H * H) 8 | 9 | pl("BMI: %.2f", BMI) 10 | 11 | if BMI < 18.5 { 12 | pl("偏瘦") 13 | } elif (18.5 <= BMI) && (BMI < 24) { 14 | pl("正常") 15 | } elif 24 <= BMI && BMI < 28 { 16 | pl("偏胖") 17 | } elif 28 <= BMI && BMI < 30 { 18 | pl("肥胖") 19 | } elif BMI >= 30 { 20 | pl("重度肥胖") 21 | } -------------------------------------------------------------------------------- /scripts/bmi1.gox: -------------------------------------------------------------------------------- 1 | H = 1.75 2 | W = 65.0 3 | 4 | BMI = W / (H * H) 5 | 6 | pl("BMI: %.2f", BMI) 7 | 8 | if BMI < 18.5 { 9 | println("偏瘦") 10 | } elif (18.5 <= BMI) && (BMI < 24) { 11 | println("正常") 12 | } elif 24 <= BMI && BMI < 28 { 13 | println("偏胖") 14 | } elif 28 <= BMI && BMI < 30 { 15 | println("肥胖") 16 | } elif BMI >= 30 { 17 | println("重度肥胖") 18 | } 19 | -------------------------------------------------------------------------------- /scripts/byteQueue.gox: -------------------------------------------------------------------------------- 1 | b1 = newObj("bytequeue", 6) 2 | 3 | pl("[%v] %#v %v", -1, b1, b1) 4 | 5 | for j = 0; j < b1.Size(); j ++ { 6 | item1 = b1.Get(j) 7 | prf(" %v", item1) 8 | } 9 | 10 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 11 | 12 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 13 | 14 | pln("remove 0:", b1.Remove(0)) 15 | 16 | pln("remove last:", b1.Remove(b1.Size())) 17 | 18 | pln("remove 3:", b1.Remove(3)) 19 | 20 | for i = 0; i < 20; i ++ { 21 | b1.Push(byte(i)) 22 | 23 | pl("[%v] %#v %v", i, b1, b1) 24 | 25 | for j = 0; j < b1.Size(); j ++ { 26 | item1 = b1.Get(j) 27 | prf(" %v", item1) 28 | } 29 | 30 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 31 | 32 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 33 | 34 | } 35 | 36 | b1.Insert(0, byte(100)) 37 | 38 | pl("-1 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 39 | 40 | for j = 0; j < b1.Size(); j ++ { 41 | item1 = b1.Get(j) 42 | prf(" %v", item1) 43 | } 44 | 45 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 46 | 47 | b1.Insert(3, byte(103)) 48 | 49 | pl("-2 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 50 | 51 | for j = 0; j < b1.Size(); j ++ { 52 | item1 = b1.Get(j) 53 | prf(" %v", item1) 54 | } 55 | 56 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 57 | 58 | b1.Insert(b1.Size()-1, byte(109)) 59 | 60 | pl("-3 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 61 | 62 | for j = 0; j < b1.Size(); j ++ { 63 | item1 = b1.Get(j) 64 | prf(" %v", item1) 65 | } 66 | 67 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 68 | 69 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 70 | 71 | // remove 0 72 | b1.Remove(0) 73 | 74 | pl("remove0 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 75 | 76 | for j = 0; j < b1.Size(); j ++ { 77 | item1 = b1.Get(j) 78 | prf(" %v", item1) 79 | } 80 | 81 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 82 | 83 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 84 | 85 | // remove last 86 | b1.Remove(b1.Size()-1) 87 | 88 | pl("removeLast [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 89 | 90 | for j = 0; j < b1.Size(); j ++ { 91 | item1 = b1.Get(j) 92 | prf(" %v", item1) 93 | } 94 | 95 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 96 | 97 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 98 | 99 | // remove 2 100 | b1.Remove(2) 101 | 102 | pl("remove2 [%v] %#v %v %v", 999, b1, b1, b1.GetInfo()) 103 | 104 | for j = 0; j < b1.Size(); j ++ { 105 | item1 = b1.Get(j) 106 | prf(" %v", item1) 107 | } 108 | 109 | pl(" F: %v L: %v", b1.Get(), b1.Get(-1)) 110 | 111 | pl("List: %#v %v", b1.GetList(), b1.GetList()) 112 | 113 | // // pop 114 | 115 | // cnt1 = 0 116 | // for { 117 | // a1 = b1.Pop() 118 | 119 | // if isErrX(a1) { 120 | // exit() 121 | // } 122 | 123 | // cnt1++ 124 | 125 | // pl("got %v", a1) 126 | 127 | // pl("[%v] %v S: %v", cnt1, b1, b1.Size()) 128 | 129 | // } 130 | 131 | // pick 132 | 133 | cnt1 = 0 134 | for { 135 | a1 = b1.Pick() 136 | 137 | if isErrX(a1) { 138 | exit() 139 | } 140 | 141 | cnt1++ 142 | 143 | pl("got %v", a1) 144 | 145 | pl("[%v] %v S: %v", cnt1, b1, b1.Size()) 146 | 147 | } -------------------------------------------------------------------------------- /scripts/calCosineSimilarity.gox: -------------------------------------------------------------------------------- 1 | // work out the cosine similarity of two vectors 2 | // the result is in [0..1], which 1 indicates almost the same, 0 indicates not same at all 3 | 4 | calCosSim = func(f1, f2) { 5 | l1 = len(f1) 6 | l2 = len(f2) 7 | 8 | if l1 != l2 { 9 | printfln("two vectors' length are not same,length of f1: %v,length of f2: %v", l1, l2) 10 | return -1 11 | } 12 | 13 | rr = 0.0 14 | f1r = 0.0 15 | f2r = 0.0 16 | 17 | for i = 0; i < l1; i++ { 18 | rr += f1[i] * f2[i] 19 | f1r += f1[i] * f1[i] 20 | f2r += f2[i] * f2[i] 21 | } 22 | 23 | rs = rr / (math.Sqrt(f1r) * math.Sqrt(f2r)) 24 | 25 | return rs 26 | } 27 | 28 | v1 = [1, 2, 3, 5] 29 | v2 = [2.0, 2, 3, 4] 30 | 31 | println(calCosSim(v1, v2)) 32 | 33 | v3 = [9, 9, 8, 8] 34 | println(calCosSim(v1, v3)) 35 | 36 | -------------------------------------------------------------------------------- /scripts/calCosineSimilarityBig.gox: -------------------------------------------------------------------------------- 1 | // work out the cosine similarity of two vectors 2 | // the result is in [0..1], which 1 indicates almost the same, 0 indicates not same at all 3 | 4 | // set the short name for math/big package 5 | big = math_big 6 | 7 | calCosineSimilarityBig = func(f1, f2) { 8 | 9 | l1 = len(f1) 10 | l2 = len(f2) 11 | 12 | if l1 != l2 { 13 | printfln("two vectors' length are not same,length of f1: %v,length of f2: %v", l1, l2) 14 | return -1 15 | } 16 | 17 | rr = big.NewFloat(0.0) 18 | 19 | f1r = big.NewFloat(0.0) 20 | 21 | f2r = big.NewFloat(0.0) 22 | 23 | for i = 0; i < l1; i++ { 24 | f1Sub = big.NewFloat(f1[i]) 25 | f2Sub = big.NewFloat(f2[i]) 26 | 27 | rr.Add(rr, big.NewFloat(0).Mul(f1Sub, f2Sub)) 28 | f1r.Add(f1r, big.NewFloat(0).Mul(f1Sub, f1Sub)) 29 | f2r.Add(f2r, big.NewFloat(0).Mul(f2Sub, f2Sub)) 30 | } 31 | 32 | tmp1 = big.NewFloat(0).Mul(big.NewFloat(0).Sqrt(f1r), big.NewFloat(0).Sqrt(f2r)) 33 | 34 | tmp2 = big.NewFloat(0).Quo(rr, tmp1) 35 | 36 | tmp3, _ = tmp2.Float64() 37 | 38 | return tmp3 39 | } 40 | 41 | 42 | v1 = [1, 2, 3, 5] 43 | v2 = [2.0, 2, 3, 4] 44 | 45 | println(calCosineSimilarityBig(v1, v2)) 46 | 47 | v3 = [9, 9, 8, 8] 48 | println(calCosineSimilarityBig(v1, v3)) 49 | 50 | println("------------") 51 | 52 | v1 = [111111, 2222222, 3333333, 55555555555555] 53 | v2 = [2.0, 2, 3, 4] 54 | 55 | println(calCosineSimilarityBig(v1, v2)) 56 | 57 | v3 = [7877358736587356853, 9666666, 8.01, 999999999999] 58 | println(calCosineSimilarityBig(v1, v3)) 59 | 60 | -------------------------------------------------------------------------------- /scripts/calculator.gox: -------------------------------------------------------------------------------- 1 | expression = getInput("Please enter the expression: ") 2 | 3 | result = eval(expression) 4 | 5 | println("result:", result) -------------------------------------------------------------------------------- /scripts/calculatorGUI.gox: -------------------------------------------------------------------------------- 1 | sciter = github_scitersdk_gosciter 2 | window = github_scitersdk_gosciter_window 3 | 4 | initGUI() 5 | 6 | htmlT := ` 7 | 8 | 9 | 10 | 11 | 12 | Calculator 13 | 14 | 15 |
16 | Please enter the expression: 17 |
18 |
19 | 20 |
21 |
22 | 23 | 24 |
25 | 26 | 40 | 41 | 42 | 43 | ` 44 | 45 | runtime.LockOSThread() 46 | 47 | w, err := window.New(sciter.DefaultWindowCreateFlag, sciter.DefaultRect) 48 | 49 | checkError(err) 50 | 51 | w.SetOption(sciter.SCITER_SET_SCRIPT_RUNTIME_FEATURES, sciter.ALLOW_EVAL|sciter.ALLOW_SYSINFO) 52 | 53 | w.LoadHtml(htmlT, "") 54 | 55 | w.SetTitle("Calculator") 56 | 57 | w.DefineFunction("prints", func(args) { 58 | tk.Pl("%v", args[0].String()) 59 | return sciter.NewValue("") 60 | }) 61 | 62 | w.Show() 63 | 64 | w.Run() -------------------------------------------------------------------------------- /scripts/call.gox: -------------------------------------------------------------------------------- 1 | func f1(a) { 2 | return a+1 3 | } 4 | 5 | println(f1(2)) -------------------------------------------------------------------------------- /scripts/chan.gox: -------------------------------------------------------------------------------- 1 | c = make(chan int) 2 | 3 | go fn() { 4 | for { 5 | c <- 1 6 | tk.SleepSeconds(1) 7 | } 8 | }() 9 | 10 | go fn() { 11 | for { 12 | c <- 200 13 | tk.SleepSeconds(1) 14 | } 15 | }() 16 | 17 | go fn() { 18 | for { 19 | tmp = <-c 20 | println(tmp) 21 | tk.SleepMilliSeconds(500) 22 | } 23 | }() 24 | 25 | for { 26 | tk.SleepSeconds(5) 27 | 28 | println("main thread") 29 | } -------------------------------------------------------------------------------- /scripts/charOracle.gox: -------------------------------------------------------------------------------- 1 | scriptT = ` 2 | param (...args) 3 | 4 | dbConnectStr := getSwitch(args, "-connect=") 5 | 6 | dbT := dbConnect("godror", dbConnectStr) 7 | 8 | if isError(dbT) { 9 | pl("failed to connect DB: %v", dbT) 10 | exit() 11 | } 12 | 13 | sqlT := "select count(*) from AWS2.BO_EU_RIGHTS_PROTECT_DATA" 14 | 15 | sqlRsT := dbQueryCount(dbT, sqlT) 16 | 17 | pl("result1: %v", sqlRsT) 18 | 19 | sqlT = "select * from AWS2.BO_EU_TEST1" 20 | 21 | sqlRs2T := dbQuery(dbT, sqlT) 22 | 23 | pl("result2: %v", sqlRs2T) 24 | 25 | sqlT = "select * from AWS2.BO_EU_TEST1" 26 | 27 | sqlRs3T := dbQueryRecs(dbT, sqlT) 28 | 29 | pl("result3: %v", sqlRs3T) 30 | 31 | sqlT = "update AWS2.BO_EU_TEST1 set ABC=:v1 where ID='8ceaf7f4-62e1-4915-85a9-138f0651d715'" 32 | 33 | sqlRs4T := dbExec(dbT, sqlT, "ABC"+getNowStr()) 34 | 35 | if isError(sqlRs4T) { 36 | pl("exec failed: %v", sqlRs4T) 37 | } else { 38 | pl("result4: %v", sqlRs4T) 39 | } 40 | 41 | dbClose(dbT) 42 | 43 | ` 44 | 45 | // connect string is like: user/password@127.0.0.1:1521/mydb 46 | quickRunChar(scriptT, toCharValue("-connect="+getSwitch(argsG, "-connect=", ""))) -------------------------------------------------------------------------------- /scripts/charms.gox: -------------------------------------------------------------------------------- 1 | vmT, errT = newChar(` 2 | param (...vargs) 3 | 4 | try { 5 | 6 | for i, v in vargs { 7 | println(i, v) 8 | } 9 | 10 | setRespHeader(vargs[1], "Content-Type", "text/json; charset=utf-8") 11 | setRespHeader(vargs[1], "Access-Control-Allow-Origin", "*") 12 | 13 | writeRespHeader(vargs[1], 200) 14 | 15 | println("writeResp:", writeResp(vargs[1], bytes(string(vargs[2])))) 16 | } catch err { 17 | printf("%+v\n", err) 18 | } 19 | 20 | 21 | 22 | `) 23 | 24 | if errT != nil { 25 | pl("compile failed: %v", errT) 26 | exit() 27 | } 28 | 29 | mux = net_http.NewServeMux() 30 | 31 | mux.HandleFunc("/", fn(w, req) { 32 | // fprintf(w, "host: %#v, path: %#v\n", req.Host, req.URL) 33 | 34 | runChar(vmT, nil, nil, *newCharAny(w), msiToCharMap(fromJSON(`{"start": "1", "count": "10"}`))) 35 | }) 36 | 37 | err = net_http.ListenAndServe(":8888", mux) 38 | if err != nil { 39 | fprintln(os.Stderr, err) 40 | } -------------------------------------------------------------------------------- /scripts/checkErrf.gox: -------------------------------------------------------------------------------- 1 | v, err =tk.FromJSON(`abc`) 2 | 3 | // checkErrf("err: %v", err) 4 | 5 | // pl("done 1") 6 | 7 | // checkErrf("[%v] err: %v", 1, err) 8 | 9 | // pl("done 2") 10 | 11 | v, err =tk.FromJSON(`{"abc": 1 23}`) 12 | 13 | checkErrf("[%v] %v err: %v", 1, nil, err) 14 | 15 | pl("done 3") 16 | -------------------------------------------------------------------------------- /scripts/class1.gox: -------------------------------------------------------------------------------- 1 | Person = class { 2 | fn setName(s) { 3 | this.name = s 4 | } 5 | 6 | fn say(s) { 7 | println(this.name, "says", s) 8 | } 9 | } 10 | 11 | person1 = new Person 12 | 13 | person1.setName("Tom") 14 | 15 | person1.say("Hello!") -------------------------------------------------------------------------------- /scripts/class2.gox: -------------------------------------------------------------------------------- 1 | Person = class { 2 | fn _init(nameA) { 3 | this.setName(nameA) 4 | } 5 | 6 | fn setName(s) { 7 | this.name = s 8 | } 9 | 10 | fn say(s) { 11 | printfln(`%v says "%v".`, this.name, s) 12 | } 13 | } 14 | 15 | person2 = new Person("Jerry") 16 | 17 | person2.say("I'm fine.") 18 | 19 | -------------------------------------------------------------------------------- /scripts/class3.gox: -------------------------------------------------------------------------------- 1 | Person = class { 2 | fn _init(argsA...) { 3 | lenT = len(argsA) 4 | 5 | if lenT > 0 { 6 | this.name = argsA[0] 7 | } 8 | 9 | if lenT > 1 { 10 | typeT = type(argsA[1]).String() 11 | if typeT == "string" { 12 | this.gender = argsA[1] 13 | } else { 14 | this.age = argsA[1] 15 | } 16 | } 17 | 18 | if lenT > 2 { 19 | typeT = type(argsA[2]).String() 20 | if typeT == "int" { 21 | this.age = argsA[2] 22 | } else { 23 | this.gender = argsA[2] 24 | } 25 | } 26 | 27 | if this.age == undefined { 28 | this.age = "unknown" 29 | } 30 | } 31 | 32 | fn info() { 33 | printfln(`Name: %v, Gender: %v, Age: %v`, this.name, this.gender, this.age) 34 | } 35 | } 36 | 37 | person3 = new Person("Lisa", "female", 18) 38 | 39 | person3.info() 40 | 41 | person4 = new Person("Michael", "male") 42 | 43 | person4.info() 44 | 45 | person5 = new Person("Tony", 9) 46 | 47 | person5.info() 48 | 49 | -------------------------------------------------------------------------------- /scripts/class4.gox: -------------------------------------------------------------------------------- 1 | Times = class { 2 | fn add(timeA, durationA) { 3 | return timeA.Add(durationA) 4 | } 5 | 6 | fn sub(time1, time2) { 7 | return time1.Sub(time2) 8 | } 9 | } 10 | 11 | t1 = time.now() 12 | 13 | printfln("t1 + 3min = %v", Times.add(nil, t1, time.Second * 60)) 14 | 15 | instance1 = new Times 16 | 17 | printfln("%v", instance1.add(t1, time.Second * 60)) -------------------------------------------------------------------------------- /scripts/cmd.gox: -------------------------------------------------------------------------------- 1 | cmd = github_gocmd_cmd 2 | 3 | findCmd := cmd.NewCmd("dir", ".", "/s") 4 | statusChan := findCmd.Start() // non-blocking 5 | 6 | // Print last line of stdout every 2s 7 | go func() { 8 | for { 9 | status := findCmd.Status() 10 | n := len(status.Stdout) 11 | fmt.Println(status.Stdout[n-1]) 12 | 13 | sleep(2.0) 14 | } 15 | }() 16 | 17 | // Stop command after 1 hour 18 | go func() { 19 | <-time.After(1 * time.Hour) 20 | findCmd.Stop() 21 | }() 22 | 23 | // Check if command is done 24 | // select { 25 | // case finalStatus := <-statusChan: 26 | // fmt.Println("finalStatus:", finalStatus) 27 | // // done 28 | // default: 29 | // // no, still running 30 | // } 31 | 32 | // go func() { 33 | // finalStatus := <-statusChan 34 | 35 | // if finalStatus != undefined { 36 | // fmt.Println("finalStatus:", finalStatus) 37 | // } 38 | // } 39 | 40 | // Block waiting for command to exit, be stopped, or be killed 41 | finalStatus := <-statusChan 42 | 43 | fmt.Println("finalStatus:", finalStatus) -------------------------------------------------------------------------------- /scripts/commandLine.gox: -------------------------------------------------------------------------------- 1 | args = os.Args 2 | 3 | for i, v = range args { 4 | pl("命令行参数%v:%v", i, v) 5 | } 6 | 7 | for i, v = range argsG { 8 | pl("精简命令行参数%v:%v", i, v) 9 | } 10 | 11 | pass() 12 | -------------------------------------------------------------------------------- /scripts/commandLineCN.gox: -------------------------------------------------------------------------------- 1 | // test command-line functions 2 | // for example: gox scripts\commandLine.gox abc -file=a.txt 3 | 4 | // 获取所有命令行参数 5 | println("The whole command-line: ", os.Args) 6 | 7 | // 获取除第一个命令行参数(一般是gox主程序名)之外的其他命令行参数 8 | argsG = os.Args[1:] 9 | println("The whole command-line without executable: ", argsG) 10 | 11 | // 获取命令行参数个数(下面均指去掉了第一个参数后的命令行参数) 12 | lenT = len(argsG) 13 | 14 | // 输出第一个命令行参数 15 | if lenT > 0 { 16 | printfln("The first command-line element is: %v", argsG[0]) 17 | } 18 | 19 | // 输出第二个命令行参数 20 | if lenT > 1 { 21 | printfln("The sencod command-line element is: %v", argsG[1]) 22 | } 23 | 24 | // 安全获取第二个(序号为1)命令行参数,如果没有则返回默认值空字符串 25 | para1 = tk.GetParameterByIndexWithDefaultValue(argsG, 1, "") 26 | pl("para1=%v", para1) 27 | 28 | // 安全获取第三个(序号为2)命令行参数,如果没有则返回默认值空字符串 29 | para2 = tk.GetParameterByIndexWithDefaultValue(argsG, 2, "") 30 | pl("para2=%v", para2) 31 | 32 | // 安全获取开关参数-file=的值(形如-file=a.txt),如果不存在则返回默认值空字符串 33 | switch1 = tk.GetSwitchWithDefaultValue(argsG, "-file=", "") 34 | 35 | pln("switch1:", switch1) 36 | 37 | // 获取所有非开关参数的命令行参数并输出 38 | paras = tk.GetAllParameters(argsG) 39 | pln("All parameters:", paras) 40 | 41 | // 获取所有开关参数的命令行参数并输出 42 | switches = tk.GetAllSwitches(argsG) 43 | pln("All switches:", switches) 44 | 45 | // 判断是否存在开关参数-file,-files这样的不算 46 | pln(tk.IfSwitchExistsWhole(argsG, "-file")) 47 | 48 | // 判断是否存在以-file开始的开关参数,因此-files也算存在 49 | pln(tk.IfSwitchExists(argsG, "-file")) -------------------------------------------------------------------------------- /scripts/comment.gox: -------------------------------------------------------------------------------- 1 | // 单行的注释,以两个斜杠字符“/”开始,范围到本行结束为止 2 | 3 | a = 1 // 单行的注释也可以从一行的中间开始,这时候“//”之前的仍然是有效代码,之后的才是注释 4 | 5 | /* 6 | 多行的注释与C语言一样, 7 | 用“/*”标志开始, 8 | 用“* /”(中间没有空格)标志结束。 9 | */ 10 | 11 | pln(a + a) 12 | 13 | a = 18 14 | 15 | for a > 0 { 16 | pln("a=", a); 17 | 18 | a = a - 1 19 | 20 | /* 21 | a = a + 2 22 | a = b 23 | */ 24 | } -------------------------------------------------------------------------------- /scripts/concurrent.gox: -------------------------------------------------------------------------------- 1 | func a() { 2 | for { 3 | if v1 == undefined || isNil(v1) { 4 | v1 = 0.0 5 | } else { 6 | v1 = v1 + 0.1 7 | } 8 | 9 | pln("av1:"+ v1) 10 | 11 | if v2 == undefined || isNil(v2) { 12 | v2 = 0.0 13 | } else { 14 | v2 = v2 + 0.1 15 | } 16 | 17 | pln("av2:"+ v2) 18 | } 19 | } 20 | 21 | func b() { 22 | for { 23 | if v1 == undefined || isNil(v1) { 24 | v1 = 0 25 | } else { 26 | v1 = v1 + 1 27 | } 28 | 29 | pln("bv1:"+ v1) 30 | 31 | if v2 == undefined || isNil(v2) { 32 | v2 = 0.0 33 | } else { 34 | v2 = v2 - 0.1 35 | } 36 | 37 | pln("bv2:"+ v2) 38 | } 39 | } 40 | 41 | go a() 42 | 43 | go b() 44 | 45 | for { 46 | if v1 == undefined || isNil(v1) { 47 | v1 = 0 48 | } else { 49 | v1 = v1 + 1 50 | } 51 | 52 | pln("mv1:"+ v1) 53 | 54 | // pln("mv2:"+ v2) 55 | 56 | } -------------------------------------------------------------------------------- /scripts/dataTypeConversion.gox: -------------------------------------------------------------------------------- 1 | a = 1 2 | b = int64(2) 3 | 4 | println("type of a is:", type(a)) 5 | println("type of b is:", type(b)) 6 | 7 | println("a + b =", a+b) 8 | printfln("a + b = %#v", a+b) 9 | 10 | a1 = tk.IntToStr(a) 11 | b1 = tk.IntToStr(b) 12 | 13 | printfln("type of a1 is: %T", a1) 14 | printfln("value of a1 is: %v", a1) 15 | printfln("internal value of a1 is: %#v", a1) 16 | 17 | println("a1 + b1 =", a1+b1) 18 | printfln("a1 + b1 = %#v", a1+b1) 19 | 20 | a2 = tk.StrToFloat64WithDefaultValue(a1, 0) 21 | b2 = tk.StrToFloat64WithDefaultValue(b1, 0) 22 | 23 | printfln("a2 + b2 = %#v", a2+b2) 24 | printfln("type of a2 + b2 is: %T", a2+b2) -------------------------------------------------------------------------------- /scripts/dataTypes.gox: -------------------------------------------------------------------------------- 1 | // Assign value to variables 2 | 3 | a = 3 4 | 5 | printfln("[%T] %v", a, a) 6 | 7 | b = 1.2 8 | 9 | printfln("[%T] %v", b, b) 10 | 11 | a = "abc" 12 | 13 | printfln("[%T] %v", a, a) 14 | 15 | println("------") 16 | 17 | a = 1 18 | 19 | f1 = fn() { 20 | a; a = 6 21 | } 22 | f1() 23 | 24 | println("a:", a) 25 | 26 | println("------") 27 | 28 | a = 1 29 | fn(c) { 30 | a = c 31 | 32 | b = a 33 | 34 | a = b + 9 35 | }(a) 36 | println(a) 37 | 38 | println("------") 39 | 40 | // Boolean 41 | 42 | b = true 43 | 44 | printf("[%T] %v\n", b, b) 45 | 46 | c = false 47 | 48 | printf("[%T] %v\n", c, c) 49 | 50 | printf("!b = %v\n", !b) 51 | 52 | printf("b == c: %v\n", b == c) 53 | 54 | printf("1 > 14: %v\n", 1 > 14) 55 | 56 | printf("b == true: %v\n", b == true) 57 | 58 | printf("b && c: %v\n", b && c) 59 | 60 | printf("b || c: %v\n", b || c) 61 | 62 | println("------") 63 | 64 | // Integer 65 | 66 | c1 = 19 67 | 68 | c2 = 18 69 | 70 | println(c1 + c2/3) 71 | 72 | printfln("%T, %v", c1, c1) 73 | 74 | printfln("%T", c1+c2) 75 | printfln("%T", c2/3) 76 | printfln("%T", c1+c2/3) 77 | printfln("%T, %v", (c1+c2/3)*6, (c1+c2/3)*6) 78 | 79 | c1++ 80 | c1 *= 3 81 | 82 | c2 += 5 83 | c2-- 84 | 85 | printfln("c1: %v, c2: %v, %T", c1, c2, c1) 86 | 87 | println("------") 88 | 89 | // Float 90 | 91 | f1 = 1.32 92 | 93 | previus_f1 = f1 94 | 95 | f1 = f1 * 0.8 96 | 97 | print(previus_f1, "*", 0.8, "=", f1) 98 | println() 99 | 100 | f2 = 0.99 101 | f2 /= 0.3 102 | 103 | print(0.99, "/", 0.3, "=", f2, "\n") 104 | 105 | println("------") 106 | 107 | // String and Byte 108 | 109 | s1 = "abc" 110 | 111 | s2 = s1 + "3" 112 | 113 | pv("s2") 114 | 115 | println(s1, "+", "3", "=", s2) 116 | 117 | s5 = "上善若水" 118 | 119 | pv("s5") 120 | 121 | s6 = []byte(s5) 122 | 123 | println(s6) 124 | 125 | t = rune(5) 126 | pv("t") 127 | 128 | s7 = []rune("上善若水") 129 | 130 | pv("s7") 131 | 132 | pl("s5[1:2] = %#v", s5[1:2]) 133 | 134 | pl("s6[1:2] = %#v", s6[1:2]) 135 | 136 | pl("s7[1:2] = %#v", s7[1:2]) 137 | 138 | pl("string(s7[1:3]) = %#v", string(s7[1:3])) 139 | 140 | pl("string([]byte(string(s7[1:3]))) = %#v", string([]byte(string(s7[1:3])))) 141 | 142 | pl("%c", s5[1]) 143 | pl("%c", s6[1]) 144 | pl("%c", s7[1]) 145 | 146 | pl("%T, %#v", s5[1], s5[1]) 147 | pl("%T, %#v", s6[1], s6[1]) 148 | pl("%T, %#v", s7[1], s7[1]) 149 | 150 | for i = 0; i < len(s5); i++ { 151 | pl("%v: %v", i, s5[i]) 152 | } 153 | 154 | for v = range s7 { 155 | pl("%#T, %v", byte(v), byte(v)) 156 | } 157 | 158 | println("------") 159 | 160 | // nil type 161 | 162 | pv("aaa") 163 | 164 | println(aaa) 165 | 166 | aaa = 18 167 | 168 | pv("aaa") 169 | 170 | println("aaa") 171 | 172 | b = nil 173 | 174 | pv("b") 175 | 176 | println(b) 177 | 178 | println("------") 179 | 180 | c, errT = tk.StrToInt("12ab") 181 | 182 | if errT != nil { 183 | println("Error:", errT.Error()) 184 | } 185 | 186 | pv("c") 187 | 188 | pv("errT") 189 | 190 | c, errT = tk.StrToInt("123") 191 | 192 | pv("c") 193 | 194 | pv("errT") 195 | 196 | if errT != nil { 197 | println("Error:", errT.Error()) 198 | } 199 | 200 | println("------") 201 | 202 | // Conversion 203 | 204 | a = 1 205 | b = int64(2) 206 | 207 | println("type of a is:", type(a)) 208 | println("type of b is:", type(b)) 209 | 210 | println("a + b =", a+b) 211 | printfln("a + b = %#v", a+b) 212 | 213 | a1 = tk.IntToStr(a) 214 | b1 = tk.IntToStr(b) 215 | 216 | printfln("type of a1 is: %T", a1) 217 | printfln("value of a1 is: %v", a1) 218 | printfln("internal value of a1 is: %#v", a1) 219 | 220 | println("a1 + b1 =", a1+b1) 221 | printfln("a1 + b1 = %#v", a1+b1) 222 | 223 | a2 = tk.StrToFloat64WithDefaultValue(a1, 0) 224 | b2 = tk.StrToFloat64WithDefaultValue(b1, 0) 225 | 226 | printfln("a2 + b2 = %#v", a2+b2) 227 | printfln("type of a2 + b2 is: %T", a2+b2) 228 | 229 | getInputf("Press enter to exit...") 230 | -------------------------------------------------------------------------------- /scripts/debug.gox: -------------------------------------------------------------------------------- 1 | a = 3 2 | 3 | func f() { 4 | pl(abc) 5 | b.Show(1) 6 | } 7 | 8 | print(a) 9 | 10 | f() 11 | -------------------------------------------------------------------------------- /scripts/debug2.gox: -------------------------------------------------------------------------------- 1 | a = 3 2 | 3 | func f() { 4 | a = a + 1 5 | if a < 10 { 6 | pl("a=%v", a) 7 | } 8 | pl(abc) 9 | b.Show(1) 10 | } 11 | 12 | print(a) 13 | 14 | f() 15 | -------------------------------------------------------------------------------- /scripts/debug3.gox: -------------------------------------------------------------------------------- 1 | a = 3 2 | 3 | func f() { 4 | a = a + 1 5 | if a < 10 { 6 | pal("a=%v", a) 7 | } 8 | pl(abc) 9 | b.Show(1) 10 | } 11 | 12 | print(a) 13 | 14 | f() 15 | -------------------------------------------------------------------------------- /scripts/deep.gox: -------------------------------------------------------------------------------- 1 | person1 = make(struct { 2 | Name string, 3 | Age int 4 | }) 5 | 6 | person1.Name = "John" 7 | person1.Age = 20 8 | 9 | pl("person1: %#v", person1) 10 | 11 | println("-------") 12 | 13 | person2 = person1 14 | 15 | person2.Name = "Tom" 16 | person2.Age = 23 17 | 18 | pl("person1: %#v", person1) 19 | pl("person2: %#v", person2) 20 | 21 | println("-------") 22 | 23 | p = deepClone(&person1) 24 | p.Name = "Jerry" 25 | person3 = *p 26 | person3.Age = 21 27 | 28 | pl("person1: %#v", person1) 29 | pl("person3: %#v", person3) 30 | 31 | println("-------") 32 | 33 | a = 1.8 34 | 35 | pv("a") 36 | 37 | b = a 38 | 39 | a = 3.2 40 | 41 | pv("a") 42 | pv("b") -------------------------------------------------------------------------------- /scripts/deepClone.gox: -------------------------------------------------------------------------------- 1 | person1 = make(struct { 2 | Name string, 3 | Age int 4 | }) 5 | 6 | person1.Name = "John" 7 | person1.Age = 20 8 | 9 | pl("%#v", person1) 10 | 11 | p = deepClone(&person1) 12 | person2 = *p 13 | person2.Name = "abc" 14 | person2.Age = 19 15 | 16 | pv("person1") 17 | pv("person2") 18 | -------------------------------------------------------------------------------- /scripts/defer.gox: -------------------------------------------------------------------------------- 1 | defer fn() { 2 | r = recover() 3 | if r != nil { 4 | println("recover:", r) 5 | } 6 | }() 7 | 8 | f, err = os.Open("file.ql") 9 | if err != nil { 10 | fprintln(os.Stderr, err) 11 | return 1 12 | } 13 | defer println("exit!") 14 | defer f.Close() 15 | 16 | println(10/0) 17 | 18 | b = make([]byte, 8) 19 | n, err = f.Read(b) 20 | if err != nil { 21 | fprintln(os.Stderr, "Read failed:", err) 22 | return 2 23 | } 24 | 25 | println(string(b[:n])) -------------------------------------------------------------------------------- /scripts/dialogs.gox: -------------------------------------------------------------------------------- 1 | dlgs = github_topxeq_dlgs 2 | 3 | // rs = dlgs.Entry("Please enter...", "Gender", "") 4 | 5 | // pv("rs") 6 | 7 | // rs = getDateGUI("Please select...", "%v date", "Start") 8 | 9 | // pv("rs") 10 | 11 | rs = getColorGUI("Please select the color...") 12 | 13 | pv("rs") 14 | -------------------------------------------------------------------------------- /scripts/downloadFile1.gox: -------------------------------------------------------------------------------- 1 | grab = github_cavaliercoder_grab 2 | 3 | resp, err = grab.Get(".", "https://github.com/cmderdev/cmder/releases/download/v1.3.16/cmder_mini.zip") 4 | if err != nil { 5 | plerr(err) 6 | exit() 7 | } 8 | 9 | println("Download saved to", resp.Filename) 10 | 11 | pass() -------------------------------------------------------------------------------- /scripts/downloadFile2.gox: -------------------------------------------------------------------------------- 1 | grab = github_cavaliercoder_grab 2 | 3 | client := grab.NewClient() 4 | req, _ := grab.NewRequest(".", "https://github.com/cmderdev/cmder/releases/download/v1.3.16/cmder_mini.zip") 5 | 6 | fmt.Printf("Downloading %v...\n", req.URL()) 7 | resp := client.Do(req) 8 | fmt.Printf(" %v\n", resp.HTTPResponse.Status) 9 | 10 | // 启动一个线程,每个100毫秒输出一次下载状态 11 | go func() { 12 | for { 13 | tk.SleepMilliSeconds(100) 14 | fmt.Printf("\r transferred %v / %v bytes (%.2f%%)", 15 | resp.BytesComplete(), 16 | resp.Size(), 17 | 100*resp.Progress()) 18 | } 19 | }() 20 | 21 | err := resp.Err() 22 | 23 | if err != nil { 24 | fmt.Fprintf(os.Stderr, "Download failed: %v\n", err) 25 | os.Exit(1) 26 | } 27 | 28 | fmt.Printf("Download saved to ./%v \n", resp.Filename) 29 | 30 | pass() -------------------------------------------------------------------------------- /scripts/editFileSciter1.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Gox Editor 8 | 9 | 10 | 11 |
12 |
13 | 14 | 15 | 16 |
17 | abc 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /scripts/encryptDataWithHead.gox: -------------------------------------------------------------------------------- 1 | s1 := "abc123天气好!" 2 | 3 | b1 := []byte(s1) 4 | 5 | plo(b1) 6 | 7 | e1 := encryptData(b1, "", "-addHead") 8 | 9 | plo(e1) 10 | 11 | e2 := encryptData(b1, "") 12 | 13 | plo(e2) 14 | 15 | ue1 := decryptData(e1, "") 16 | 17 | plo(ue1, string(ue1)) 18 | 19 | ue2 := decryptData(e2, "") 20 | 21 | plo(ue2, string(ue2)) 22 | -------------------------------------------------------------------------------- /scripts/enlargeImage.gox: -------------------------------------------------------------------------------- 1 | // 引入imagetk包,获得ImageTK对象 2 | itk = imagetk.NewImageTK() 3 | 4 | // 获取命令行参数中指定要转换的图像文件名(第3个参数,序号为2,第1个参数是gox主程序,第2个是本脚本文件路径,第3个才是真正的参数) 5 | fileNameT = getParameter(os.Args, 2, "") 6 | 7 | pl("convert file: %v", fileNameT) 8 | 9 | // 加载图像文件中的文件到内存变量imageT中 10 | imageT, errT = itk.LoadImage(fileNameT) 11 | 12 | // 检查如果出现错误则中止程序运行 13 | checkError(errT) 14 | 15 | // 调用imagetk库中的EnlargeImage函数将图片放大4.5倍存入新内存变量newImageT中 16 | newImageT, errT = itk.EnlargeImage(imageT, 4.5) 17 | 18 | checkError(errT) 19 | 20 | // 将放大后的图片保存为新文件名 21 | itk.SaveImageAs(newImageT, fileNameT+".new.png", "") -------------------------------------------------------------------------------- /scripts/evalx.gox: -------------------------------------------------------------------------------- 1 | env = {} 2 | 3 | env.Field1 = "1" 4 | env.Field2 = "2" 5 | 6 | plv(env) 7 | 8 | vm = tk.NewEval("Field1 + Field2", env) 9 | 10 | r, err = tk.RunEval(vm, env) 11 | 12 | pln(r, err) -------------------------------------------------------------------------------- /scripts/excelRead.gox: -------------------------------------------------------------------------------- 1 | // 从命令行参数获取要打开的Excel文件路径 2 | filePathT = trim(getSwitch(argsG, "-file=", "")) 3 | 4 | // 文件名不能为空 5 | if filePathT == "" { 6 | fatalf("empty file name") 7 | } 8 | 9 | pl("try open %v ...", filePathT) 10 | 11 | // excelOpen指令用于打开一个Excel文件,获得文件对象 12 | excelT, errT = excelize.OpenFile(filePathT) 13 | 14 | checkErrX(errT) 15 | 16 | // defer执行保证程序退出时被执行 17 | defer excelT.Close() 18 | 19 | rowsT, errT = excelT.GetRows(excelT.GetSheetName(0)) 20 | 21 | checkErrX(errT) 22 | 23 | plv(rowsT) 24 | 25 | -------------------------------------------------------------------------------- /scripts/excelToCSV.gox: -------------------------------------------------------------------------------- 1 | excel = github_360EntSecGroupSkylar_excelize 2 | 3 | fileNameT = getParameter(argsG, 1, "") 4 | 5 | if fileNameT == "" { 6 | pl("not enough parameters") 7 | exit() 8 | } 9 | 10 | f, errT = excel.OpenFile(fileNameT) 11 | checkError(errT) 12 | 13 | sheets = f.GetSheetList() 14 | 15 | lenT = len(sheets) 16 | 17 | fixColumnT = ifSwitchExists(argsG, "-fixColumn") 18 | 19 | if lenT <= 1 { 20 | rowsT, errT = f.GetRows(sheets[0]) 21 | checkError(errT) 22 | 23 | if fixColumnT { 24 | colLenT = len(rowsT[0]) 25 | 26 | for i, v := range rowsT { 27 | if i == 0 { 28 | continue 29 | } 30 | 31 | diffG = colLenT - len(v) 32 | 33 | if diffG > 0 { 34 | for j = 0; j < diffG; j ++ { 35 | rowsT[i] = append(rowsT[i], "") 36 | } 37 | } 38 | } 39 | } 40 | 41 | of, err = os.Create(fileNameT+".csv") 42 | checkError(err) 43 | 44 | defer of.Close() 45 | 46 | w = encoding_csv.NewWriter(of) 47 | 48 | w.WriteAll(rowsT) 49 | 50 | errT = w.Error() 51 | 52 | checkErrf("failed to write output csv file: %v", errT) 53 | 54 | } else { 55 | 56 | func saveCSV(idxA) { 57 | rowsT, errT = f.GetRows(sheets[idxA]) 58 | checkError(errT) 59 | 60 | of, err = os.Create(sprintf("%v_%d.csv", fileNameT, idxA+1)) 61 | checkError(err) 62 | 63 | defer of.Close() 64 | 65 | w = encoding_csv.NewWriter(of) 66 | 67 | w.WriteAll(rowsT) 68 | 69 | errT = w.Error() 70 | 71 | checkErrf("failed to write output csv file: %v", errT) 72 | } 73 | 74 | for i, _ = range sheets { 75 | saveCSV(i) 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /scripts/fib.char: -------------------------------------------------------------------------------- 1 | fibonacci = func(c) { 2 | if c < 2 { 3 | return c 4 | } 5 | 6 | return fibonacci(c-2) + fibonacci(c-1) 7 | } 8 | 9 | startTime = getNowStr() 10 | 11 | resultInt = fibonacci(10) 12 | 13 | endTime = getNowStr() 14 | 15 | pl("Result: %v\n", resultInt) 16 | 17 | pl("Duration: %v %v\n", startTime, endTime) -------------------------------------------------------------------------------- /scripts/fib.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func fibonacci(c int64) int64 { 9 | if c < 2 { 10 | return c 11 | } 12 | 13 | return fibonacci(c-2) + fibonacci(c-1) 14 | } 15 | 16 | func main() { 17 | startTime := time.Now() 18 | 19 | resultInt := fibonacci(50) 20 | 21 | endTime := time.Now() 22 | 23 | fmt.Printf("Result: %v\n", resultInt) 24 | 25 | fmt.Printf("Duration: %v\n", endTime.Sub(startTime)) 26 | 27 | } 28 | -------------------------------------------------------------------------------- /scripts/fib.gox: -------------------------------------------------------------------------------- 1 | func fibonacci(c) { 2 | if c < 2 { 3 | return c 4 | } 5 | 6 | return fibonacci(c-2) + fibonacci(c-1) 7 | } 8 | 9 | startTime = time.Now() 10 | 11 | resultInt = fibonacci(35) 12 | 13 | endTime = time.Now() 14 | 15 | fmt.Printf("Result: %v\n", resultInt) 16 | 17 | fmt.Printf("Duration: %v\n", endTime.Sub(startTime) / time.Second) -------------------------------------------------------------------------------- /scripts/fib.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import time 3 | 4 | def fib(n): 5 | if n < 2: 6 | return n 7 | 8 | return fib(n-1) + fib(n-2) 9 | 10 | startTime = datetime.datetime.now() 11 | 12 | print(fib(35)) 13 | 14 | endTime = datetime.datetime.now() 15 | 16 | print("Duration: ", endTime - startTime) 17 | 18 | -------------------------------------------------------------------------------- /scripts/fibFlat.gox: -------------------------------------------------------------------------------- 1 | func fibonacciFlat(c) { 2 | if c < 2 { 3 | return c 4 | } 5 | 6 | fibo = 1 7 | fiboPrev = 1 8 | for i = 2; i < c; i++ { 9 | temp = fibo 10 | fibo += fiboPrev 11 | fiboPrev = temp 12 | } 13 | 14 | return fibo 15 | } 16 | 17 | n = toInt(getParam(argsG, 1)) 18 | 19 | startTime = time.Now() 20 | 21 | result = fibonacciFlat(n) 22 | 23 | endTime = time.Now() 24 | 25 | fmt.Printf("Result: %v\n", result) 26 | 27 | fmt.Printf("Duration: %v s\n", tk.ToFloat(endTime.Sub(startTime)) / 1000000000.0) 28 | -------------------------------------------------------------------------------- /scripts/findStringDiffPos.gox: -------------------------------------------------------------------------------- 1 | s1 := "abc123+-*/" 2 | 3 | s2 := "abc163+-*/" 4 | 5 | pln(strFindDiffPos(s1, s2)) 6 | 7 | -------------------------------------------------------------------------------- /scripts/funcArg.gox: -------------------------------------------------------------------------------- 1 | func f1(idxA, argA) { 2 | for true { 3 | pl("f1[%v]: %v", idxA, argA) 4 | sleep(1.1) 5 | } 6 | } 7 | 8 | func f2(argA) { 9 | for true { 10 | pl("f2: %v", argA) 11 | sleep(1.3) 12 | } 13 | } 14 | 15 | go f1(1, 1) 16 | go f1(2, "a") 17 | go f2([6]) 18 | 19 | for { 20 | sleep(2.7) 21 | } -------------------------------------------------------------------------------- /scripts/funcVar.gox: -------------------------------------------------------------------------------- 1 | func f1() { 2 | a = 1 3 | 4 | for true { 5 | pl("a1=%v", a) 6 | 7 | sleep(1.1) 8 | } 9 | } 10 | 11 | func f2() { 12 | a = "abc" 13 | 14 | for true { 15 | pl("a2=%v", a) 16 | 17 | sleep(1.3) 18 | } 19 | } 20 | 21 | go f1() 22 | go f2() 23 | 24 | for true { 25 | // pl("a=%v", a) 26 | sleep(2.7) 27 | } -------------------------------------------------------------------------------- /scripts/functionType.gox: -------------------------------------------------------------------------------- 1 | myAdd = fn(a, b) { 2 | return a + b + b 3 | } 4 | 5 | c = myAdd(3, 5) 6 | 7 | println(c) 8 | 9 | upperPrintln = fn(s ...) { 10 | for _, v = range(s) { 11 | if typeOf(v) == "string" { 12 | print(tk.ToUpper(v)) 13 | } else { 14 | printf("%v", v) 15 | } 16 | } 17 | 18 | println() 19 | } 20 | 21 | upperPrintln("a", "bcd", 123) 22 | 23 | sum = fn(n...) { 24 | t = 0 25 | for _, a = range(n) { 26 | t += a 27 | } 28 | return t 29 | } 30 | 31 | println(sum(1, 2, 3, 1.8)) 32 | 33 | println2 = fn(s...) { 34 | println(s...) 35 | println(s) 36 | println() 37 | } 38 | 39 | println2(1, "abc", 2.6, true) 40 | 41 | println2(myAdd(2.9 ,7.1)) 42 | -------------------------------------------------------------------------------- /scripts/generateImport.gox: -------------------------------------------------------------------------------- 1 | // Usage: gox c:\goprjs\src\github.com\topxeq\gox\scripts\generateImport.gox -file=c:\goprjs\src\github.com\topxeq\tk\tk.go -package=tk > a.txt 2 | // 3 | 4 | var tk = import("tk") 5 | var os = import("os") 6 | 7 | argsT = os.Args 8 | 9 | println(os.Args) 10 | 11 | fileNameT = tk.GetSwitchWithDefaultValue(argsT, "-file=", "") 12 | 13 | 14 | packageNameT = tk.GetSwitchWithDefaultValue(argsT, "-package=", "") 15 | 16 | if packageNameT == "" { 17 | printfln("not enough parameters") 18 | os.Exit(1) 19 | } 20 | 21 | printfln("package name: %v", packageNameT) 22 | 23 | if fileNameT == "" { 24 | printfln("not enough parameters") 25 | exit() 26 | } 27 | 28 | printfln("file name: %v", fileNameT) 29 | 30 | fcT = tk.LoadStringFromFile(fileNameT) 31 | 32 | if tk.IsErrorString(fcT) { 33 | printfln("failed to load file content: %v", tk.GetErrorString(fcT)) 34 | exit() 35 | } 36 | 37 | pl("file content: ", fcT) 38 | 39 | aryT = tk.RegFindAll(fcT, `(?m)^func\s*([A-Z]\S*?)\(`, 1) 40 | 41 | pl("found: %v", aryT) 42 | 43 | for v in aryT { 44 | printfln("%#v: reflect.ValueOf(%v.%v),", v, packageNameT, v) 45 | } -------------------------------------------------------------------------------- /scripts/generategoxc.gox: -------------------------------------------------------------------------------- 1 | gopathT = os.Getenv("GOPATH") 2 | 3 | if gopathT == "" { 4 | pl("GOPATH not defined") 5 | return 6 | } 7 | 8 | sourceFileNameT = tk.JoinPath(gopathT, "/src/github.com/topxeq/gox/gox.go") 9 | 10 | fcT = tk.LoadStringFromFile(sourceFileNameT) 11 | 12 | if tk.IsErrorString(fcT) { 13 | pl("load source file failed: %v", tk.GetErrorString(fcT)) 14 | return 15 | } 16 | 17 | foundT = tk.RegFindFirst(fcT, `(?m)// GUI related start[\s\S]*?// GUI related end`, 0) 18 | 19 | if tk.IsErrorString(foundT) { 20 | pl("GUI part not found, maybe not expected source file: %v", tk.GetErrorString(foundT)) 21 | return 22 | } 23 | 24 | fcNewT = tk.RegReplace(fcT, `(?m)// GUI related start[\s\S]*?// GUI related end`, "") 25 | 26 | tk.EnsureMakeDirs(tk.JoinPath(gopathT, "/src/github.com/topxeq/goxc")) 27 | 28 | newFilePathT = tk.JoinPath(gopathT, "/src/github.com/topxeq/goxc/goxc.go") 29 | 30 | rsT = tk.SaveStringToFile(fcNewT, newFilePathT) 31 | 32 | if tk.IsErrorString(rsT) { 33 | pl("failed to save destination file: %v", tk.GetErrorString(rsT)) 34 | return 35 | } 36 | 37 | sourceFileNameT = tk.JoinPath(gopathT, "/src/github.com/topxeq/gox/embed.go") 38 | 39 | fcT = tk.LoadStringFromFile(sourceFileNameT) 40 | 41 | if tk.IsErrorString(fcT) { 42 | pl("load source file failed: %v", tk.GetErrorString(fcT)) 43 | return 44 | } 45 | 46 | newFilePathT = tk.JoinPath(gopathT, "/src/github.com/topxeq/goxc/embed.go") 47 | 48 | rsT = tk.SaveStringToFile(fcT, newFilePathT) 49 | 50 | if tk.IsErrorString(rsT) { 51 | pl("failed to save destination file: %v", tk.GetErrorString(rsT)) 52 | return 53 | } 54 | 55 | sourceFileNameT = tk.JoinPath(gopathT, "/src/github.com/topxeq/gox/comp.go") 56 | 57 | fcT = tk.LoadStringFromFile(sourceFileNameT) 58 | 59 | if tk.IsErrorString(fcT) { 60 | pl("load source file failed: %v", tk.GetErrorString(fcT)) 61 | return 62 | } 63 | 64 | newFilePathT = tk.JoinPath(gopathT, "/src/github.com/topxeq/goxc/comp.go") 65 | 66 | rsT = tk.SaveStringToFile(fcT, newFilePathT) 67 | 68 | if tk.IsErrorString(rsT) { 69 | pl("failed to save destination file: %v", tk.GetErrorString(rsT)) 70 | return 71 | } 72 | 73 | pl("Done") -------------------------------------------------------------------------------- /scripts/generategoxct.gox: -------------------------------------------------------------------------------- 1 | gopathT = os.Getenv("GOPATH") 2 | 3 | if gopathT == "" { 4 | pl("GOPATH not defined") 5 | return 6 | } 7 | 8 | sourceFileNameT = tk.JoinPath(gopathT, "/src/github.com/topxeq/gox/gox.go") 9 | 10 | fcT = tk.LoadStringFromFile(sourceFileNameT) 11 | 12 | if tk.IsErrorString(fcT) { 13 | pl("load source file failed: %v", tk.GetErrorString(fcT)) 14 | return 15 | } 16 | 17 | foundT = tk.RegFindFirst(fcT, `(?m)// GUI related start[\s\S]*?// GUI related end`, 0) 18 | 19 | if tk.IsErrorString(foundT) { 20 | pl("GUI part not found, maybe not expected source file: %v", tk.GetErrorString(foundT)) 21 | return 22 | } 23 | 24 | fcNewT = tk.RegReplace(fcT, `(?m)// GUI related start[\s\S]*?// GUI related end`, "") 25 | 26 | fcNewT = tk.RegReplace(fcNewT, `(?m)// full version related start[\s\S]*?// full version related end`, "") 27 | 28 | tk.EnsureMakeDirs(tk.JoinPath(gopathT, "/src/goxct")) 29 | 30 | newFilePathT = tk.JoinPath(gopathT, "/src/goxct/goxct.go") 31 | 32 | rsT = tk.SaveStringToFile(fcNewT, newFilePathT) 33 | 34 | if tk.IsErrorString(rsT) { 35 | pl("failed to save destination file: %v", tk.GetErrorString(rsT)) 36 | return 37 | } 38 | 39 | pl("Done") -------------------------------------------------------------------------------- /scripts/generategoxt.gox: -------------------------------------------------------------------------------- 1 | gopathT = os.Getenv("GOPATH") 2 | 3 | if gopathT == "" { 4 | pl("GOPATH not defined") 5 | return 6 | } 7 | 8 | sourceFileNameT = tk.JoinPath(gopathT, "/src/github.com/topxeq/gox/gox.go") 9 | 10 | fcT = tk.LoadStringFromFile(sourceFileNameT) 11 | 12 | if tk.IsErrorString(fcT) { 13 | pl("load source file failed: %v", tk.GetErrorString(fcT)) 14 | return 15 | } 16 | 17 | foundT = tk.RegFindFirst(fcT, `(?m)// full version related start[\s\S]*?// full version related end`, 0) 18 | 19 | if tk.IsErrorString(foundT) { 20 | pl("Full part not found, maybe not expected source file: %v", tk.GetErrorString(foundT)) 21 | return 22 | } 23 | 24 | fcNewT = tk.RegReplace(fcT, `(?m)// full version related start[\s\S]*?// full version related end`, "") 25 | 26 | tk.EnsureMakeDirs(tk.JoinPath(gopathT, "/src/goxt")) 27 | 28 | newFilePathT = tk.JoinPath(gopathT, "/src/goxt/goxt.go") 29 | 30 | rsT = tk.SaveStringToFile(fcNewT, newFilePathT) 31 | 32 | if tk.IsErrorString(rsT) { 33 | pl("failed to save destination file: %v", tk.GetErrorString(rsT)) 34 | return 35 | } 36 | 37 | pl("Done") -------------------------------------------------------------------------------- /scripts/getChar.gox: -------------------------------------------------------------------------------- 1 | pr("please input a key:") 2 | 3 | r = getChar() 4 | 5 | pl("char1 is %v", r) 6 | 7 | pr("please input a key:") 8 | 9 | r = getChar() 10 | 11 | pl("char2 is %v", r) 12 | 13 | keyboard = github_eiannone_keyboard 14 | 15 | err = keyboard.Open() 16 | 17 | if err != nil { 18 | panic(err) 19 | } 20 | 21 | defer keyboard.Close() 22 | 23 | pln("Press ESC to quit") 24 | 25 | for { 26 | char, key, err = keyboard.GetKey() 27 | if err != nil { 28 | panic(err) 29 | } 30 | 31 | fmt.Printf("You pressed: rune %q, key %X\r\n", char, key) 32 | 33 | if key == keyboard.KeyEsc { 34 | break 35 | } 36 | } 37 | 38 | for { 39 | r = getChar() 40 | 41 | pl("char is %v", r) 42 | 43 | if r == "3+0" { 44 | break 45 | } 46 | } -------------------------------------------------------------------------------- /scripts/getCurrentTime.gox: -------------------------------------------------------------------------------- 1 | println(tk.GetNowTimeStringFormal()) 2 | -------------------------------------------------------------------------------- /scripts/getFileList.gox: -------------------------------------------------------------------------------- 1 | // 从命令行获取要读取文件列表的目录,默认为“.”,即当前目录 2 | pathT = getSwitch(argsG, "-dir=", ".") 3 | 4 | // 调用内置函数getFileList获取文件列表 5 | // 除了第一个参数表示目录外,其他参数都是可选 6 | // 有-recursive表示也递归获取所有子目录下的文件 7 | // -pattern=用于指定获取文件的名字匹配模板,*代表获取所有文件,*.txt表示所有扩展名为.txt的文件 8 | // -exclusive=用于指定排除的文件名匹配模板 9 | // 有-verbose开关表示输出每一个文件路径(所有读到的,而不是最终过滤过的) 10 | listT = getFileList(pathT, "-recursive", "-pattern=*", "-exclusive=*.txt", "-verbose") 11 | 12 | // 将文件列表转换成JSON格式文本输出 13 | // 其中toJSON函数用于将任意对象转换为JSON格式 14 | // 除第一个参数外都是可选参数,-sort表示编码的字段按排序(否则Go语言中字段是会随机排序的) 15 | // -indent表示输出带缩进的多行JSON格式 16 | pl("%v", toJSON(listT, "-sort", "-indent")) 17 | 18 | // 遍历得到的文件列表,并做一下比较友好的输出 19 | // 其中v是每次遍历中获得的枚举对象,就是一条文件信息记录 20 | // v["Name"], v.Size是对v中各个属性字段的两种访问方式 21 | for i, v = range listT { 22 | pl("[%v] 文件名:%v,文件大小(字节):%v", i+1, v["Name"], v.Size) 23 | } -------------------------------------------------------------------------------- /scripts/getLines.gox: -------------------------------------------------------------------------------- 1 | // view the specified lines in a text file along with the lines nearby 2 | // usage: gox getLines.gox fileToView.txt -start=3 -end=5 3 | // the start and end index start at 1 4 | // use command-line switch -index to indicate start and end index start at 0 5 | // i.e. gox getLines.gox fileToView.txt -start=3 -end=5 -index 6 | // if -range switch is used, the program will report error if start or end index exceed the range of lines in the file 7 | // but we will not catch the error returned in function tk.GetLinesFromFile in this example 8 | 9 | // get file name to view from command line 10 | fileNameT = getParameter(argsG, 1, "") 11 | 12 | if fileNameT == "" { 13 | pl("not enough paramters") 14 | exit() 15 | } 16 | 17 | // get the start and end index of the lines 18 | startLineNumberT = getIntSwitch(argsG, "-start=", 1) 19 | endLineNumberT = getIntSwitch(argsG, "-end=", 3) 20 | 21 | // get the lines from file 22 | listT, _ = tk.GetLinesFromFile(fileNameT, startLineNumberT, endLineNumberT, argsG...) 23 | 24 | // output the lines 25 | for i, v = range listT { 26 | pl("[%v] %v", startLineNumberT + i, v) 27 | } -------------------------------------------------------------------------------- /scripts/ggBasicDrawingCN.gox: -------------------------------------------------------------------------------- 1 | // 设置image/color包的简称 2 | // github.com/fogleman/gg包已经默认简称gg 3 | color = image_color 4 | 5 | // 建立imagetk包的引用,注意该包的用法比较特殊 6 | itk = imagetk.NewImageTK() 7 | 8 | // 建立一个绘图环境,图片大小为 600×400 像素 9 | contextT = gg.NewContext(600, 400) 10 | 11 | // 用十六进制方式设置当前颜色 12 | contextT.SetHexColor("FFFFFF") 13 | 14 | // 用当前颜色来清空整个图片 15 | contextT.Clear() 16 | 17 | // 设置线宽为 2 个像素 18 | contextT.SetLineWidth(2) 19 | 20 | // 设置RGB颜色,每种颜色的数值范围是 0.0 - 1.0 21 | contextT.SetRGB(0.0, 0.0, 1.0) 22 | 23 | // 画一个圆,以坐标为 (200, 200) 的点为圆心,半径为 50像素 24 | contextT.DrawCircle(250, 250, 60) 25 | 26 | // 真正进行线条绘制,并且保留绘图路径以便后面填充颜色 27 | contextT.StrokePreserve() 28 | 29 | // 创建一个渐变色填充方案 gradientT 30 | // 是两点之间的圆环式渐变色 31 | gradientT = gg.NewRadialGradient(250, 250, 0, 250, 250, 80) 32 | 33 | // 创建一个颜色的基本方法 34 | colorT = new(color.RGBA) 35 | colorT.R = uint8(0) 36 | colorT.G = uint8(0) 37 | colorT.B = uint8(0) 38 | colorT.A = uint8(255) 39 | 40 | gradientT.AddColorStop(0, colorT) 41 | 42 | // 注意创建颜色的快捷方法 43 | gradientT.AddColorStop(1, itk.NewRGBA(0, 0, 255, 255)) 44 | 45 | // 设置用渐变色 gradientT 填充 46 | contextT.SetFillStyle(gradientT) 47 | 48 | // 真正进行填充,并清除绘画路径,因为后面已经不需要了 49 | contextT.Fill() 50 | 51 | // 开始用填充的方式绘制一个矩形 52 | 53 | // 用RGBA色彩体系设置当前颜色 54 | // 用 0 - 255 的数值范围表示颜色和透明度 55 | // 设置一定的透明度以便显示出被覆盖住的图形(圆形) 56 | contextT.SetRGBA255(0, 255, 0, 180) 57 | 58 | // 绘制一个左上角点坐标为 (300, 200),宽 100,高 100的矩形 59 | contextT.DrawRectangle(300, 200, 100, 100) 60 | 61 | // 仅填充颜色不绘制边线 62 | contextT.Fill() 63 | 64 | // 开始用路径法画一个三角形 65 | 66 | // 用十六进制字符串设置颜色 67 | // 可以加上前面的“#”号,也可以后面加上一个字节表示透明度 68 | contextT.SetHexColor("#FF000099") 69 | 70 | // 将虚拟的画笔移动到坐标为 (300, 120) 的点 71 | contextT.MoveTo(300, 120) 72 | 73 | // 从当前点绘制一条线到坐标为 (240, 230)的点为止 74 | // 当前点将随之移动到 (240, 230) 75 | contextT.LineTo(240, 230) 76 | 77 | // 继续绘制一条直线到 (360, 230) 78 | contextT.LineTo(360, 230) 79 | 80 | // 继续绘制一条直线到 (300, 120) 81 | contextT.LineTo(300, 120) 82 | 83 | // 创建一个新的线性渐变色 84 | gradientT = gg.NewLinearGradient(240, 120, 360, 230) 85 | 86 | // 注意从16进制数字创建颜色的方法 87 | gradientT.AddColorStop(0, itk.NewRGBAFromHex("#00FF00FF")) 88 | gradientT.AddColorStop(1, itk.NewRGBAFromHex("0000FFFF")) 89 | gradientT.AddColorStop(0.5, itk.NewRGBAFromHex("FF0000")) 90 | 91 | // 渐变色也可以用于线条颜色的渐变 92 | contextT.SetStrokeStyle(gradientT) 93 | 94 | // 设置粗一点的线宽以体现渐变色 95 | contextT.SetLineWidth(10) 96 | 97 | // 真正绘制三角形 98 | contextT.Stroke() 99 | 100 | // 保存图像为PNG格式的图片文件 101 | contextT.SavePNG(`c:\test\gg.png`) 102 | -------------------------------------------------------------------------------- /scripts/grep.gox: -------------------------------------------------------------------------------- 1 | dirT = getSwitch(argsG, "-dir=", ".") 2 | 3 | patternT = getSwitch(argsG, "-pattern=", "*") 4 | 5 | findT = getSwitch(argsG, "-find=", "") 6 | 7 | if ifSwitchExists(argsG, "-clip") { 8 | findT = getClipText() 9 | } 10 | 11 | filesT = getFiles(dirT, "-recursive", "-pattern="+patternT) 12 | 13 | // pln(filesT) 14 | 15 | foundCountT = 0 16 | 17 | for i, v = range filesT { 18 | // pl("process [%v] %v", i, v) 19 | 20 | fcT = loadTextX(v.Abs) 21 | 22 | if isErr(fcT) { 23 | pl("failed to load text(%v): %v", v, fcT) 24 | continue 25 | } 26 | 27 | foundT = regFind(fcT, findT, 0) 28 | 29 | if isErrStr(foundT) { 30 | 31 | if foundT != "TXERROR:no match"{ 32 | pln(foundT) 33 | exit() 34 | } 35 | // pln(foundT) 36 | continue 37 | } 38 | 39 | foundCountT++ 40 | 41 | pl("[%v] %v", foundCountT, v.Abs) 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /scripts/guiG.gox: -------------------------------------------------------------------------------- 1 | plo(guiG) 2 | 3 | guiG("showInfo", nil, nil, "title1", "msg1") -------------------------------------------------------------------------------- /scripts/guiInfo.gox: -------------------------------------------------------------------------------- 1 | print(runtime.GOOS) -------------------------------------------------------------------------------- /scripts/helloworld.gox: -------------------------------------------------------------------------------- 1 | pln("Hello world!") 2 | -------------------------------------------------------------------------------- /scripts/hexToInt.gox: -------------------------------------------------------------------------------- 1 | argsG = tk.GetAllParameters(os.Args) 2 | 3 | lenT = len(argsG) 4 | 5 | printfln("args length: %v", lenT) 6 | 7 | if lenT > 2 { 8 | pl("Try to convert %v", argsG[2]) 9 | 10 | numT = tk.HexToInt(argsG[2]) 11 | 12 | pl("Result: %v", numT) 13 | 14 | return 15 | } 16 | 17 | errT = lcl.InitLCL() 18 | 19 | if errT != nil { 20 | plerr(errT) 21 | exit() 22 | } 23 | 24 | application = lcl.GetApplication() 25 | 26 | application.Initialize() 27 | 28 | application.SetTitle("Hex to Integer converter") 29 | application.SetMainFormOnTaskBar(true) 30 | 31 | mainForm = application.CreateForm() 32 | 33 | mainForm.SetWidth(400) 34 | mainForm.SetHeight(200) 35 | mainForm.SetCaption("Hex to Integer converter") 36 | mainForm.SetPosition(lcl.PoScreenCenter) 37 | 38 | mainForm.Font().SetSize(11) 39 | 40 | label1 = lcl.NewLabel(mainForm) 41 | label1.SetParent(mainForm) 42 | label1.SetLeft(10) 43 | label1.SetTop(10) 44 | label1.Font().SetName("Arial") 45 | label1.Font().SetSize(18) 46 | 47 | label1.SetCaption("Enter the Hex Value:") 48 | 49 | edit1 = lcl.NewEdit(mainForm) 50 | edit1.SetParent(mainForm) 51 | edit1.SetBounds(10, 48, 200, 32) 52 | edit1.Font().SetSize(11) 53 | 54 | onClick1 = func(objA) { 55 | numT = tk.HexToInt(edit1.Text()) 56 | 57 | if numT < 0 { 58 | edit1.SetText("invalid hex value") 59 | } else { 60 | edit1.SetText(tk.IntToStr(numT)) 61 | } 62 | } 63 | 64 | lastResult = "" 65 | 66 | onClick2 = func(sender) { 67 | lastResult = edit1.Text() 68 | application.Terminate() 69 | } 70 | 71 | button1 = lcl.NewButton(mainForm) 72 | button1.SetParent(mainForm) 73 | button1.SetLeft(20) 74 | button1.SetTop(90) 75 | button1.SetCaption("Convert") 76 | button1.SetOnClick(lcl.NewTNotifyEvent(onClick1)) 77 | 78 | button2 = lcl.NewButton(mainForm) 79 | button2.SetParent(mainForm) 80 | button2.SetLeft(110) 81 | button2.SetTop(90) 82 | button2.SetCaption("Close") 83 | button2.SetOnClick(lcl.NewTNotifyEvent(onClick2)) 84 | 85 | application.Run() 86 | 87 | pl("the last result: %v", lastResult) 88 | -------------------------------------------------------------------------------- /scripts/htmlKeyWV2.gox: -------------------------------------------------------------------------------- 1 | w := webview2.New(true) 2 | 3 | if w == nil { 4 | log.Fatalln("Failed to load webview.") 5 | } 6 | 7 | defer w.Destroy() 8 | 9 | w.SetTitle("dialog") 10 | 11 | w.SetSize(800, 600, webview2.HintNone) 12 | 13 | htmlT = ` 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 45 | 46 | 47 |
48 |
49 |
50 | abc 51 |
52 | 53 | 54 | ` 55 | 56 | w.SetHtml(htmlT) 57 | 58 | w.Run() 59 | -------------------------------------------------------------------------------- /scripts/httpGet.gox: -------------------------------------------------------------------------------- 1 | // 以GET方式访问Web服务 2 | rs = getWeb("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=北京") 3 | 4 | // 检查可能出现的错误 5 | if isErrStr(rs) { 6 | pl("server response error: %v", getErrStr(rs)) 7 | exit() 8 | } 9 | 10 | // 输出返回结果 11 | pln(rs) 12 | 13 | // 获取服务返回信息的某个xml节点 14 | // 这里是天气预报信息 15 | node = fromXML(rs, "ArrayOfString") 16 | 17 | // 检查可能的XML格式错误 18 | checkErrf("failed to get XML node: %v", node) 19 | 20 | // 获取该节点下所有的子节点 21 | ary = node.ChildElements() 22 | 23 | // 遍历这些节点并输出每个节点的文字 24 | for i, v = range ary { 25 | pl("[%v] %v", i, v.Text()) 26 | } -------------------------------------------------------------------------------- /scripts/httpPost1.gox: -------------------------------------------------------------------------------- 1 | // 以POST方式访问Web服务 2 | 3 | // 定义需要POST的数据 4 | data = {"theCityName": "北京"} 5 | 6 | // 访问网络API接口 7 | // 直接将POST数据代入参数即可,getWeb函数第一个参数必须是URL,后面的参数顺序无所谓 8 | rs = getWeb("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName", data) 9 | 10 | // 检查可能出现的错误 11 | if isErrStr(rs) { 12 | pl("server response error: %v", getErrStr(rs)) 13 | exit() 14 | } 15 | 16 | // 输出返回结果 17 | pln(rs) 18 | 19 | // 获取服务返回信息的某个xml节点 20 | // 这里是天气预报信息 21 | node = fromXML(rs, "ArrayOfString") 22 | 23 | // 检查可能的XML格式错误 24 | checkErrf("failed to get XML node: %v", node) 25 | 26 | // 获取该节点下所有的子节点 27 | ary = node.ChildElements() 28 | 29 | // 遍历这些节点并输出每个节点的文字 30 | for i, v = range ary { 31 | pl("[%v] %v", i, v.Text()) 32 | } -------------------------------------------------------------------------------- /scripts/httpServer.gox: -------------------------------------------------------------------------------- 1 | mux = net_http.NewServeMux() 2 | mux.Handle("/404", net_http.NotFoundHandler()) 3 | 4 | mux.HandleFunc("/", fn(w, req) { 5 | fprintf(w, "host: %#v, path: %#v\n", req.Host, req.URL) 6 | }) 7 | 8 | err = net_http.ListenAndServe(":8888", mux) 9 | if err != nil { 10 | fprintln(os.Stderr, err) 11 | } -------------------------------------------------------------------------------- /scripts/if.gox: -------------------------------------------------------------------------------- 1 | if !a { 2 | pln("!a") 3 | } 4 | 5 | if a { 6 | pln("a =", a) 7 | } else { 8 | pln("a is not defined") 9 | } 10 | 11 | b = 1 12 | 13 | if b { 14 | pln("b =", b) 15 | } else { 16 | pln("b is not defined") 17 | } 18 | 19 | pln("!b", !b) 20 | 21 | pln("!c", !c) 22 | -------------------------------------------------------------------------------- /scripts/infoErrConfirm.gox: -------------------------------------------------------------------------------- 1 | // 调用内置函数getConfirmGUI获取用户确认 2 | // 将弹出对话框允许用户选择“是”、“否” 3 | // 第一个参数是对话框标题文字,第二个参数是提示内容文字 4 | // 结果以布尔值形式传入result变量 5 | // 也可以用类似printf的用法:getConfirmGUI("请确认……", "%s比%v快吗?", "雷声", "闪电") 6 | result = getConfirmGUI("请确认……", "雷声比闪电快吗?") 7 | 8 | // 判断用户如果选了“是”,则result值为true,否则为false 9 | // 如果选择了是,则弹出错误提示框 10 | // 否则弹出表示回答正确的信息提示框 11 | // 两种对话框的第一个参数都是对话框标题文字,第二个参数是提示内容文字 12 | if result { 13 | showErrorGUI("回答错误", "闪电速度比雷声要快:闪电以光速运动,每秒30万公里。雷声是以音速运动,每秒340米,所以是闪电快。") 14 | } else { 15 | showInfoGUI("信息提示", "回答得非常正确") 16 | } 17 | -------------------------------------------------------------------------------- /scripts/input.gox: -------------------------------------------------------------------------------- 1 | printf("A:") 2 | 3 | a = getInput() 4 | 5 | printf("B:") 6 | 7 | b = getInput() 8 | 9 | println("A + B =", toFloat(a)+toFloat(b)) -------------------------------------------------------------------------------- /scripts/intfloat.gox: -------------------------------------------------------------------------------- 1 | a = 18 2 | a = a + 1 3 | 4 | pln(a) 5 | 6 | x = 1.2 7 | 8 | y = -3 9 | 10 | z = 9.1 11 | 12 | pln(x * y / z) -------------------------------------------------------------------------------- /scripts/joinTextFile.gox: -------------------------------------------------------------------------------- 1 | file1 = trim(getParam(argsG, 1)) 2 | 3 | file2 = trim(getParam(argsG, 2)) 4 | 5 | file3 = trim(getParam(argsG, 3)) 6 | 7 | if !file3 || file3 == "" { 8 | fatalf("empty file3") 9 | } 10 | 11 | pl("join %v + %v -> %v", file1, file2, file3) 12 | 13 | leLoadFile(file1) 14 | 15 | leAppendFile(file2) 16 | 17 | leSort() 18 | 19 | leSaveFile(file3) 20 | 21 | -------------------------------------------------------------------------------- /scripts/json.gox: -------------------------------------------------------------------------------- 1 | // convert JSON string to object with Golang standard library 2 | 3 | jsonStrT = `{"name": "Peter", "age": 19, "身高": 175, "father": {"name": "Jordan 约翰", "age": 56, "身高": 172}}` 4 | println("jsonStrT:", jsonStrT) 5 | println("\n---\n") 6 | 7 | 8 | outT, errT = encoding_json.Unmarshal([]byte(jsonStrT)) 9 | 10 | if errT != nil { 11 | println("invald JSON:", errT) 12 | return 13 | } 14 | 15 | println("result:", outT) 16 | 17 | println("name:", outT.name) 18 | println("age:", outT.age) 19 | println("father:", outT.father) 20 | 21 | println("\n---\n") 22 | 23 | // convert JSON string to object with tk package 24 | 25 | outT, errT = tk.FromJSON(jsonStrT) 26 | 27 | if errT != nil { 28 | println("invald JSON:", errT) 29 | return 30 | } 31 | 32 | println("result:", outT) 33 | 34 | println("name:", outT.name) 35 | println("age:", outT.age) 36 | println("father:", outT.father) 37 | println("\n---\n") 38 | 39 | 40 | // convert object to JSON string 41 | appleT = { 42 | "Type": "apple", 43 | "Color": "Red红的", 44 | "Weight重量": 10, 45 | "canEat": true, 46 | "Ingredients" : [ 47 | { 48 | "Name": "Protein", 49 | "Amount": 0.3, 50 | }, 51 | { 52 | "Name": "Sugar糖分", 53 | "Amount": 10.4, 54 | }, 55 | ], 56 | } 57 | 58 | pv("appleT") 59 | println("\n---\n") 60 | 61 | newJSONT, errT = tk.ToJSON(appleT) 62 | 63 | if errT != nil { 64 | println("failed to generate JSON:", errT) 65 | return 66 | } 67 | 68 | pl("JSON: %v", newJSONT) 69 | pl("JSON: %v", tk.ToJSONWithDefault(appleT, "")) 70 | 71 | // get indented JSON string 72 | newJSONIndentT, errT = tk.ToJSONIndent(appleT) 73 | 74 | if errT != nil { 75 | println("failed to generate JSON:", errT) 76 | return 77 | } 78 | 79 | println("\n---\n") 80 | 81 | pl("Indented JSON: %v", newJSONIndentT) 82 | pl("Indented JSON: %v", tk.ToJSONIndentWithDefault(appleT, "")) 83 | 84 | println("\n---\n") 85 | 86 | // get the node as various typed data 87 | nodeT = tk.GetJSONNode(newJSONT, "Color") 88 | pv("nodeT") 89 | 90 | // lower-cased key is also allowed 91 | 92 | node1T = tk.GetJSONNode(newJSONT, "canEat") 93 | 94 | println("\n---\n") 95 | pv("node1T") 96 | 97 | println("\n---\n") 98 | 99 | node2T = tk.GetJSONNodeAny(newJSONT, "Ingredients") 100 | pl("Value type: %v", node2T.ValueType()) 101 | 102 | println("\n---\n") 103 | 104 | pv("node2T") 105 | 106 | subNode1T = tk.GetJSONSubNode(node2T, 0, "Name") 107 | 108 | println("\n---\n") 109 | 110 | pv("subNode1T") 111 | 112 | subNode2T = tk.GetJSONNode(newJSONT, "Ingredients", 1, "Amount") 113 | 114 | println("\n---\n") 115 | pv("subNode2T") 116 | 117 | subNode3T = tk.GetJSONNode(newJSONT, "Ingredients", "*") 118 | 119 | println("\n---\n") 120 | pv("subNode3T") 121 | 122 | subSubNodeT = tk.GetJSONSubNode(subNode3T[0], "Name") 123 | 124 | println("\n---\n") 125 | pv("subSubNodeT") 126 | 127 | subNode4T = tk.GetJSONNodeAny(newJSONT, "Ingredients", 3, "Name") 128 | 129 | println("\n---\n") 130 | pv("subNode4T") 131 | 132 | pl("Value type: %v", subNode4T.ValueType()) 133 | 134 | pl("Last Error: %v", subNode4T.LastError()) -------------------------------------------------------------------------------- /scripts/limitStr.gox: -------------------------------------------------------------------------------- 1 | s := "abcdefg1234567" 2 | 3 | pln(limitStr(s, 5)) 4 | 5 | pln(limitStr(s, 5, "-end")) 6 | 7 | pln(limitStr(s, 5, "-suffix=!!!")) -------------------------------------------------------------------------------- /scripts/localVar.gox: -------------------------------------------------------------------------------- 1 | 2 | func cal(lo...) { 3 | lo = {} 4 | 5 | lo.map1 = {"a": 10001, "b": 30003, "c": 50005} 6 | 7 | lo["i"] = 0 8 | lo["v"] = 0 9 | 10 | for true { 11 | for i, v = range lo.map1 { 12 | pl("i: %v, v: %v, lo: %v", i, v, lo) 13 | 14 | sleep(1) 15 | } 16 | } 17 | 18 | } 19 | 20 | func cal2(idxA, secA) { 21 | lo = {} 22 | 23 | lo.map1 = {"a": idxA, "b": idxA+1, "c": idxA+2} 24 | 25 | lo.ary1 = ["a", "b", "c"] 26 | 27 | if (idxA == 5) { 28 | lo.ary1 = ["***", "###", "^^^"] 29 | } 30 | 31 | for true { 32 | for iL1, vL1 = range lo.ary1 { 33 | pl("[%v] i: %v, v: %v, lo: %v", idxA, iL1, vL1, lo) 34 | 35 | sleep(secA) 36 | } 37 | } 38 | 39 | } 40 | 41 | 42 | iL1 43 | vL1 44 | // go cal() 45 | 46 | go cal2(1, 1) 47 | go cal2(2, 0.7) 48 | 49 | go cal2(3, 1.1) 50 | go cal2(4, 0.3) 51 | 52 | go cal2(5, 0.1) 53 | 54 | i = 0 55 | lo = [1, 2, 3] 56 | 57 | for true { 58 | i ++ 59 | pl("main i=%v, lo=%v", i, lo) 60 | sleep(1) 61 | } -------------------------------------------------------------------------------- /scripts/localVar2.gox: -------------------------------------------------------------------------------- 1 | func f1() { 2 | a = 1.1 3 | for { 4 | pl("f1: %v", a) 5 | 6 | sleep(1.0) 7 | } 8 | } 9 | 10 | func f2() { 11 | a 12 | for { 13 | a = "A" 14 | pl("f2: %v", a) 15 | 16 | sleep(0.7) 17 | } 18 | } 19 | 20 | a 21 | 22 | go f1() 23 | go f2() 24 | 25 | a = 0 26 | for { 27 | pl("f0: %v", a) 28 | 29 | sleep(0.3) 30 | } -------------------------------------------------------------------------------- /scripts/localVsGlobal.gox: -------------------------------------------------------------------------------- 1 | a = 1 2 | 3 | fn() { 4 | a = 2 5 | }() 6 | 7 | println(a) 8 | 9 | b = "I'm fine." 10 | 11 | fn(b) { 12 | b = "Hi!" + b 13 | println(b) 14 | }(b) 15 | 16 | println(b) 17 | 18 | c = "abcd" 19 | 20 | func cal(c, d) { 21 | c.attr1 = [1, 2, 3] 22 | c.attr1 = append(c.attr1, 123) 23 | c.attr1 = append(c.attr1, d) 24 | 25 | c.attr2 = "That's nice." 26 | c.attr3 = {} 27 | 28 | c.attr3.a1 = 2.6 29 | 30 | println(c) 31 | } 32 | 33 | cal({}, 1) 34 | 35 | cal({}, 5) 36 | 37 | cal({}, 10) 38 | 39 | println(c) 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /scripts/loopAndIf.gox: -------------------------------------------------------------------------------- 1 | i = 0 2 | 3 | for { 4 | println(i) 5 | i++ 6 | if i > 1 { 7 | break 8 | } 9 | } 10 | 11 | println("") 12 | 13 | for i, v = range [0, 1] { 14 | println(i, v) 15 | } 16 | 17 | println("") 18 | 19 | for key, value = range {"a": "b"} { 20 | println(key, value) 21 | } 22 | 23 | println("") 24 | 25 | m = {"a": "b", "c": 3} 26 | 27 | for k, v = range m { 28 | println(k, v) 29 | } 30 | 31 | println("") 32 | 33 | i = 0 34 | for i < 2 { 35 | println(i) 36 | i++ 37 | } 38 | 39 | println("") 40 | 41 | for i = 0; i < 2; i++ { 42 | println(i) 43 | } 44 | 45 | println("") 46 | 47 | 48 | for i = 0; i < 10; i++ { 49 | println(i) 50 | if i < 1 { 51 | continue 52 | } 53 | 54 | break 55 | } 56 | 57 | println("") 58 | 59 | aryT = [3, "abc", true, 2.8] 60 | 61 | for i, v = range aryT { 62 | printf("v: %v ", v) 63 | switch v { 64 | case typeOf(v) == "bool": 65 | println("is bool:", v) 66 | case typeOf(v) == "string": 67 | println("is string") 68 | case 2.8: // fallthrough is not supported now 69 | case 3: 70 | println("is number") 71 | default: 72 | println("unknown:", v) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /scripts/map.gox: -------------------------------------------------------------------------------- 1 | a = map[var]var{} 2 | 3 | a["Num"] = 3 4 | a[5] = "abc" 5 | a[-1] = true 6 | a["ary"] = [1, "xyz", false] 7 | a[false] = "not true" 8 | a.Item1 = "item 1" 9 | 10 | pv("a") 11 | 12 | pl("length of a: %v", len(a)) 13 | pl("a.Num: %v", a.Num) 14 | 15 | a["Num"]++ 16 | println(a["Num"]) 17 | 18 | a[5]=a[5]+a[5] 19 | a[5] = a[5][1:] 20 | println(a[5]) 21 | 22 | b = map[var]var{} 23 | 24 | pv("b") 25 | 26 | c = map[int]string{} 27 | 28 | c[3] = "3" 29 | c[18] = "abc" 30 | c[-198] = "true" 31 | 32 | pv("c") 33 | 34 | v = c[18] 35 | 36 | if v == undefined { 37 | println("v:", v) 38 | } 39 | 40 | delete(c, 18) 41 | 42 | println("c:", c) 43 | 44 | // ok = c["b"] // will cause runtime error, since key should be int 45 | // println(ok) 46 | 47 | println("---") 48 | 49 | for k, v = range a { 50 | println("[", k, "]:", v) 51 | } 52 | 53 | -------------------------------------------------------------------------------- /scripts/mapCN.gox: -------------------------------------------------------------------------------- 1 | // 默认的映射是map[string]interface{}类型的,相当于Gox中的map[string]var 2 | a = {} 3 | pv("a") 4 | 5 | // 如果要键值非string,可以指定var或者其他的类型 6 | a = map[var]var{} 7 | pv("a") 8 | 9 | // var类型支持各种值 10 | a["Num"] = 3 11 | a[5] = "abc" 12 | a[-1] = true 13 | a["ary"] = [1, "xyz", false] 14 | a[false] = "not true" 15 | a.Item1 = "item 1" 16 | 17 | pv("a") 18 | 19 | // 内置函数len用于取映射长度,即其中的键值对数 20 | pl("length of a: %v", len(a)) 21 | 22 | // 可以用“.key”的方式来取map中对应的键值 23 | pl("a.Num: %v", a.Num) 24 | 25 | // 键值项可以直接进行计算和其他操作 26 | a["Num"]++ 27 | println(a["Num"]) 28 | 29 | a[5]=a[5]+a[5] 30 | a[5] = a[5][1:] 31 | println(a[5]) 32 | 33 | 34 | // 直接定义以int类型作为键类型 35 | c = map[int]string{} 36 | 37 | c[3] = "3" 38 | c[18] = "abc" 39 | c[-198] = "true" 40 | 41 | pv("c") 42 | 43 | // 此时v是有值的 44 | v = c[18] 45 | if v == undefined { 46 | println("v:", v) 47 | } 48 | 49 | // 删除掉该项 50 | delete(c, 18) 51 | 52 | println("c:", c) 53 | 54 | // 这样索引取键值会报错 55 | // ok = c["b"] // will cause runtime error, since key should be int 56 | // println(ok) 57 | 58 | println("---") 59 | 60 | // 遍历map的方法 61 | for k, v = range a { 62 | println("[", k, "]:", v) 63 | } 64 | 65 | a = {"a": 3, "b": "abc"} 66 | pv("a") -------------------------------------------------------------------------------- /scripts/mapIndex.gox: -------------------------------------------------------------------------------- 1 | a = 1 2 | 3 | pln(a["a"]["b"]["c"]) 4 | -------------------------------------------------------------------------------- /scripts/memfs.gox: -------------------------------------------------------------------------------- 1 | // 创建一个内存文件系统对象 2 | fs = github_topxeq_afero.NewMemFS() 3 | 4 | // 在根目录下新建一个文件a.txt 5 | f, err = fs.Create(`/a.txt`) 6 | 7 | // 输出一下创建结果,f是文件对象,如果发生错误,err中包含错误对象 8 | // plvsr用于连续输出多个对象信息 9 | plvsr(f, err) 10 | 11 | // 在该文件中写入字符串abc 12 | f.WriteString("abc") 13 | 14 | // 关闭文件(也可以用defer,但会在脚本最后才执行,所以不太适合) 15 | f.Close() 16 | 17 | // 以二进制方式从该文件中载入字节数组进行检验 18 | rs, err := fs.LoadBytesFromFile(`/a.txt`) 19 | 20 | // 输出获得的字节数组 21 | plvsr(rs, err) 22 | 23 | // 直接创建一个二级子目录(一级目录会自动创建) 24 | fs.MkdirAll("/tmp/data", 0x666) 25 | 26 | // 复制真实文件系统的某个文件到内存文件系统,-force参数表示如果文件存在则覆盖 27 | err = fs.CopyFileFrom(`d:\tmpx\sp\sel1.txt`, fs.Join(`/tmp/data`, `sel1.txt`), "-force") 28 | 29 | plvsr(err) 30 | 31 | // 打开根目录 32 | root, err = fs.Open(`/`) 33 | 34 | plvsr(root, err) 35 | 36 | // 读取目录内所有文件名的方法之一 37 | plvsr(root.Readdirnames(-1)) 38 | 39 | // 直接从文件中载入字符串(注意一定是UTF-8编码的) 40 | rs, err = fs.LoadStringFromFile(`/tmp/data/sel1.txt`) 41 | 42 | plvsr(rs, err) 43 | 44 | // 列出该目录下所有文件(不包含子目录名和子目录下的文件) 45 | pl("ls files: %v", fs.Ls("/")) 46 | 47 | // 列出该目录下所有文件(不包含所有子目录本身,但包含各级子目录下的文件) 48 | pl("ls files recursively: %v", fs.Lsr("/")) 49 | 50 | // 创建另一个子目录(如果没有上级目录会报错) 51 | fs.Mkdir("/tmp/next", 0x666) 52 | 53 | // 在内存文件系统中复制文件 54 | err = fs.CopyFile(fs.Join(`/tmp/data`, `sel1.txt`), fs.Join(`/tmp/next`, `sel1bak.txt`)) 55 | 56 | // 如果有错误则退出程序执行 57 | checkErrf("failed to copy file: %v", err) 58 | 59 | // 再次列出内存文件系统所有文件以验证 60 | // 按通配符列出符合条件的文件 61 | dirs, err = fs.Glob("/tmp/*/*.txt") 62 | plvsr(dirs, err) 63 | 64 | // 删除一个文件 65 | err = fs.RemoveFile(`/tmp/data/sel1.txt`) 66 | 67 | // 验证删除是否成功 68 | pl("ls files recursively: %v", fs.Lsr("/")) 69 | 70 | // 从内存文件系统中复制文件到真实文件系统(没有-force参数则如果存在文件会报错) 71 | err = fs.CopyFileTo(fs.Join(`/tmp/next`, `sel1bak.txt`), path_filepath.Join(`d:\tmpx\sp`, `testsel1.txt`)) 72 | 73 | // 如果有错误则退出程序执行 74 | checkErrf("failed to copy file: %v", err) 75 | -------------------------------------------------------------------------------- /scripts/memtar.gox: -------------------------------------------------------------------------------- 1 | // 新建一个内存虚拟文件系统 2 | mfs = memfs.NewMemFS() 3 | 4 | // 将一系列真实文件系统中的文件和文件夹进行打包压缩(TAR+GZ格式),生成的文件在虚拟文件系统上 5 | mfs.TarFrom([`d:\tmpx\demo1.html`, `d:\tmpx\demo2.html`, `d:\tmpx\test`], "/abc.tar.gz") 6 | 7 | // 将打包文件复制到真实文件系统中以备检查 8 | mfs.CopyFileTo("/abc.tar.gz", `d:\tmpx\abc.tar.gz`) 9 | 10 | // 解压缩该文件到内存虚拟文件系统中 11 | mfs.UntarFrom(`d:\tmpx\abc.tar.gz`, "/extract") 12 | 13 | // 列表检查所有文件是否存在 14 | plv(mfs.Lsr("/")) 15 | 16 | // 将虚拟文件系统中所有文件打包成all.tar.gz 17 | err = mfs.Tar(["/"], "/all.tar.gz") 18 | checkError(err) 19 | 20 | // 列表检查all.tar.gz是否存在 21 | plv(mfs.Lsr("/")) 22 | 23 | // 解压all.tar.gz文件到/all目录下 24 | err = mfs.Untar("/all.tar.gz", "/all") 25 | checkError(err) 26 | 27 | // 检查所有文件是否正常存在 28 | plv(mfs.Lsr("/")) 29 | -------------------------------------------------------------------------------- /scripts/module.gox: -------------------------------------------------------------------------------- 1 | module rectangle { 2 | _length = 1 3 | _width = 1 4 | 5 | func setLength (length) { 6 | if length <= 0 { 7 | return 8 | } 9 | _length = length 10 | } 11 | 12 | func setWidth (width) { 13 | if width <= 0 { 14 | return 15 | } 16 | _width = width 17 | } 18 | 19 | func area () { 20 | return _length * _width 21 | } 22 | 23 | func perimeter () { 24 | return 2 * (_length + _width) 25 | } 26 | } 27 | 28 | rectangle1 = rectangle 29 | 30 | rectangle1.setLength(4) 31 | rectangle1.setWidth(5) 32 | 33 | println(rectangle1.area()) 34 | println(rectangle1.perimeter()) 35 | 36 | rectangle2 = rectangle 37 | 38 | rectangle2.setLength(2) 39 | rectangle2.setWidth(4) 40 | 41 | println(rectangle2.area()) 42 | println(rectangle2.perimeter()) 43 | 44 | println(rectangle1.area()) 45 | println(rectangle1.perimeter()) 46 | println("---") 47 | 48 | module person1 { 49 | nameM = "" 50 | ageM = 0 51 | 52 | func getName() { 53 | return nameM 54 | } 55 | 56 | func setName(nameA) { 57 | nameM = nameA 58 | } 59 | 60 | } 61 | 62 | var p2 = person1 63 | p2.setName("Jerry") 64 | println(p2.getName()) 65 | println(p2.nameM) 66 | println("---") 67 | 68 | p5 = person1 69 | p5.setName("Lisa") 70 | println(p5.getName()) 71 | println(p5.nameM) 72 | println("---") 73 | 74 | println(p2.getName()) 75 | println(p2.nameM) 76 | 77 | -------------------------------------------------------------------------------- /scripts/newObject.gox: -------------------------------------------------------------------------------- 1 | nilT = newObject("nil") 2 | 3 | plv(nilT) 4 | 5 | errT = newObject("error", "0/%v is not allowed", 0) 6 | 7 | plv(errT) 8 | 9 | errStrT = newObject("errStr", "0/%v is not allowed", 0) 10 | 11 | plv(errStrT) 12 | 13 | buf1 = newObj("bytesBuffer") 14 | 15 | buf1.WriteString("abc") 16 | 17 | buf1.Write([]byte{2, 5, 8}) 18 | 19 | buf1.WriteByte('\t') 20 | 21 | buf1.WriteRune(rune(123456)) 22 | 23 | plv(buf1) 24 | 25 | buf2 = newObj("bytesBuffer", "123") 26 | 27 | pln(buf2.Bytes()) 28 | pln(buf2.String()) 29 | 30 | buf3 = newObj("bytesBuffer", []byte{1, 4, 7}) 31 | 32 | plv(buf3) 33 | 34 | buf4 = newObj("stringBuilder") 35 | 36 | plv(buf4) 37 | 38 | buf4.WriteString("qwerty") 39 | 40 | plv(buf4.String()) 41 | 42 | buf5 = newObj("stringBuilder", "1234567") 43 | 44 | plv(buf5.String()) 45 | 46 | reader1 = newObj("stringReader", "abcde12345") 47 | 48 | for { 49 | b, err = reader1.ReadByte() 50 | 51 | if err != nil { 52 | if err == io.EOF { 53 | break 54 | } 55 | 56 | pl("err: %v", err) 57 | break 58 | } 59 | 60 | plv(b) 61 | } 62 | 63 | 64 | -------------------------------------------------------------------------------- /scripts/nosql.gox: -------------------------------------------------------------------------------- 1 | // 设置github/dgraph-io/badger包的简称,注意该报中因为有连字符,因此会被省略 2 | badger = github_dgraphio_badger 3 | 4 | // 创建或打开数据库 5 | dbT, errT = badger.Open(badger.DefaultOptions(`c:\test\db`)) 6 | if errT != nil { 7 | log.Fatal(errT) 8 | } 9 | 10 | // 确保退出前关闭数据库 11 | defer dbT.Close() 12 | 13 | // 准备用于测试的数据,是映射类型的数据 14 | dataT = make(map[string]string) 15 | 16 | dataT["ok"] = "yes" 17 | dataT["名字"] = "张三" 18 | 19 | // 新建一个事务 20 | transT = dbT.NewTransaction(true) 21 | 22 | // 遍历测试数据并存入数据库 23 | for k, v = range dataT { 24 | 25 | // 将对应的键值对存入 26 | errT = transT.Set([]byte(k), []byte(v)) 27 | 28 | if errT != nil { 29 | fmt.Printf("设置KV对时发生错误:%v", errT.Error()) 30 | } 31 | 32 | } 33 | 34 | // 提交事务,此时才真正写入数据库 35 | _ = transT.Commit() 36 | 37 | // 输出分隔线 38 | fmt.Printf("\n-----\n") 39 | 40 | // 再次新建一个事务用于查询 41 | transT = dbT.NewTransaction(true) 42 | 43 | // 查询键名为ok对应的键值 44 | itemT, errT = transT.Get([]byte("ok")) 45 | 46 | if errT != nil { 47 | log.Fatalf("获取KV对时发生错误:%v", errT) 48 | } 49 | 50 | // 获取键值 51 | valueT, errT = itemT.ValueCopy(nil) 52 | 53 | if errT != nil { 54 | log.Fatalf("获取KV对值时发生错误:%v", errT) 55 | } 56 | 57 | fmt.Printf("获取到的键名为%v的键值:%v\n", "ok", string(valueT)) 58 | 59 | // 用只读模式打开数据库后遍历其中所有的键值对 60 | errT = dbT.View(func(txn) { 61 | 62 | // 准备遍历数据库中键值对的设置参数,这里用的是默认设置 63 | optionsT = new(badger.IteratorOptions) 64 | 65 | optionsT.PrefetchValues = true 66 | optionsT.PrefetchSize = 100 67 | optionsT.Reverse = false 68 | optionsT.AllVersions = false 69 | 70 | // 设置预获取的数量 71 | optionsT.PrefetchSize = 10 72 | 73 | // 创建遍历用的枚举对象 74 | iteratorT = txn.NewIterator(*optionsT) 75 | 76 | // 确保枚举对象被关闭 77 | defer iteratorT.Close() 78 | 79 | // 进行遍历 80 | iteratorT.Rewind() 81 | 82 | for iteratorT.Valid() { 83 | 84 | // 获取一个枚举值 85 | itemT = iteratorT.Item() 86 | 87 | // 获取该枚举值中的键值 88 | k = itemT.Key() 89 | 90 | // 调用匿名函数获取键值并处理 91 | errT = itemT.Value(func(v) { 92 | fmt.Printf("键名:%s,键值:%s\n", k, v) 93 | return nil 94 | }) 95 | 96 | if errT != nil { 97 | return errT 98 | } 99 | 100 | iteratorT.Next() 101 | 102 | } 103 | 104 | return nil 105 | }) 106 | 107 | if errT != nil { 108 | log.Fatalf("遍历KV对时发生错误:%v", errT) 109 | } 110 | 111 | fmt.Printf("\n-----\n") 112 | 113 | -------------------------------------------------------------------------------- /scripts/not.gox: -------------------------------------------------------------------------------- 1 | pln(!a) 2 | 3 | a = nil 4 | pln(!a) 5 | 6 | pln(!nil) -------------------------------------------------------------------------------- /scripts/operators.gox: -------------------------------------------------------------------------------- 1 | // Assignment 2 | a = nil 3 | println(a) 4 | a = true 5 | println(a) 6 | 7 | println("-----") 8 | 9 | // basic operators 10 | a = 2 + 1 11 | println(a) 12 | a = 2 - 1 13 | println(a) 14 | a = 2 * 1 15 | println(a) 16 | a = 4 / 2 17 | println(a) 18 | 19 | println("-----") 20 | 21 | // ++ and -- 22 | a = 1 23 | a++ 24 | println(a) 25 | a-- 26 | println(a) 27 | 28 | println("-----") 29 | 30 | // +=, -=, *=, /= 31 | a = 1 32 | a += 1 33 | println(a) 34 | a -= 1 35 | println(a) 36 | a *= 4 37 | println(a) 38 | a /= 2 39 | println(a) 40 | a = 2 - (-2) 41 | println(a) 42 | 43 | println("-----") 44 | 45 | // bitwise and/or/not 46 | a = 1 & 3 47 | println(a) 48 | a = 1 | 2 49 | println(a) 50 | a = !true 51 | println(a) 52 | 53 | println("-----") 54 | 55 | // bitwise shift 56 | a = 2 << 3 57 | println(a) 58 | a = 8 >> 2 59 | println(a) 60 | 61 | println("-----") 62 | 63 | // mod 64 | a = 7 % 3 65 | println(a) 66 | 67 | println("-----") 68 | 69 | // bitwise complement 70 | a = bitXor(1.1, 2) 71 | println(a) 72 | -------------------------------------------------------------------------------- /scripts/oracle.gox: -------------------------------------------------------------------------------- 1 | // sqltk库提供访问数据库的一些简单方法 2 | 3 | // 连接数据库,Oralce数据库要使用godror驱动 4 | // 用户名、密码、数据库服务器地址和端口、数据库名等均需要替换成自己的 5 | dbT, errT = sqltk.ConnectDB("godror", `username/password@db.example.com:1521/dbname`) 6 | 7 | if errT != nil { 8 | printfln("数据库连接错误: %v", errT) 9 | exit() 10 | } 11 | 12 | // 注意一定要关闭数据库连接,释放资源,即使是异常退出 13 | defer dbT.Close() 14 | 15 | // 拼装SQL语句,建议一般都用拼装的方式,避免传参数的SQL调用方式 16 | // 注意将数据库名、表名和字段名换成自己的 17 | sqlT = `select * from dbname.MY_TABLE_NAME where RECIPE_NO='0200006619210053289'` 18 | 19 | // QueryDBNSS函数将查询结果返回为一个二维数组,第一行为列名,第二行开始是数据,所有数据都被转换为字符串表示形式 20 | 21 | sqlResultT, errT = sqltk.QueryDBNSS(dbT, sqlT) 22 | 23 | if errT != nil { 24 | printfln("获取数据记录失败:%v", errT) 25 | 26 | exit() 27 | } 28 | 29 | // 查看结果 30 | plv(sqlResultT) 31 | 32 | -------------------------------------------------------------------------------- /scripts/orderedMap.gox: -------------------------------------------------------------------------------- 1 | map1 = newObj("orderedMap") 2 | 3 | v2 = 1 4 | v3 = fromJSONX(`["s1", "s2"]`) 5 | 6 | setMapItem(map1, "SSS", "v11") 7 | 8 | map1.Set("k1", "v1") 9 | map1.Set("a2", v2) 10 | map1.Set("3", v3) 11 | 12 | json1 = toJSONX(map1) 13 | 14 | pln(json1) 15 | 16 | map1a = map1.ToMap() 17 | 18 | plo(map1a) 19 | 20 | map1b = map1.ToMapAnyKey() 21 | 22 | plo(map1b) 23 | 24 | map2 = toOrderedMap(map1a) 25 | 26 | pln(map2) 27 | 28 | map2.MoveToFront("a2") 29 | 30 | pln(map2) 31 | 32 | map2.MoveBefore("3", "SSS") 33 | 34 | pln(map2) 35 | 36 | map2.SortStringKeys() 37 | 38 | pln(map2.Dump()) 39 | 40 | pln(map2) 41 | 42 | map2.SortStringKeys("-desc") 43 | 44 | pln(map2) 45 | 46 | map2.MoveToFront("3") 47 | map2.MoveToFront("SSS") 48 | map2.MoveToFront("kkk") 49 | 50 | pln(map2) 51 | 52 | 53 | -------------------------------------------------------------------------------- /scripts/perf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | double calPi(int pointCount) 6 | { 7 | int inCircleCount = 0; 8 | double x, y, Pi; 9 | 10 | for (int i = 0; i < pointCount; i++) 11 | { 12 | x = rand() / (double)RAND_MAX; // x 将介于[0, 1]之间 13 | y = rand() / (double)RAND_MAX; // x 将介于[0, 1]之间 14 | 15 | if (x * x + y * y < 1) // 判断随机产生的点是否落在四分之一圆内 16 | { 17 | inCircleCount++; // 18 | } 19 | } 20 | 21 | Pi = (4.0 * inCircleCount) / pointCount; 22 | 23 | return Pi; 24 | } 25 | 26 | double square(double a) 27 | { 28 | return a * a; 29 | } 30 | 31 | long long fibonacci(long long c) 32 | { 33 | if (c < 2) 34 | { 35 | return c; 36 | } 37 | 38 | return fibonacci(c - 2) + fibonacci(c - 1); 39 | } 40 | 41 | int main() 42 | { 43 | srand((int)time(NULL)); // 初始化随机数 44 | 45 | time_t startTime = time(NULL); 46 | 47 | double result = 0.0; 48 | 49 | for (double i = 0; i < 1000000000; i = i + 1) 50 | { 51 | result += i * i; 52 | } 53 | 54 | time_t endTime = time(NULL); 55 | 56 | printf("Result: %f\n", result); 57 | 58 | printf("耗时: %ld秒\n", (endTime - startTime)); 59 | 60 | printf("Test 2\n"); 61 | 62 | startTime = time(NULL); 63 | 64 | long long result2 = 0; 65 | 66 | result2 = fibonacci(50); 67 | 68 | endTime = time(NULL); 69 | 70 | printf("Result: %lld\n", result2); 71 | 72 | printf("耗时: %ld秒\n", (endTime - startTime)); 73 | 74 | return 0; 75 | } -------------------------------------------------------------------------------- /scripts/performance.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "time" 7 | 8 | tk "github.com/topxeq/tkc" 9 | ) 10 | 11 | func calPi(pointCount int) float64 { 12 | inCircleCount := 0 13 | 14 | var x, y float64 15 | var Pi float64 16 | 17 | r := tk.NewRandomGenerator() 18 | 19 | for i := 0; i < pointCount; i++ { 20 | // x = rand.Float64() 21 | // y = rand.Float64() 22 | x = r.Float64() 23 | y = r.Float64() 24 | 25 | if x*x+y*y < 1 { 26 | inCircleCount++ 27 | } 28 | } 29 | 30 | Pi = (4.0 * float64(inCircleCount)) / float64(pointCount) 31 | 32 | return Pi 33 | } 34 | 35 | func fibonacci(c int64) int64 { 36 | if c < 2 { 37 | return c 38 | } 39 | 40 | return fibonacci(c-2) + fibonacci(c-1) 41 | } 42 | 43 | func fibonacciFlat(c int64) int64 { 44 | if c < 2 { 45 | return c 46 | } 47 | 48 | var fibo int64 = 1 49 | var fiboPrev int64 = 1 50 | for i := int64(2); i < c; i++ { 51 | temp := fibo 52 | fibo += fiboPrev 53 | fiboPrev = temp 54 | } 55 | 56 | return fibo 57 | } 58 | 59 | func main() { 60 | rand.Seed(time.Now().Unix()) // 初始化随机数 61 | 62 | // fmt.Printf("Test 1\n") 63 | 64 | // startTime := time.Now() 65 | 66 | // result := 0.0 67 | 68 | // for i := 0.0; i < 1000000000; i = i + 1 { 69 | // result += i * i 70 | // } 71 | 72 | // endTime := time.Now() 73 | 74 | // fmt.Printf("Result: %v\n", result) 75 | 76 | // fmt.Printf("Duration: %v\n", endTime.Sub(startTime)) 77 | 78 | countT := 10000000 79 | 80 | fmt.Printf("\nGolang Test 2\n") 81 | 82 | startTime := time.Now() 83 | 84 | result := calPi(countT) 85 | 86 | endTime := time.Now() 87 | 88 | fmt.Printf("Result: %v\n", result) 89 | 90 | fmt.Printf("Duration: %v s\n", endTime.Sub(startTime)) 91 | 92 | return 93 | 94 | fmt.Printf("Golang Test 2\n") 95 | 96 | startTime = time.Now() 97 | 98 | resultInt := fibonacciFlat(10000000000) 99 | 100 | endTime = time.Now() 101 | 102 | fmt.Printf("Result: %v\n", resultInt) 103 | 104 | fmt.Printf("Duration: %v\n", endTime.Sub(startTime)) 105 | 106 | fmt.Printf("Test 2r\n") 107 | 108 | startTime = time.Now() 109 | 110 | resultInt = fibonacci(50) 111 | 112 | endTime = time.Now() 113 | 114 | fmt.Printf("Result: %v\n", resultInt) 115 | 116 | fmt.Printf("Duration: %v\n", endTime.Sub(startTime)) 117 | 118 | fmt.Printf("Test 3\n") 119 | 120 | startTime = time.Now() 121 | 122 | result = 0.0 123 | 124 | for i := 0.0; i < 100000000; i = i + 1 { 125 | result += rand.Float64() 126 | } 127 | 128 | endTime = time.Now() 129 | 130 | fmt.Printf("Result: %v\n", result) 131 | 132 | fmt.Printf("Duration: %v\n s", endTime.Sub(startTime)) 133 | 134 | } 135 | -------------------------------------------------------------------------------- /scripts/performance.gox: -------------------------------------------------------------------------------- 1 | fmt = import ("fmt") 2 | tk = import("tk") 3 | time = import("time") 4 | rand = import("math/rand") 5 | 6 | func calPi(pointCount) { 7 | inCircleCount = 0 8 | 9 | r = tk.NewRandomGenerator() 10 | 11 | for i = 0; i < pointCount; i++ { 12 | x = r.Float64() 13 | y = r.Float64() 14 | 15 | if x*x+y*y < 1 { 16 | inCircleCount++ 17 | } 18 | } 19 | 20 | Pi = (4.0 * inCircleCount) / pointCount 21 | 22 | return Pi 23 | } 24 | 25 | func fibonacci(c) { 26 | if c < 2 { 27 | return c 28 | } 29 | 30 | return fibonacci(c-2) + fibonacci(c-1) 31 | } 32 | 33 | func fibonacciFlat(c) { 34 | if c < 2 { 35 | return c 36 | } 37 | 38 | var fibo = 1 39 | var fiboPrev = 1 40 | for i = 2; i < c; i++ { 41 | temp = fibo 42 | fibo += fiboPrev 43 | fiboPrev = temp 44 | } 45 | 46 | return fibo 47 | } 48 | 49 | func main() { 50 | tk.Randomize() // 初始化随机数 51 | 52 | countT = 10000000 53 | 54 | println("\nGox Test 2") 55 | 56 | startTime = time.Now() 57 | 58 | println("Count:", countT) 59 | 60 | result = calPi(countT) 61 | 62 | endTime = time.Now() 63 | 64 | fmt.Printf("Result: %v\n", result) 65 | 66 | fmt.Printf("Duration: %v s\n", endTime.Sub(startTime)) 67 | 68 | println("\nJavaScript Test 2") 69 | 70 | startTime = time.Now() 71 | 72 | jsStrT = ` 73 | function calPi(pointCount) { 74 | var inCircleCount = 0 75 | 76 | for (var i = 0; i < pointCount; i++) { 77 | var x = Math.random() 78 | var y = Math.random() 79 | 80 | if (x*x+y*y < 1) { 81 | inCircleCount++ 82 | } 83 | } 84 | 85 | var Pi = (4.0 * inCircleCount) / pointCount 86 | 87 | return Pi 88 | } 89 | 90 | 91 | var countStrT = getVar("Count"); 92 | 93 | var countT = 1000; 94 | 95 | if (!countStrT.startsWith("TXERROR:")) { 96 | countT = parseInt(countStrT); 97 | } 98 | 99 | if (countT == NaN) { 100 | countT = 1000; 101 | } 102 | 103 | println("Count:", countT); 104 | 105 | resultG = calPi(countT) 106 | 107 | ` 108 | 109 | setVar("Count", toString(countT)) 110 | 111 | result = runScript(jsStrT, "js") 112 | 113 | endTime = time.Now() 114 | 115 | fmt.Printf("Result: %v\n", result) 116 | 117 | fmt.Printf("Duration: %v s\n", endTime.Sub(startTime)) 118 | 119 | println("\nTengo Test 2") 120 | 121 | startTime = time.Now() 122 | 123 | tgStrT = ` 124 | timelib := import("times") 125 | fmt := import("fmt") 126 | rand := import("rand") 127 | text := import("text") 128 | 129 | 130 | calPi := func(pointCount) { 131 | inCircleCount := 0 132 | 133 | rand.seed(timelib.time_unix(timelib.now())) 134 | 135 | for i := 0; i < pointCount; i++ { 136 | x := rand.float() 137 | y := rand.float() 138 | 139 | if x*x+y*y < 1 { 140 | inCircleCount++ 141 | } 142 | } 143 | 144 | Pi := (4.0 * inCircleCount) / pointCount 145 | 146 | return Pi 147 | } 148 | 149 | countStrT := getVar("Count"); 150 | 151 | countT := 1000; 152 | 153 | if !text.has_prefix(countStrT, "TXERROR:") { 154 | countT = int(countStrT) 155 | } 156 | 157 | if (countT == undefined) { 158 | countT = 1000 159 | } 160 | 161 | fmt.printf("Count: %v\n", countT); 162 | 163 | resultG := calPi(countT) 164 | 165 | ` 166 | 167 | setVar("Count", toString(countT)) 168 | 169 | result = runScript(tgStrT, "tg") 170 | 171 | endTime = time.Now() 172 | 173 | fmt.Printf("Result: %v\n", result) 174 | 175 | fmt.Printf("Duration: %v s\n", endTime.Sub(startTime)) 176 | 177 | // fmt.Printf("Test 1\n") 178 | 179 | // startTime = time.Now() 180 | 181 | // result = 0.0 182 | 183 | // for i = 0; i < 10000000; i ++ { 184 | // result += i * i 185 | // } 186 | 187 | // endTime = time.Now() 188 | 189 | // fmt.Printf("Result: %v\n", result) 190 | 191 | // fmt.Printf("Duration: %v\n", endTime.Sub(startTime)) 192 | 193 | // fmt.Printf("Test 2\n") 194 | 195 | // startTime = time.Now() 196 | 197 | // resultInt = fibonacciFlat(100000000) 198 | 199 | // endTime = time.Now() 200 | 201 | // fmt.Printf("Result: %v\n", resultInt) 202 | 203 | // fmt.Printf("Duration: %v\n", endTime.Sub(startTime)) 204 | 205 | // fmt.Printf("Test 2r\n") 206 | 207 | // startTime = time.Now() 208 | 209 | // resultInt = fibonacci(20) 210 | 211 | // endTime = time.Now() 212 | 213 | // fmt.Printf("Result: %v\n", resultInt) 214 | 215 | // fmt.Printf("Duration: %v\n", endTime.Sub(startTime)) 216 | 217 | // fmt.Printf("Test 3\n") 218 | 219 | // startTime = time.Now() 220 | 221 | // result = 0.0 222 | 223 | // for i = 0; i < 1000000; i ++ { 224 | // result += rand.Float64() 225 | // } 226 | 227 | // endTime = time.Now() 228 | 229 | // fmt.Printf("Result: %v\n", result) 230 | 231 | // fmt.Printf("Duration: %v\n s", endTime.Sub(startTime)) 232 | 233 | // fmt.Printf("Test 4\n") 234 | 235 | // startTime = time.Now() 236 | 237 | // result = calPi(1000000) 238 | 239 | // endTime = time.Now() 240 | 241 | // fmt.Printf("Result: %v\n", result) 242 | 243 | // fmt.Printf("Duration: %v s\n", endTime.Sub(startTime)) 244 | 245 | } 246 | 247 | main() 248 | 249 | -------------------------------------------------------------------------------- /scripts/performance.js: -------------------------------------------------------------------------------- 1 | function calPi(pointCount) { 2 | var inCircleCount = 0 3 | 4 | for (var i = 0; i < pointCount; i++) { 5 | var x = Math.random() 6 | var y = Math.random() 7 | 8 | if (x*x+y*y < 1) { 9 | inCircleCount++ 10 | } 11 | } 12 | 13 | var Pi = (4.0 * inCircleCount) / pointCount 14 | 15 | return Pi 16 | } 17 | 18 | 19 | var countStrT = getVar("Count"); 20 | 21 | println("Count:", countStrT); 22 | 23 | var countT = 1000; 24 | 25 | if (!countStrT.startsWith("TXERROR:")) { 26 | countT = parseInt(countStrT); 27 | } 28 | 29 | if (countT == NaN) { 30 | countT = 1000; 31 | } 32 | 33 | resultG = calPi(countT) 34 | 35 | -------------------------------------------------------------------------------- /scripts/performance.py: -------------------------------------------------------------------------------- 1 | import random 2 | import datetime 3 | import time 4 | 5 | 6 | def calPi(pointCount): 7 | inCircleCount = 0 8 | 9 | x = 0.0 10 | y = 0.0 11 | Pi = 0.0 12 | 13 | for i in range(pointCount): 14 | x = random.random() 15 | y = random.random() 16 | 17 | if (x * x + y * y) < 1: 18 | inCircleCount = inCircleCount + 1 19 | 20 | Pi = (4.0 * inCircleCount) / pointCount 21 | 22 | return Pi 23 | 24 | def square(a): 25 | return a * a 26 | 27 | 28 | random.seed() 29 | 30 | startTime = datetime.datetime.now() 31 | 32 | result = calPi(10000000) 33 | # result = 0.0 34 | 35 | # for i in range(1000000000): 36 | # result += square(i) 37 | 38 | endTime = datetime.datetime.now() 39 | 40 | print("Pi: ", result) 41 | print("Duration: ", endTime - startTime) 42 | -------------------------------------------------------------------------------- /scripts/performance.tg: -------------------------------------------------------------------------------- 1 | timelib := import("times") 2 | fmt := import("fmt") 3 | rand := import("rand") 4 | text := import("text") 5 | 6 | 7 | calPi := func(pointCount) { 8 | inCircleCount := 0 9 | 10 | rand.seed(timelib.time_unix(timelib.now())) 11 | 12 | for i := 0; i < pointCount; i++ { 13 | x := rand.float() 14 | y := rand.float() 15 | 16 | if x*x+y*y < 1 { 17 | inCircleCount++ 18 | } 19 | } 20 | 21 | Pi := (4.0 * inCircleCount) / pointCount 22 | 23 | return Pi 24 | } 25 | 26 | countStrT := getVar("Count"); 27 | 28 | countT := 1000; 29 | 30 | if !text.has_prefix(countStrT, "TXERROR:") { 31 | countT = int(countStrT) 32 | } 33 | 34 | if (countT == undefined) { 35 | countT = 1000; 36 | } 37 | 38 | fmt.println("Count:", countT); 39 | 40 | resultG := calPi(countT) 41 | 42 | 43 | -------------------------------------------------------------------------------- /scripts/pointer.gox: -------------------------------------------------------------------------------- 1 | // b is a string type pointer newly created 2 | b = new(string) 3 | 4 | printfln("b: %#v", b) 5 | 6 | // use built-in function setValue to assign values refered by pointers 7 | // This kind of assignment operation, *b = "abb", is not allowed 8 | setValue(b, "abb") 9 | 10 | // but * could be used as dereference operator 11 | c = *b 12 | 13 | pc1 = ^c 14 | 15 | println("c:", c, "pc1:", pc1) 16 | 17 | setValue(pc1, "123") 18 | 19 | println("c:", c, "pc1:", pc1) 20 | 21 | pl("b: %#v, *b: %#v", b, *b) 22 | 23 | // built-in function getValue is also available to get value from pointer 24 | d = getValue(b) 25 | 26 | println("d:", d) 27 | 28 | e = false 29 | 30 | println("e:", e) 31 | 32 | // use ^ to get reference/pointer instead of & in Gox 33 | f = ^e 34 | 35 | printfln("f: %#v", f) 36 | 37 | printfln("hex value of f: %x", f) 38 | 39 | // *f represents the value in variable e 40 | println("*f:", *f) 41 | 42 | setValue(f, true) 43 | 44 | println("*f:", *f) 45 | 46 | // value in e is changed after setValue called 47 | println("e:", e) 48 | 49 | // for complex types 50 | a = []string{"first", "second", "3rd"} // &[]string{"aa", "bb"} 这种方式在Gox语言(Qlang引擎)中是不允许的 51 | // a = []int{1, 2, 3} 52 | 53 | println("a:", a) 54 | 55 | // but you can retrieve pointer by this way 56 | pa = ^a 57 | 58 | printfln("pa: %T, %v, %#v, %p, %#v", pa, pa, pa, pa, *pa) 59 | 60 | va = getValue(pa) 61 | 62 | va[1] = "aaa" 63 | 64 | printfln("*pa: %#v", *pa) 65 | printfln("a: %#v", a) 66 | 67 | np = new(int) 68 | 69 | setValue(np, 16) 70 | 71 | pl("np: %v, *np: %v", np, *np) 72 | 73 | b1 = 0x7A // 01111010 74 | 75 | b2 = 0x21 // 00100001 76 | 77 | // 01111010 XOR 00100001 = 01011011 78 | printfln("b1 XOR b2 = %b", bitXor(b1, b2)) 79 | 80 | printfln("b1 XOR b2 = %b", tk.BitXor(b1, b2)) -------------------------------------------------------------------------------- /scripts/pointerCN.gox: -------------------------------------------------------------------------------- 1 | // 注:本代码例子中仅适用于Gox语言在使用Qlang-like引擎时 2 | 3 | // b是用内置函数new新创建的一个string类型的指针 4 | b = new(string) 5 | 6 | printfln("b: %#v", b) 7 | 8 | // 对于指针只能用setValue函数来给其对应的值赋新值 9 | // 类似这样的操作:*b = "abb"是不允许的 10 | setValue(b, "abb") 11 | 12 | // 但是同其他语言类似,*可以用于将指针变量对应的值取出来 13 | c = *b 14 | 15 | println("c:", c) 16 | 17 | // 也可以用内置函数getValue从指针中取值 18 | d = getValue(b) 19 | 20 | println("d:", d) 21 | 22 | e = false 23 | 24 | println("e:", e) 25 | 26 | // Gox语言中是使用 ^ 来进行取地址/引用操作的 27 | // 注意,因此^不能被用于异或操作 28 | f = ^e 29 | 30 | printfln("f: %#v", f) 31 | 32 | printfln("hex value of f: %x", f) 33 | 34 | // *f表示指针变量e指向的值 35 | println("*f:", *f) 36 | 37 | setValue(f, true) 38 | 39 | println("*f:", e) 40 | 41 | // e对应的值在使用了setValue后改变了 42 | println("e:", e) 43 | 44 | // 对于复合变量 45 | a = []string{"first", "second", "3rd"} // &[]string{"aa", "bb"} 这种方式在Gox语言(Qlang引擎)中是不允许的,&不能用于取指针 46 | 47 | println("a:", a) 48 | 49 | // 但是可以用这种方式获得需要的指针 50 | pa = ^a 51 | 52 | printfln("pa: %#v", pa) 53 | 54 | // 如果要做二进制按位异或不能用“^”符号了,需要用内置函数bitXor或者tk包中的BitXor 55 | b1 = 0x7A // 01111010 56 | 57 | b2 = 0x21 // 00100001 58 | 59 | // 01111010 XOR 00100001 = 01011011 60 | printfln("b1 XOR b2 = %b", bitXor(b1, b2)) 61 | 62 | printfln("b1 XOR b2 = %b", tk.BitXor(b1, b2)) -------------------------------------------------------------------------------- /scripts/portForward1.gox: -------------------------------------------------------------------------------- 1 | func copy(w, r) { 2 | _, err1 := io.Copy(w, r) 3 | if err1 != nil { 4 | pl("failed to copy: %v", err1) 5 | } 6 | 7 | w.Close() 8 | } 9 | 10 | func forward(lc, server) { 11 | defer lc.Close() 12 | 13 | rc, err2 := net.Dial("tcp", server) 14 | if err2 != nil { 15 | pl("failed to forward: %v", err2) 16 | return 17 | } 18 | 19 | pl("Forwarding connection to %v", server) 20 | 21 | go copy(rc, lc) 22 | copy(lc, rc) 23 | pl("Terminated: %s -> %s ", lc.RemoteAddr(), server) 24 | } 25 | 26 | func start(local, serverA) { 27 | l, err3 := net.Listen("tcp", local) 28 | if err3 != nil { 29 | pl("failed to start: %v", err3) 30 | exit() 31 | } 32 | defer l.Close() 33 | 34 | pl("Listening on %v", local) 35 | 36 | for { 37 | // Wait for a connection. 38 | conn, err4 := l.Accept() 39 | if err4 != nil { 40 | pl("failed to accept: %v", err4) 41 | } 42 | 43 | pl("New connection from %v", conn.RemoteAddr()) 44 | // Handle the connection in a new goroutine. 45 | // The loop then returns to accepting, so that 46 | // multiple connections may be served concurrently. 47 | go forward(conn, serverA) 48 | } 49 | } 50 | 51 | pl("Usage: %s ", argsG[0]) 52 | 53 | start(getSwitch(argsG, "-local=", ""), getSwitch(argsG, "-remote=", "")) -------------------------------------------------------------------------------- /scripts/portForward1Compact.gox: -------------------------------------------------------------------------------- 1 | 2 | tk.StartTransparentProxy(getSwitch(argsG, "-local=", "0.0.0.0:7481"), getSwitch(argsG, "-remote=", "0.0.0.0:7480"), "-verbose") 3 | 4 | -------------------------------------------------------------------------------- /scripts/portForward2.gox: -------------------------------------------------------------------------------- 1 | func forward(connA, remoteA) { 2 | clientT, errT := net.Dial("tcp", remoteA) 3 | if errT != nil { 4 | log.Fatalf("Dial failed: %v", errT) 5 | } 6 | 7 | log.Printf("Connected to localhost %v\n", connA) 8 | 9 | go func() { 10 | defer clientT.Close() 11 | defer connA.Close() 12 | io.Copy(clientT, connA) 13 | }() 14 | 15 | go func() { 16 | defer clientT.Close() 17 | defer connA.Close() 18 | io.Copy(connA, clientT) 19 | }() 20 | } 21 | 22 | listenerT, err1T := net.Listen("tcp", getSwitch(argsG, "-local=", "0.0.0.0:7481")) 23 | if err1T != nil { 24 | log.Fatalf("Failed to setup listener: %v", err1T) 25 | } 26 | 27 | for { 28 | connT, err1T := listenerT.Accept() 29 | if err1T != nil { 30 | log.Fatalf("ERROR: failed to accept listener: %v", err1T) 31 | } 32 | 33 | log.Printf("Accepted connection %v\n", connY) 34 | 35 | go forward(connT, getSwitch(argsG, "-remote=", "0.0.0.0:7480")) 36 | } 37 | -------------------------------------------------------------------------------- /scripts/portForward2Compact.gox: -------------------------------------------------------------------------------- 1 | 2 | tk.StartTransparentProxy2(getSwitch(argsG, "-local=", "0.0.0.0:7481"), getSwitch(argsG, "-remote=", "0.0.0.0:7480"), "-verbose") 3 | 4 | -------------------------------------------------------------------------------- /scripts/qexports.gox: -------------------------------------------------------------------------------- 1 | packageNameT = tk.Trim(tk.GetParameterByIndexWithDefaultValue(os.Args, 2, "")) 2 | 3 | if packageNameT == "" { 4 | tk.Pl("not enough parameters") 5 | return 6 | } 7 | 8 | basePathT, errT = tk.EnsureBasePath("gox") 9 | 10 | if errT != nil { 11 | checkError(errT) 12 | } 13 | 14 | tmpPathT = tk.JoinPath(basePathT, "tmp") 15 | 16 | tk.EnsureMakeDirsE(tmpPathT) 17 | 18 | pl("tmp path: %v", tmpPathT) 19 | 20 | rs = tk.SystemCmd("cmd", "/c", `qexport -outpath `+tmpPathT+` ` + packageNameT) 21 | 22 | pl(rs) 23 | 24 | if !tk.IfFileExists(tk.JoinPath(tmpPathT, packageNameT)) { 25 | pl("file not created") 26 | } 27 | 28 | goPathT = os.Getenv("GOPATH") 29 | 30 | tk.Pl("CMD: %v", `xcopy /E /I /Y `+tk.JoinPath(tmpPathT, packageNameT)+` ` + tk.JoinPath(goPathT, `src/github.com/topxeq/qlang/lib`, packageNameT)) 31 | rs = tk.SystemCmd("cmd", "/c", `xcopy /E /I /Y `+tk.JoinPath(tmpPathT, packageNameT)+` ` + tk.JoinPath(goPathT, `src/github.com/topxeq/qlang/lib`, packageNameT)) 32 | 33 | pl(tk.ConvertStringToUTF8(rs, "")) 34 | -------------------------------------------------------------------------------- /scripts/regexpx.gox: -------------------------------------------------------------------------------- 1 | regexp = github_topxeq_regexpx 2 | 3 | 4 | re := regexp.MustCompile(`^(\w)\w+\k{1}$`) 5 | 6 | fmt.Println(re.MatchString("acca")) 7 | fmt.Println(re.MatchString("accccab")) 8 | fmt.Println(re.MatchString("AA")) 9 | 10 | pl("found1: %v", tk.RegFindFirstX("abcde123456!#@e1abcdefg", `(e\d).*?\k{1}`, 0)) 11 | pl("found2: %v", tk.RegFindFirstX("abcde123456!#@e1abcdefg", `.e.(?![a-z])`, 0)) 12 | 13 | pass() -------------------------------------------------------------------------------- /scripts/replaceGoxn.gox: -------------------------------------------------------------------------------- 1 | gopathT = os.Getenv("GOPATH") 2 | 3 | if gopathT == "" { 4 | pl("GOPATH not defined") 5 | return 6 | } 7 | 8 | sourceFileNameT = tk.JoinPath(gopathT, "/src/github.com/topxeq/gox/gox.go") 9 | 10 | fcT = tk.LoadStringFromFile(sourceFileNameT) 11 | 12 | if tk.IsErrorString(fcT) { 13 | pl("load source file failed: %v", tk.GetErrorString(fcT)) 14 | return 15 | } 16 | 17 | foundT = tk.RegFindFirst(fcT, `(?m)\s*var defaultExports = map\[string\]interface\{\}\{[\s\S]*?"leBufG": leBufG`, 0) 18 | 19 | if tk.IsErrorString(foundT) { 20 | pl("the part not found, maybe not expected source file: %v", tk.GetErrorString(foundT)) 21 | return 22 | } 23 | 24 | // pl("srcFound: %v", foundT) 25 | 26 | destFileNameT = tk.JoinPath(gopathT, "/src/github.com/topxeq/goxn/goxn.go") 27 | 28 | fcT = tk.LoadStringFromFile(destFileNameT) 29 | 30 | if tk.IsErrorString(fcT) { 31 | pl("load source file failed: %v", tk.GetErrorString(fcT)) 32 | return 33 | } 34 | 35 | found2T = tk.RegFindFirst(fcT, `(?m)\s*var defaultExports = map\[string\]interface\{\}\{[\s\S]*?"leBufG": leBufG`, 0) 36 | 37 | if tk.IsErrorString(found2T) { 38 | pl("the part not found, maybe not expected source file: %v", tk.GetErrorString(found2T)) 39 | return 40 | } 41 | 42 | // pl("destFound: %v", found2T) 43 | 44 | fcNewT = tk.Replace(fcT, found2T, foundT) 45 | 46 | pl("fcNewT: %v", fcNewT) 47 | 48 | rs := saveText(fcNewT, destFileNameT) 49 | 50 | pl("rs: %v", rs) 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /scripts/replaceTextInFiles.gox: -------------------------------------------------------------------------------- 1 | dirT = getSwitch(argsG, "-dir=", ".") 2 | 3 | patternT = getSwitch(argsG, "-pattern=", "*") 4 | 5 | findT = getSwitch(argsG, "-find=", "") 6 | 7 | if ifSwitchExists(argsG, "-clip") { 8 | findT = getClipText() 9 | } 10 | 11 | replaceT = getSwitch(argsG, "-replace=", "") 12 | 13 | filesT = getFiles(dirT, "-recursive", "-pattern="+patternT) 14 | 15 | // pln(filesT) 16 | 17 | for i, v = range filesT { 18 | // pl("process [%v] %v", i, v) 19 | 20 | fcT = loadTextX(v.Abs) 21 | 22 | if isErr(fcT) { 23 | pln(fcT) 24 | continue 25 | } 26 | 27 | foundT = regFind(fcT, findT, 0) 28 | 29 | if isErrStr(foundT) { 30 | 31 | if foundT != "TXERROR:no match"{ 32 | pln(foundT) 33 | exit() 34 | } 35 | // pln(foundT) 36 | continue 37 | } 38 | 39 | newFcT = regReplace(fcT, findT, replaceT) 40 | 41 | rs := saveTextX(newFcT, v.Abs) 42 | 43 | if isErr(rs) { 44 | pl("failed to save new text to file %v", v.Abs) 45 | exit() 46 | } 47 | } 48 | 49 | 50 | -------------------------------------------------------------------------------- /scripts/runXie.gox: -------------------------------------------------------------------------------- 1 | codeT := ` 2 | var $map1 map 3 | 4 | setMapItem $map1 "姓名" 张三 5 | 6 | setMapItem $map1 "年龄" #i39 7 | 8 | var $map2 map 9 | 10 | setMapItem $map2 "姓名" 张胜利 11 | 12 | setMapItem $map2 "年龄" #i5 13 | 14 | var $list1 list 15 | 16 | addItem $list1 $map2 17 | 18 | setMapItem $map1 "子女" $list1 19 | 20 | plo $map1 21 | 22 | toJson $map1 $push -indent -sort 23 | 24 | pln $pop 25 | 26 | 27 | ` 28 | 29 | runXie(codeT, nil) -------------------------------------------------------------------------------- /scripts/sciter.gox: -------------------------------------------------------------------------------- 1 | // 设置两个Sciter包的简称 2 | sciter = github_scitersdk_gosciter 3 | window = github_scitersdk_gosciter_window 4 | 5 | // htmlT中将是在Sciter界面中载入的HTML页面文本 6 | // 其中self.ready()函数类似JQuery中的$(document).ready函数 7 | // 在其中定义了按钮2点击后的回调函数,调用了Gox语言中定义的prints函数 8 | htmlT = ` 9 | 10 | 11 | 12 | 13 | 14 | Sciter演示 15 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | ` 32 | 33 | // 锁死GUI线程,理论上所有图形界面操作应该在一个线程中进行 34 | runtime.LockOSThread() 35 | 36 | // 创建Sciter对象,并设置大小位置为默认 37 | w, err := window.New(sciter.DefaultWindowCreateFlag, sciter.DefaultRect) 38 | if err != nil { 39 | log.Fatal(err) 40 | } 41 | 42 | // 载入HTML文本 43 | w.LoadHtml(htmlT, "") 44 | 45 | // 设置图形窗口标题 46 | w.SetTitle("Sciter演示") 47 | 48 | // 设定一个Gox语言函数供TiScript中调用 49 | // 注意输入输出参数的转换方式 50 | w.DefineFunction("prints", func(args) { 51 | fmt.Println(args[0].String()) 52 | 53 | return sciter.NewValue("") 54 | }) 55 | 56 | // 选择界面中的根元素 57 | root, _ := w.GetRootElement() 58 | 59 | // 选取id为btn1的元素,即按钮1 60 | btn1, _ := root.SelectById("btn1") 61 | 62 | // 设置按钮1点击后的Gox语言回调函数 63 | btn1.OnClick(func() { 64 | fmt.Println("btn1被点击了") 65 | 66 | btn1.SetStyle("color", "#FF0000") 67 | 68 | fmt.Println(btn1.Html(true)) 69 | btn1.SetHtml("已点击", sciter.SIH_REPLACE_CONTENT) 70 | 71 | }) 72 | 73 | // 显示Sciter图形界面并开始运行之 74 | w.Show() 75 | w.Run() 76 | -------------------------------------------------------------------------------- /scripts/sciter01.gox: -------------------------------------------------------------------------------- 1 | sciter = github_scitersdk_gosciter 2 | window = github_scitersdk_gosciter_window 3 | 4 | w, err := window.New(sciter.SW_TITLEBAR| 5 | sciter.SW_RESIZEABLE| 6 | sciter.SW_CONTROLS| 7 | sciter.SW_MAIN| 8 | sciter.SW_ENABLE_DEBUG, 9 | nil) 10 | if err != nil { 11 | checkError(err) 12 | } 13 | //load file;加载文件 14 | w.LoadFile(`d:\tmpx\demo1.html`) 15 | //set title; 设置标题 16 | w.SetTitle("Hello, world") 17 | //show;显示窗口 18 | w.Show() 19 | //run, loop message;运行窗口,进入消息循环 20 | w.Run() -------------------------------------------------------------------------------- /scripts/sciter02.gox: -------------------------------------------------------------------------------- 1 | sciter = github_scitersdk_gosciter 2 | window = github_scitersdk_gosciter_window 3 | 4 | //创建window窗口 5 | //参数一表示创建窗口的样式 6 | //SW_TITLEBAR 顶层窗口,有标题栏 7 | //SW_RESIZEABLE 可调整大小 8 | //SW_CONTROLS 有最小/最大按钮 9 | //SW_MAIN 应用程序主窗口,关闭后其他所有窗口也会关闭 10 | //SW_ENABLE_DEBUG 可以调试 11 | //参数二表示创建窗口的矩形 12 | w, err := window.New(sciter.SW_TITLEBAR| 13 | sciter.SW_RESIZEABLE| 14 | sciter.SW_CONTROLS| 15 | sciter.SW_MAIN| 16 | sciter.SW_ENABLE_DEBUG, 17 | //给窗口设置个大小 18 | // &sciter.Rect{Left: int32(0), Top: 0, Right: 500, Bottom: 500}) 19 | &sciter.Rect{Left: int32(0), Top: int32(0), Right: int32(500), Bottom: int32(500)}) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | //加载文件 24 | // fp, err := filepath.Abs(`demo2.html`) 25 | // if err != nil { 26 | // log.Fatal(err) 27 | // } 28 | w.LoadFile(`d:\tmpx\demo2.html`) 29 | //设置标题 30 | w.SetTitle("表单") 31 | //显示窗口 32 | w.Show() 33 | //运行窗口,进入消息循环 34 | w.Run() 35 | -------------------------------------------------------------------------------- /scripts/sciter03.gox: -------------------------------------------------------------------------------- 1 | sciter = github_scitersdk_gosciter 2 | window = github_scitersdk_gosciter_window 3 | 4 | //一些基础操作 5 | func base(root) { 6 | //通过ID选择元素 7 | ul, _ := root.SelectById("list") 8 | //获取元素的文本 9 | text, _ := ul.Text() 10 | fmt.Println("text:", text) 11 | //获取元素的html 12 | //参数为真,则返回元素外部html 13 | //参数为假,则返回元素内部html 14 | text, _ = ul.Html(false) 15 | fmt.Println("html:", text) 16 | //获取子元素个数 17 | n, _ := ul.ChildrenCount() 18 | fmt.Println(n) 19 | } 20 | 21 | //动态的添加元素 22 | func addElement(root) { 23 | //创建一个元素 24 | add, _ := sciter.CreateElement("li", "444") 25 | //设置元素的属性 26 | add.SetAttr("data", "add") 27 | 28 | //通过标签和ID来选择元素,类似jquery 29 | ul, _ := root.SelectFirst("ul#list") 30 | //插入元素,下标从0开始 31 | err := ul.Insert(add, 3) 32 | if err != nil { 33 | log.Fatal("添加元素失败") 34 | } 35 | 36 | add2, _ := sciter.CreateElement("li", "") 37 | err2 := ul.Insert(add2, 4) 38 | //注意这里,元素先insert后再去设置html才有效 39 | //设置添加元素的html 40 | add2.SetHtml("555", sciter.SIH_REPLACE_CONTENT) 41 | if err2 != nil { 42 | log.Fatal("添加元素失败") 43 | } 44 | } 45 | 46 | //删除元素 47 | func delElement(root) { 48 | ul, _ := root.SelectFirst("ul#list") 49 | //获取第一个子元素,下标从0开始 50 | li, _ := ul.NthChild(0) 51 | //删除元素 52 | li.Delete() 53 | 54 | //我们也可以用css选择器直接选择要删除的元素 55 | //注意css里面的nth-child(n)下标从1开始 56 | li2, _ := root.SelectFirst("ul#list>li:nth-child(2)") 57 | //删除元素 58 | li2.Delete() 59 | } 60 | 61 | //修改元素 62 | func updElement(root) { 63 | li, _ := root.SelectFirst("ul#list>li:nth-child(1)") 64 | //给元素设置样式 65 | li.SetStyle("color", "#f00") 66 | //给元素设置html 67 | //参数一:html内容 68 | //参数二:html放在哪里,SIH_REPLACE_CONTENT表示替换旧内容 69 | li.SetHtml("baidu.com", sciter.SIH_REPLACE_CONTENT) 70 | //在最后面追加内容 71 | li.SetHtml("哈哈", sciter.SIH_APPEND_AFTER_LAST) 72 | //设置元素属性 73 | li.SetAttr("test", "test") 74 | li2, _ := root.SelectFirst("ul#list>li:nth-child(2)") 75 | //设置文本 76 | li2.SetText("我改我改") 77 | } 78 | 79 | //查找元素 80 | func selElement(root) { 81 | //通过css选择器选择元素,会返回*Element的slice 82 | root.Select("ul#list>li") 83 | //通过选择器返回第一个元素 84 | //也是调用的Select,不过只返回第一个元素 85 | root.SelectFirst("ul#list>li") 86 | //通过元素ID 87 | root.SelectById("list") 88 | //选择父元素 89 | //参数二:表示深度 90 | root.SelectParent("li", 1) 91 | //返回选择器匹配唯一子元素,如果没有或匹配多个,会引发Panic 92 | root.SelectUnique("ul#list>li:nth-child(1)") 93 | } 94 | 95 | //创建一个新窗口 96 | //这里参数一和参数二都使用的默认值 97 | //DefaultWindowCreateFlag = SW_TITLEBAR | SW_RESIZEABLE | SW_CONTROLS | SW_MAIN | SW_ENABLE_DEBUG 98 | //DefaultRect = &Rect{0, 0, 300, 400} 99 | w, err := window.New(sciter.DefaultWindowCreateFlag, sciter.DefaultRect) 100 | if err != nil { 101 | log.Fatal(err) 102 | } 103 | //设置标题 104 | w.SetTitle("文本html") 105 | html := ` 106 | 107 | 108 |
    109 |
  • 111
  • 110 |
  • 222
  • 111 |
  • 333
  • 112 |
113 | 114 | ` 115 | //加载html,从一个字符串变量中 116 | w.LoadHtml(html, "") 117 | //窗口获取根元素,这里应该是html 118 | root, _ := w.GetRootElement() 119 | 120 | //这里把一些操作单独写成函数方便查看 121 | base(root) 122 | addElement(root) 123 | delElement(root) 124 | updElement(root) 125 | selElement(root) 126 | 127 | //显示窗口 128 | w.Show() 129 | //运行窗口,进入消息循环 130 | w.Run() 131 | -------------------------------------------------------------------------------- /scripts/sciter04.gox: -------------------------------------------------------------------------------- 1 | sciter = github_scitersdk_gosciter 2 | window = github_scitersdk_gosciter_window 3 | 4 | htmlT = ` 5 | 6 | 7 | 8 | 9 | 10 | 事件处理 11 | 12 | 13 | 14 | 15 | 16 | 17 | 48 | 49 | 50 | ` 51 | 52 | //设置元素的处理程序 53 | func setElementHandlers(root) { 54 | btn1, _ := root.SelectById("btn1") 55 | //处理元素简单点击事件 56 | btn1.OnClick(func() { 57 | fmt.Println("btn1被点击了") 58 | }) 59 | 60 | //这里给元素定义的方法是在tiscript中进行调用的 61 | //并且作为元素的属性进行访问 62 | btn1.DefineMethod("test", func(args) { 63 | //我们把从传入的参数打印出来 64 | for _, arg := range args { 65 | //String()把参数转换成字符串 66 | fmt.Print(arg.String() + " ") 67 | } 68 | 69 | //返回一个空值 70 | return sciter.NullValue() 71 | }) 72 | btn2, _ := root.SelectById("btn2") 73 | //调用在tiscript中定义的方法 74 | data, _ := btn2.CallMethod("test2", sciter.NewValue("1"), sciter.NewValue("2"), sciter.NewValue("3")) 75 | //输出调用方法的返回值 76 | fmt.Println(data.String()) 77 | } 78 | 79 | 80 | callback1 = func(p) { 81 | //显示加载资源的uri 82 | fmt.Println("加载:", p.Uri()) 83 | return sciter.LOAD_OK 84 | } 85 | 86 | callback2 = func(p) { 87 | fmt.Println("加载中:", p.Uri()) 88 | return sciter.LOAD_OK 89 | } 90 | 91 | //设置回调 92 | func setCallbackHandlers(w) { 93 | //CallbackHandler是一个结构,里面定义了一些方法 94 | //你可以通过实现这些方法,自定义自已的回调 95 | cb := &sciter.CallbackHandler{ 96 | //加载数据开始 97 | OnLoadData: *sciter.NewScnLoadDataFunc(^callback1), 98 | //加载数据过程中 99 | OnDataLoaded: *sciter.NewScnDataLoaded(^callback2), 100 | } 101 | w.SetCallback(cb) 102 | } 103 | 104 | //定义函数 105 | func setWinHandler(w) { 106 | //定义函数,在tis脚本中需要通过view对象调用 107 | 108 | //定义inc函数,返回参数加1 109 | w.DefineFunction("inc", func(args) { 110 | return sciter.NewValue(args[0].Int() + 1) 111 | }) 112 | //定义dec函数,返回参数减1 113 | w.DefineFunction("dec", func(args) { 114 | return sciter.NewValue(args[0].Int() - 1) 115 | }) 116 | } 117 | 118 | //测试调用函数 119 | func testCallFunc(w) { 120 | //调用tis脚本中定义的函数 121 | data, _ := w.Call("sum", sciter.NewValue(10), sciter.NewValue(20)) 122 | fmt.Println(data.String()) 123 | root, _ := w.GetRootElement() 124 | //我们也可以指定元素调用函数 125 | data, _ = root.CallFunction("sum", sciter.NewValue(50), sciter.NewValue(100)) 126 | fmt.Println(data.String()) 127 | } 128 | 129 | //创建一个新窗口 130 | w, err := window.New(sciter.DefaultWindowCreateFlag, sciter.DefaultRect) 131 | if err != nil { 132 | log.Fatal(err) 133 | } 134 | 135 | // w.LoadFile(`d:\tmpx\demo4.html`) 136 | w.LoadHtml(htmlT, "") 137 | //设置标题 138 | w.SetTitle("事件处理") 139 | 140 | //设置回调处理程序 141 | setCallbackHandlers(w) 142 | //获取根元素 143 | root, _ := w.GetRootElement() 144 | //设置元素处理程序 145 | setElementHandlers(root) 146 | //设置窗口处理程序 147 | setWinHandler(w) 148 | //测试调用函数 149 | testCallFunc(w) 150 | 151 | //显示窗口 152 | w.Show() 153 | //运行窗口,进入消息循环 154 | w.Run() 155 | -------------------------------------------------------------------------------- /scripts/sciter05img.gox: -------------------------------------------------------------------------------- 1 | sciter = github_scitersdk_gosciter 2 | window = github_scitersdk_gosciter_window 3 | 4 | initGUI() 5 | 6 | htmlT = ` 7 | 8 | 9 | 10 | 11 | 12 | 加载图像 13 | 14 | 15 | 16 | 17 | 18 | ` 19 | 20 | //创建一个新窗口 21 | w, err := window.New(sciter.DefaultWindowCreateFlag, sciter.DefaultRect) 22 | if err != nil { 23 | log.Fatal(err) 24 | } 25 | 26 | // w.LoadFile(`d:\tmpx\demo4.html`) 27 | w.LoadHtml(htmlT, "") 28 | 29 | //设置标题 30 | w.SetTitle("加载图像……") 31 | 32 | //获取根元素 33 | root, _ := w.GetRootElement() 34 | 35 | img, _ := root.SelectById("imgID") 36 | 37 | imgData, errT := loadBytes(`c:\test\points.png`) 38 | 39 | checkError(errT) 40 | 41 | base64Data = base64Encode(imgData) 42 | 43 | img.SetAttr("src", `data:image/jpg;base64,`+base64Data) 44 | 45 | // img.Load("http://mat1.gtimg.com/www/images/qq2012/qqLogoFilter.png", sciter.RT_DATA_IMAGE) 46 | 47 | //显示窗口 48 | w.Show() 49 | 50 | //运行窗口,进入消息循环 51 | w.Run() 52 | -------------------------------------------------------------------------------- /scripts/screenShot.gox: -------------------------------------------------------------------------------- 1 | // 设置github.com/kbinani/screenshot包的简称 2 | screenshot = github_kbinani_screenshot 3 | 4 | // 显示有几个显示器以及 5 | pl("Total screen count: %v", screenshot.NumActiveDisplays()) 6 | 7 | // 获取第一个显示器的屏幕尺寸区域 8 | bounds := screenshot.GetDisplayBounds(0) 9 | 10 | // 截取该屏幕截图 11 | img, _ := screenshot.CaptureRect(bounds) 12 | 13 | 14 | // 保存截图到png格式的图片文件 15 | fileName := fmt.Sprintf("screenshot1_%vx%v.png", bounds.Dx(), bounds.Dy()) 16 | file, _ := os.Create(fileName) 17 | defer file.Close() 18 | 19 | image_png.Encode(file, img) 20 | 21 | -------------------------------------------------------------------------------- /scripts/screenShotToImage.gox: -------------------------------------------------------------------------------- 1 | // 设置github.com/kbinani/screenshot包的简称 2 | screenshot = github_kbinani_screenshot 3 | 4 | // 获取第一个显示器的屏幕尺寸区域 5 | bounds := screenshot.GetDisplayBounds(0) 6 | 7 | // 截取该屏幕截图 8 | // 注意 := 和 = 作为赋值用,在Gox语言中是等价的 9 | img, _ := screenshot.CaptureRect(bounds) 10 | 11 | 12 | // 创建一个字节缓冲区,用于存放图片的二进制数据 13 | bufT = new(bytes.Buffer) 14 | 15 | // 将屏幕截图以PNG格式编码到缓冲区中 16 | image_png.Encode(bufT, img) 17 | 18 | // 获取字节缓冲区的字节数组([]byte)类型引用 19 | dataT = bufT.Bytes() 20 | 21 | // 设置github.com/sciter-sdk/go-sciter及其子包window的简称 22 | sciter = github_scitersdk_gosciter 23 | window = github_scitersdk_gosciter_window 24 | 25 | // 将图片的字节数组数据转换为BASE64编码的字符串 26 | // 以便传递给Sciter 27 | // 由于从Gox到Sciter传递数据在传递数组等复杂类型时不太方便, 28 | // 因此最好转换成基本类型,如字符串和数字等 29 | // 复杂对象可以转换成JSON字符串传递 30 | base64StrT := tk.EncodeToBase64(dataT) 31 | 32 | // 设置Sciter格式的HTML网页字符串 33 | // 除了DOM元素id属性的设置等微小差异外,与一般的HTML网页完全相同 34 | // Sciter完整地支持HTML/HTML5,并有一定改进 35 | // 网页中的脚本部分,则不太一样,只支持Sciter自己的TiScript,不支持JavaScript 36 | // TiScript可以看作JavaScript的加强版,增加了类似JQuery的一些功能 37 | htmlT := ` 38 | 39 | 40 | 66 | 67 | 68 |
Screenshots 1-3
69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | ` 84 | 85 | // 锁定GUI线程,理论上GUI编程都要求在同一线程中更新界面元素 86 | runtime.LockOSThread() 87 | 88 | // 创建Sciter窗口,并指定窗口区域位置及大小 89 | w, err := window.New(sciter.DefaultWindowCreateFlag, sciter.NewRect(0, 0, 800, 600)) 90 | 91 | checkError(err) 92 | 93 | // 设置该窗口的一些属性 94 | w.SetOption(sciter.SCITER_SET_SCRIPT_RUNTIME_FEATURES, sciter.ALLOW_FILE_IO | sciter.ALLOW_SOCKET_IO | sciter.ALLOW_EVAL | sciter.ALLOW_SYSINFO) 95 | 96 | // 载入设计好的HTML页面 97 | w.LoadHtml(htmlT, "") 98 | 99 | // 设置窗口标题 100 | w.SetTitle("Screenshots") 101 | 102 | // 调用getImageData并传入图片数据显示 103 | // 此时只显示前三幅图片,第四幅图片将在后面用Gox代码来载入 104 | w.Call("getImageData", sciter.NewValue(base64StrT)) 105 | 106 | // 获取Sciter页面的根元素 107 | root, _ := w.GetRootElement() 108 | 109 | // 获取根元素下的id为img3ID的元素 110 | img, _ := root.SelectById("img3ID") 111 | 112 | // 设置该元素的src属性为BASE64格式的图片 113 | img.SetAttr("src", `data:image/png;base64,`+base64StrT) 114 | 115 | // 显示窗口并运行GUI图形界面 116 | w.Show() 117 | w.Run() 118 | -------------------------------------------------------------------------------- /scripts/script.gox: -------------------------------------------------------------------------------- 1 | vm, err = tk.NewScript(` 2 | print( "The variable the script received was ", var, "\n" ); 3 | 4 | if ( var >= 20 ) { 5 | print( "\tWe've run a long time..\n"); 6 | } else { 7 | print("\tWe'll keep going until we hit 20 iterations.\n"); 8 | } 9 | 10 | new = var * 4; 11 | 12 | return false; 13 | `) 14 | 15 | tk.SetScriptValue(vm, "var", 15) 16 | 17 | ret, err = vm.Run(nil) 18 | 19 | result = tk.GetScriptValue(vm, "new") 20 | 21 | pln(ret, err, result) -------------------------------------------------------------------------------- /scripts/selectFile.gox: -------------------------------------------------------------------------------- 1 | // 使用涉及图形界面的程序,都要先调用initGUI函数来初始化 2 | initGUI() 3 | 4 | // selectFileGUI函数会弹出对话框以供选择文件 5 | // 参数类似命令行的开关参数,均为可选且无顺序之分 6 | // 参数title为对话框提示文字 7 | // filterName为文件类型的提示文字 8 | // filter为文件类型匹配模式 9 | // start为起始目录(文件夹) 10 | rs = selectFileGUI("-title=请选择文件……", "-filterName=所有文件", "-filter=*", "-start=.") 11 | 12 | // 如果发生错误则提示后退出 13 | if isErrStr(rs) { 14 | pl("发生错误:%v", getErrStr(rs)) 15 | exit() 16 | } 17 | 18 | // getFileSize函数用于获取文件大小 19 | pl("您选择的文件是%v,大小为%v个字节", rs, getFileSize(rs)) 20 | 21 | -------------------------------------------------------------------------------- /scripts/sendAliyunSMS.gox: -------------------------------------------------------------------------------- 1 | // 设置阿里云短信发送包的简称 2 | alisms = github_aliyun_alibabacloudsdkgo_services_dysmsapi 3 | 4 | // 从命令行获取手机号,如果没有则使用默认手机号 5 | mobileT = getParameter(os.Args, 2, `此处为默认手机号`) 6 | 7 | if mobileT == "" { 8 | pl("手机号不能为空") 9 | exit() 10 | } 11 | 12 | // 建立发送短信的客户端对象 13 | // 第二个和第三个参数分别为AccessKeyID和AccessKeySecret 14 | // 注意将它们都替换成自己的 15 | clientT, errT = alisms.NewClientWithAccessKey("cn-hangzhou", "此处为AccessKeyID", "此处为AccessKeySecret") 16 | if errT != nil { 17 | pl("验证码发送失败:%v", errT) 18 | exit() 19 | } 20 | 21 | // 建立发送短消息的请求 22 | requestT = alisms.CreateSendSmsRequest() 23 | requestT.Scheme = "https" 24 | requestT.PhoneNumbers = mobileT 25 | requestT.SignName = "此处替换为短信签名" // 短信签名 26 | requestT.TemplateCode = "此处替换为需要使用的短信模板名称" // 短信模板名称 27 | 28 | // 生成一个6位纯数字的随机验证码 29 | authCodeT := tk.GenerateRandomString(6, 6, false, false, true, false, false, false) 30 | pl("生成的验证码为:%v", authCodeT) 31 | 32 | // 在请求中填入验证码 33 | requestT.TemplateParam = `{"code":"` + authCodeT + `"}` 34 | 35 | // 发送短信请求 36 | responseT, errT := clientT.SendSms(requestT) 37 | 38 | if errT != nil { 39 | pl("验证码发送失败:%v", errT) 40 | exit() 41 | } 42 | 43 | // 判断发送是否成功 44 | if responseT.Code != "OK" { 45 | pl("验证码发送失败,服务器返回消息:%v", responseT.Message) 46 | exit() 47 | } 48 | 49 | pl("发送成功,服务器响应:%v", responseT) 50 | 51 | // 正常结束程序 52 | pass() 53 | -------------------------------------------------------------------------------- /scripts/seq.gox: -------------------------------------------------------------------------------- 1 | seq1 := newEx("seq") 2 | 3 | plt(seq1) 4 | 5 | rs := seq1.Get() 6 | 7 | plt(rs) 8 | 9 | rs = seq1.Get() 10 | 11 | plt(rs) -------------------------------------------------------------------------------- /scripts/smtp.gox: -------------------------------------------------------------------------------- 1 | // set the short name for the package 2 | mailyak = github_domodwyer_mailyak 3 | 4 | // 3 ways to new a SMTP client to send mail, the first one supports TLS/Secure connection to mail servers 5 | mail = mailyak.New("mail.example.com:25", net_smtp.PlainAuth("", "user@example.com", "mypassword", "mail.example.com")) 6 | // mail := mailyak.New("mail.example.com:25", tk.GetPlainAuth("", "user@example.com", "mypassword", "mail.example.com")) 7 | // mail := mailyak.New("mail.example.com:25", tk.GetLoginAuth("user@example.com", "mypassword")) 8 | 9 | mail.To("test@example.com") 10 | 11 | mail.From("abc@other.com") 12 | mail.FromName("ABC") 13 | 14 | mail.Subject("[Important!] The Submission Result") 15 | 16 | mailBodyHtml = ` 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
  27 |
28 |

29 | Dear Mr. Tom,
30 | 31 | I am pleased to inform you that the submission has been accepted for publication.
32 |
33 | Yours sincerely
34 | Jerry
35 | 36 |
37 |
38 | 39 |
40 | 41 | 42 | 43 | ` 44 | 45 | // Write your HTML context in mail.HTML() 46 | _, errT = io.WriteString(mail.HTML(), mailBodyHtml) 47 | 48 | if errT != nil { 49 | tk.Pl("failed to write mail: %v", errT) 50 | return 51 | } 52 | 53 | mail.Plain().Set("Please use a standard mail or web-mail client") 54 | 55 | // Send the mail 56 | errT = mail.Send() 57 | if errT != nil { 58 | tk.Pl("failed to send mail: %v", errT) 59 | return 60 | } 61 | 62 | tk.Pl("Sent!") 63 | -------------------------------------------------------------------------------- /scripts/soap.gox: -------------------------------------------------------------------------------- 1 | // 准备发送到Web Service的XML请求体 2 | // 其中用“TX_”和“_TX”包含的是准备替换的文本 3 | // 这里用了简化处理,如果需要严谨的XML文本生成 4 | // 可以使用github.com/beevik/etree包(用github_beevik_etree引用) 5 | xmlT = ` 6 | 7 | 8 | 9 | TX_Path_XT 10 | TX_Reserv1_XT 11 | TX_Reserv2_XT 12 | TX_Reserv3_XT 13 | TX_Vbeln_XT 14 | 15 | 16 | 17 | ` 18 | 19 | // 替换其中的文本内容为自己所需的值 20 | // 注意要把文本值用tk.EncodeToXMLString函数编码一下 21 | // 以防出现会对XML文本造成混淆的字符(例如“<”或“>”等) 22 | bodyT = tk.Replace(xmlT, "TX_Path_XT", tk.EncodeToXMLString(urlT)) 23 | bodyT = tk.Replace(bodyT, "TX_Vbeln_XT", tk.EncodeToXMLString(v.customerOrderId)) 24 | bodyT = tk.Replace(bodyT, "TX_Reserv1_XT", tk.EncodeToXMLString(v.printSn)) 25 | bodyT = tk.Replace(bodyT, "TX_Reserv2_XT", tk.EncodeToXMLString(v.signDate)) 26 | bodyT = tk.Replace(bodyT, "TX_Reserv3_XT", tk.EncodeToXMLString(v.receiptUploadDate)) 27 | 28 | // 访问WebService接口 29 | // 替换其中的URL为自己实际的SOAP服务地址和端口 30 | // 其中请求头中加入了一个空的SOAPAction字段 31 | // 这是因为某些旧的SOAP服务需要这个字段 32 | rs, errT = tk.PostRequestX("http://your.webservice.com:8001/soap/create_receipt/801/create_receipt/create_receipt", tk.Trim(bodyT), "Content-Type:text/xml; charset=\"utf-8\"\nSOAPAction:", 15) 33 | 34 | // 检查可能出现的错误 35 | if errT != nil { 36 | tk.Pl("server response error: err: %v", errT) 37 | exit() 38 | } 39 | 40 | // 获取服务返回信息的某个xml字段 41 | // 我们这个例子服务将返回类似“1”这样的响应 42 | flagT, err = tk.GetNodeStringFromXML(rs, "Flag") 43 | 44 | checkErrf("failed to get flag: %v", err) 45 | 46 | if flagT != "" { 47 | pl("invalid flag: %v", flagT) 48 | exit() 49 | } -------------------------------------------------------------------------------- /scripts/socket.gox: -------------------------------------------------------------------------------- 1 | func connect(uri) { 2 | proxy = os.Getenv("http_proxy") 3 | 4 | if proxy != "" { 5 | u, e = net_url.Parse(proxy) 6 | 7 | if e != nil { 8 | return nil, e 9 | } 10 | 11 | return net.Dial("tcp", u.Host) 12 | } 13 | 14 | return net.Dial("tcp", uri) 15 | } 16 | 17 | c, e = connect("www.baidu.com:80") 18 | 19 | if e != nil { 20 | tk.CheckError(e) 21 | } 22 | 23 | c.Write([]byte("GET http://www.baidu.com/ HTTP/1.0\r\n\r\n")) 24 | 25 | b, e = io_ioutil.ReadAll(c) 26 | 27 | if e != nil { 28 | tk.CheckError(e) 29 | } 30 | 31 | printf("%s\n", b) 32 | -------------------------------------------------------------------------------- /scripts/socksClient.gox: -------------------------------------------------------------------------------- 1 | socks5 = github_topxeq_socks 2 | 3 | remoteIpT = getSwitch(argsG, "-remoteIp=", "0.0.0.0") 4 | remotePortT = getSwitch(argsG, "-remotePort=", "7480") 5 | localIpT = getSwitch(argsG, "-localIp=", "0.0.0.0") 6 | localPortT = getSwitch(argsG, "-localPort=", "7481") 7 | passwordT = getSwitch(argsG, "-password=", "acb123!@#") 8 | 9 | lenT = len(passwordT) 10 | 11 | if lenT < 16 { 12 | passwordT = passwordT + strings.Repeat("z", 16 - lenT) 13 | } elif lenT > 16 { 14 | passwordT = passwordT[0:16] 15 | } 16 | 17 | local, err := net.Listen("tcp", fmt.Sprintf("%s:%s", localIpT, localPortT)) 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | 22 | for { 23 | conn, err := local.Accept() 24 | if err != nil { 25 | log.Println("accept err:", err) 26 | } else { 27 | socks5.OpenLocalTunnel(conn, fmt.Sprintf("%s:%s", remoteIpT, remotePortT), passwordT) 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /scripts/socksClientCompact.gox: -------------------------------------------------------------------------------- 1 | // usage: gox socksClientCompact.gox -remoteIp=9.9.9.9 -remotePort=10080 -localIp=0.0.0.0 -localPort=1080 -password=acb123 2 | 3 | checkError(tk.StartSocksClient(argsG...)) -------------------------------------------------------------------------------- /scripts/socksServer.gox: -------------------------------------------------------------------------------- 1 | socks5 = github_topxeq_socks 2 | 3 | ipT = getSwitch(argsG, "-ip=", "0.0.0.0") 4 | portT = getSwitch(argsG, "-port=", "7480") 5 | passwordT = getSwitch(argsG, "-password=", "acb123!@#") 6 | 7 | lenT = len(passwordT) 8 | 9 | if lenT < 16 { 10 | passwordT = passwordT + strings.Repeat("z", 16 - lenT) 11 | } elif lenT > 16 { 12 | passwordT = passwordT[0:16] 13 | } 14 | 15 | remote, err := net.Listen("tcp", fmt.Sprintf("%s:%s", ipT, portT)) 16 | 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | 21 | for { 22 | conn, err := remote.Accept() 23 | if err != nil { 24 | log.Println("accept err:", err) 25 | } else { 26 | socks5.OpenRemoteTunnel(conn, passwordT) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /scripts/socksServerCompact.gox: -------------------------------------------------------------------------------- 1 | // usage: gox socksServerCompact.gox -ip=0.0.0.0 -port=10080 -password=acb123 2 | 3 | checkError(tk.StartSocksServer(argsG...)) -------------------------------------------------------------------------------- /scripts/sortByFunc.gox: -------------------------------------------------------------------------------- 1 | a = [1, 3, 2.5, 435, "abc", "zbds123", "0123a", "2.33", 2.33] 2 | 3 | b = sortByFuncQuick(a, func(i, j) { 4 | // pl("i: %v, j: %v", i, j) 5 | return toStr(a[i]) < toStr(a[j]) 6 | }) 7 | 8 | plv(b) 9 | 10 | m = [{"Name": "Tom", "Age": 18}, {"Name": "Jerry", "Age": 22}, {"Name": "Jerry", "Age": 18}, {"Name": "Peter", "Age": 8}] 11 | 12 | func sort1(dataA, i, j) { 13 | if dataA[i].Name < dataA[j].Name { 14 | return true 15 | } 16 | 17 | if dataA[i].Name == dataA[j].Name { 18 | return dataA[i].Age < dataA[j].Age 19 | } 20 | 21 | return false 22 | } 23 | 24 | m1 := sortByFunc(m, sort1) 25 | pln(toJson(m1, "-sort")) 26 | 27 | -------------------------------------------------------------------------------- /scripts/sortX.gox: -------------------------------------------------------------------------------- 1 | a = [1,3,2.5,435,"abc", "zbds123", "0123a", "2.33", 2.33] 2 | 3 | b = sortX(a) 4 | plv(b) 5 | 6 | c = sortX(a, "-desc") 7 | plv(c) 8 | 9 | 10 | m = [{"Name": "Tom", "Age": 18}, {"Name": "Jerry", "Age": 22}, {"Name": "Peter", "Age": 8}] 11 | 12 | sortX(m, "-key=Name") 13 | plv(m) 14 | 15 | sortX(m, "-key=Age") 16 | plv(m) 17 | 18 | m2 = ["abc", "ddd"] 19 | 20 | sortX(m2) 21 | plv(m2) 22 | 23 | m3 = [] 24 | 25 | m3 = append(m3, "abc") 26 | m3 = append(m3, "ddd") 27 | 28 | sortX(m3, "-desc") 29 | plv(m3) 30 | 31 | m4 = [] 32 | 33 | m4 = append(m4, ["abc", "123"]) 34 | m4 = append(m4, ["ddd", "777"]) 35 | 36 | sortX(m4, "-desc") 37 | plv(m4) 38 | 39 | -------------------------------------------------------------------------------- /scripts/sqlite.gox: -------------------------------------------------------------------------------- 1 | dbFilePathT := joinPath(getHomeDir(), `test.db`) 2 | 3 | // 如果存在该库(SQLite库是放在单一的文件中的)则删除该文件 4 | if tk.IfFileExists(dbFilePathT) { 5 | os.Remove(dbFilePathT) 6 | } 7 | 8 | // 创建新库 9 | dbT, errT = sqltk.ConnectDB("sqlite3", dbFilePathT) 10 | 11 | if errT != nil { 12 | printfln("创建数据库时发生错误:%v", errT) 13 | return 14 | } 15 | 16 | // 确保关闭数据库 17 | defer dbT.Close() 18 | 19 | //创建表 20 | sqlStmtT = ` 21 | create table TEST (ID integer not null primary key, CODE text); 22 | ` 23 | _, errT = dbT.Exec(sqlStmtT) 24 | if errT != nil { 25 | printfln("创建表时发生错误:%v", errT.Error()) 26 | return 27 | } 28 | 29 | // 开始一个数据库事务 30 | txT, errT = dbT.Begin() 31 | if errT != nil { 32 | printfln("新建事务时发生错误:%v", errT.Error()) 33 | return 34 | } 35 | 36 | // 准备一个SQL语句,用于向表中插入记录 37 | stmtT, errT = txT.Prepare("insert into TEST(ID, CODE) values(?, ?)") 38 | if errT != nil { 39 | printfln("准备SQL语句插入记录时发生错误:%v", errT.Error()) 40 | return 41 | } 42 | 43 | // 确保关闭SQL语句对象 44 | defer stmtT.Close() 45 | 46 | // 向表中插入10条记录 47 | // 每条记录的ID字段用循环变量的值赋值 48 | // CODE字段用随机产生的字符串 49 | for i = 0; i < 10; i++ { 50 | _, errT = stmtT.Exec(i, tk.GenerateRandomString(5, 8, true, true, true, false, false, false)) 51 | if errT != nil { 52 | printfln("执行SQL插入记录语句时发生错误:%v", errT.Error()) 53 | return 54 | } 55 | } 56 | 57 | // 执行事务,此时新纪录才会被真正插入到表中 58 | txT.Commit() 59 | 60 | // 进行SQL查询 61 | rowsT, errT = dbT.Query("select ID, CODE from TEST") 62 | if errT != nil { 63 | printfln("执行SQL查询语句时发生错误:%v", errT.Error()) 64 | return 65 | } 66 | 67 | // 确保关闭数据库查询结果集对象 68 | defer rowsT.Close() 69 | 70 | // 遍历查询结果 71 | for { 72 | 73 | if rowsT.Next() == false { 74 | break 75 | } 76 | 77 | idT = "" 78 | codeT = "" 79 | 80 | // 注意Gox语言中取指针要用符号^ 81 | errT = rowsT.Scan(^idT, ^codeT) 82 | if errT != nil { 83 | printfln("遍历查询结果时发生错误:%v", errT.Error()) 84 | return 85 | } 86 | 87 | printfln("ID: %v, CODE: %v", idT, codeT) 88 | } 89 | 90 | // 检查查询结果的错误 91 | errT = rowsT.Err() 92 | if errT != nil { 93 | printfln("查询结果有错误:%v", errT.Error()) 94 | } 95 | -------------------------------------------------------------------------------- /scripts/sqliteMem.gox: -------------------------------------------------------------------------------- 1 | // 创建在内存中的新库 2 | dbT, errT = sqltk.ConnectDB("sqlite3", `file:test.db?cache=shared&mode=memory`) 3 | 4 | if errT != nil { 5 | printfln("创建数据库时发生错误:%v", errT) 6 | return 7 | } 8 | 9 | // 确保关闭数据库 10 | defer dbT.Close() 11 | 12 | //创建表 13 | sqlStmtT = ` 14 | create table TEST (ID integer not null primary key, CODE text); 15 | ` 16 | _, errT = dbT.Exec(sqlStmtT) 17 | if errT != nil { 18 | printfln("创建表时发生错误:%v", errT.Error()) 19 | return 20 | } 21 | 22 | // 开始一个数据库事务 23 | txT, errT = dbT.Begin() 24 | if errT != nil { 25 | printfln("新建事务时发生错误:%v", errT.Error()) 26 | return 27 | } 28 | 29 | // 准备一个SQL语句,用于向表中插入记录 30 | stmtT, errT = txT.Prepare("insert into TEST(ID, CODE) values(?, ?)") 31 | if errT != nil { 32 | printfln("准备SQL语句插入记录时发生错误:%v", errT.Error()) 33 | return 34 | } 35 | 36 | // 确保关闭SQL语句对象 37 | defer stmtT.Close() 38 | 39 | // 向表中插入10条记录 40 | // 每条记录的ID字段用循环变量的值赋值 41 | // CODE字段用随机产生的字符串 42 | for i = 0; i < 10; i++ { 43 | _, errT = stmtT.Exec(i, tk.GenerateRandomString(5, 8, true, true, true, false, false, false)) 44 | if errT != nil { 45 | printfln("执行SQL插入记录语句时发生错误:%v", errT.Error()) 46 | return 47 | } 48 | } 49 | 50 | // 执行事务,此时新纪录才会被真正插入到表中 51 | txT.Commit() 52 | 53 | // 进行SQL查询 54 | rowsT, errT = dbT.Query("select ID, CODE from TEST") 55 | if errT != nil { 56 | printfln("执行SQL查询语句时发生错误:%v", errT.Error()) 57 | return 58 | } 59 | 60 | // 确保关闭数据库查询结果集对象 61 | defer rowsT.Close() 62 | 63 | // 遍历查询结果 64 | for { 65 | 66 | if rowsT.Next() == false { 67 | break 68 | } 69 | 70 | idT = "" 71 | codeT = "" 72 | 73 | // 注意Gox语言中取指针要用符号^ 74 | errT = rowsT.Scan(^idT, ^codeT) 75 | if errT != nil { 76 | printfln("遍历查询结果时发生错误:%v", errT.Error()) 77 | return 78 | } 79 | 80 | printfln("ID: %v, CODE: %v", idT, codeT) 81 | } 82 | 83 | // 检查查询结果的错误 84 | errT = rowsT.Err() 85 | if errT != nil { 86 | printfln("查询结果有错误:%v", errT.Error()) 87 | } 88 | -------------------------------------------------------------------------------- /scripts/sqliteOrdered.gox: -------------------------------------------------------------------------------- 1 | //This example demonstrates dbQueryOrdered function, which always get an Array of ordered maps 2 | 3 | dbFilePathT := joinPath(getHomeDir(), `test.db`) 4 | 5 | // Determine if the database already exists (run sqlite.char first to create one) 6 | if !fileExists(dbFilePathT) { 7 | fatalf("database not exists") 8 | } 9 | 10 | dbT := dbConnect("sqlite3", dbFilePathT) 11 | 12 | if isErr(dbT) { 13 | pl("failed to open the database file: %v", getErrStr(dbT)) 14 | exit() 15 | } 16 | 17 | sqlT := `select ID, CODE from TEST` 18 | 19 | rsT := dbQuery(dbT, sqlT) 20 | 21 | if isErr(rsT) { 22 | pl("failed to query database: %v", getErrStr(rsT)) 23 | dbClose(dbT) 24 | exit() 25 | } 26 | 27 | // ID and CODE will not always the same order in each item 28 | plt(rsT) 29 | 30 | // use dbQueryOrdered to query the database again 31 | rsT = dbQueryOrdered(dbT, sqlT) 32 | 33 | if isErr(rsT) { 34 | pl("failed to query database: %v", getErrStr(rsT)) 35 | dbClose(dbT) 36 | exit() 37 | } 38 | 39 | dbClose(dbT) 40 | 41 | // ID and CODE should be always the same order in each item 42 | plt(rsT) 43 | -------------------------------------------------------------------------------- /scripts/ssh.gox: -------------------------------------------------------------------------------- 1 | // create a SSH client by host name(or IP address), port, user name and password 2 | clientT, errT = tk.NewSSHClient("example.com", 22, "root", "mypassword") 3 | 4 | // if error occured, exit the program 5 | checkError(errT) 6 | 7 | // ensure close the client 8 | defer clientT.Close() 9 | 10 | // run "pwd" command on the remote server and get the output 11 | cmdT = "pwd" 12 | 13 | outT, errT = clientT.Run(cmdT) 14 | 15 | checkError(errT) 16 | 17 | pathT = tk.Trim(string(outT)) 18 | 19 | pl("current path: %v", pathT) 20 | 21 | // list the directory 22 | outT, errT = clientT.Run(`ls -p`) 23 | 24 | checkError(errT) 25 | 26 | filesT = tk.SplitLines(tk.Trim(string(outT))) 27 | 28 | lenT = len(filesT) 29 | 30 | dirCountT = 0 31 | 32 | for _, v = range filesT { 33 | if tk.EndsWith(v, "/") { 34 | dirCountT++ 35 | } 36 | } 37 | 38 | pl("%v\n", filesT) 39 | 40 | pl("totally %v files, %v of them is directory", lenT, dirCountT) 41 | 42 | // create a local file to uplaod 43 | errStrT = tk.SaveStringToFile("*****test****", `./abc.txt`) 44 | 45 | checkErrorString(errStrT) 46 | 47 | // upload the local file 48 | errT = clientT.Upload(`./abc.txt`, tk.Replace(tk.JoinPath(pathT, `abc.txt`), `\`, "/")) 49 | 50 | checkError(errT) 51 | 52 | // check if the upload process is successful 53 | outT, errT = clientT.Run(`ls -p; cat abc.txt`) 54 | 55 | checkError(errT) 56 | 57 | pl("files: \n%v", string(outT)) 58 | 59 | // create a file on the remote server 60 | clientT.Run(`echo "abc123" > down.txt`) 61 | 62 | // download it to local current directory 63 | errT = clientT.Download(`down.txt`, `./down.txt`) 64 | 65 | checkError(errT) 66 | 67 | // check and show the file content 68 | println(tk.SystemCmd("dir")) 69 | 70 | println("\nfile content: ", tk.LoadStringFromFile(`down.txt`)) 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /scripts/stack.gox: -------------------------------------------------------------------------------- 1 | utils = github_topxeq_gods_utils 2 | 3 | stack := newObject("stack") 4 | 5 | stack.Push(1) // 1 6 | pln(stack) 7 | 8 | stack.Push(2) // 1, 2 9 | pln(stack) 10 | 11 | pln(stack.Values()) // 2, 1 (LIFO order) 12 | pln(stack.Peek()) // 2,true 13 | pln(stack.Pop()) // 2, true 14 | pln(stack.Pop()) // 1, true 15 | pln(stack.Pop()) // nil, false (nothing to pop) 16 | 17 | stack.Push(1) // 1 18 | pln(stack) 19 | 20 | stack.Clear() // empty 21 | pln(stack) 22 | 23 | stack.Empty() // true 24 | pln(stack) 25 | 26 | stack.Size() // 0 27 | pln(stack) 28 | -------------------------------------------------------------------------------- /scripts/string.gox: -------------------------------------------------------------------------------- 1 | a = "good" 2 | 3 | b = "morning" 4 | 5 | c = a + " " + b 6 | 7 | pln(c) -------------------------------------------------------------------------------- /scripts/stringRing.gox: -------------------------------------------------------------------------------- 1 | ring = newStringRing(5) 2 | 3 | for i = 0; i < 20; i ++ { 4 | ring.Push("a"+toStr(i)) 5 | 6 | plv(ring) 7 | pln(ring.GetList()) 8 | pln(ring.GetString()) 9 | } 10 | 11 | -------------------------------------------------------------------------------- /scripts/struct1.gox: -------------------------------------------------------------------------------- 1 | client1T = &net_http.Client{Timeout: time.Duration(15 * time.Second)} 2 | 3 | pl("%#v", client1T) 4 | 5 | client2T = new(net_http.Client) 6 | 7 | pl("%#v", client2T) 8 | 9 | client2T.Timeout = time.Duration(30) 10 | 11 | pl("%#v", client2T) 12 | 13 | pl("%#v", client2T.Timeout) 14 | 15 | pl("%#v", client2T@Timeout) 16 | -------------------------------------------------------------------------------- /scripts/struct1CN.gox: -------------------------------------------------------------------------------- 1 | // 创建一个Go语言标准库中net/http包内的Client结构/对象 2 | // 并在创建时对其成员Timeout赋以初值15秒 3 | // 由于数据类型的要求,必须强制转换为time.Duration类型 4 | client1T = &net_http.Client{Timeout: time.Duration(15 * time.Second)} 5 | 6 | // 这样创建出来的是一个指针/引用 7 | pl("%#v", client1T) 8 | 9 | // 用内置函数new也可以创建Go语言中的结构体或对象,获得的也是指针 10 | client2T = new(net_http.Client) 11 | 12 | pl("%#v", client2T) 13 | 14 | // 然后可以对其字段进行单独赋值 15 | client2T.Timeout = time.Duration(30) 16 | 17 | pl("%#v", client2T) 18 | -------------------------------------------------------------------------------- /scripts/sync.gox: -------------------------------------------------------------------------------- 1 | valueG = 0 2 | groupG = new(sync.WaitGroup) 3 | 4 | mutexG = new(sync.Mutex) 5 | 6 | addRoutine = fn(countA) { 7 | 8 | for i = 0; i < countA; i++ { 9 | mutexG.Lock() 10 | valueG = valueG + 2 11 | mutexG.Unlock() 12 | } 13 | 14 | groupG.Done() 15 | 16 | } 17 | 18 | minusRoutine = fn(countA) { 19 | 20 | for i = 0; i < countA; i++ { 21 | mutexG.Lock() 22 | valueG = valueG - 2 23 | mutexG.Unlock() 24 | } 25 | 26 | groupG.Done() 27 | } 28 | 29 | times = 5000 30 | 31 | groupG.Add(2) 32 | 33 | go addRoutine(times) 34 | go minusRoutine(times - 2) 35 | 36 | groupG.Wait() 37 | 38 | printfln("valueG: %v", valueG) 39 | -------------------------------------------------------------------------------- /scripts/term.gox: -------------------------------------------------------------------------------- 1 | pterm = github_pterm_pterm 2 | 3 | // pterm.DefaultBigText.WithLetters(pterm.NewLettersFromString("Welcome")).Render() 4 | 5 | // // Print a large text with differently colored letters. 6 | // pterm.DefaultBigText.WithLetters(pterm.NewLettersFromStringWithStyle("W", pterm.NewStyle(pterm.FgCyan)), 7 | // pterm.NewLettersFromStringWithStyle("elcome", pterm.NewStyle(pterm.FgLightMagenta))). 8 | // Render() 9 | 10 | // pterm.DefaultCenter.Println("This text is centered!\nIt centeres the whole block by default.\nIn that way you can do stuff like this:") 11 | 12 | // // Generate BigLetters 13 | // s, _ := pterm.DefaultBigText.WithLetters(pterm.NewLettersFromString("PTerm")).Srender() 14 | // pterm.DefaultCenter.Println(s) // Print BigLetters with the default CenterPrinter 15 | 16 | // pterm.DefaultCenter.WithCenterEachLineSeparately().Println("This text is centered!\nBut each line is\ncentered\nseparately") 17 | 18 | pterm.DefaultHeader.Println("This is the default header!") 19 | 20 | second = time.Second 21 | 22 | introSpinner, _ := pterm.DefaultSpinner.WithRemoveWhenDone(true).Start("Waiting for 15 seconds...") 23 | time.Sleep(second) 24 | for i := 14; i > 0; i-- { 25 | if i > 1 { 26 | introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " seconds...") 27 | } else { 28 | introSpinner.UpdateText("Waiting for " + strconv.Itoa(i) + " second...") 29 | } 30 | time.Sleep(second) 31 | } 32 | introSpinner.Stop() -------------------------------------------------------------------------------- /scripts/test.gox: -------------------------------------------------------------------------------- 1 | // f1 = func(a) { 2 | // return 1 3 | // } 4 | 5 | // prin tln(f1(1)) 6 | 7 | // f2 = func(a) { 8 | // return 2 9 | // } 10 | 11 | // println(f2(1 / 0)) 12 | // b = 1 13 | // a = 1 14 | // f1 = fn() { 15 | // println(1.3) 16 | // } 17 | 18 | // f1() 19 | 20 | a = "1" 21 | 22 | b = ^a 23 | 24 | pl("%T", *b) 25 | 26 | // return 27 | 28 | func f2() { 29 | // println(1) 30 | println(1.4) 31 | } 32 | 33 | f2() 34 | 35 | Person = class { 36 | func f2(s) { 37 | this.name = s 38 | println(1.9) 39 | } 40 | 41 | } 42 | 43 | person1 = new Person 44 | 45 | person1.f2("a") 46 | 47 | pl("%#v", person1) 48 | 49 | person2 = new Person 50 | 51 | person2.f2("b") 52 | 53 | pl("%#v", person2) 54 | 55 | // f1() 56 | 57 | // f3 = fn() { 58 | // println(1.5) 59 | // } 60 | 61 | // f3() 62 | 63 | -------------------------------------------------------------------------------- /scripts/testAll.gox: -------------------------------------------------------------------------------- 1 | rs = systemCmd("gox", "-gopath", "basic.gox") 2 | 3 | testByText(rs, "3.4000000000000004\n", getSeq(), "basic.gox") 4 | 5 | rs = systemCmd("gox", "-gopath", "bitwise.gox") 6 | 7 | testByText(rs, "[0] (int)3\n[1] (int)3\n[2] (string)03\n[0] (int)1\n[1] (int)163\n[2] (int)163\n163 -> a3 -> 10100011\n92 -> 5C -> 01011100\n00001100\n01011111\n01010011\n", getSeq(), "bitwise.gox") 8 | 9 | rs = systemCmd("gox", "-gopath", "arrayContains.gox", "-verbose") 10 | 11 | testByText(rs, "true\nfalse\ntrue\nfalse\ntrue\nfalse\ntrue\nfalse\n", getSeq(), "arrayContains.gox") 12 | 13 | rs = systemCmd("gox", "-gopath", "limitStr.gox") 14 | 15 | testByText(rs, "abcde...\n34567...\nabcde!!!\n", getSeq(), "limitStr.gox") 16 | 17 | rs = systemCmd("gox", "-gopath", "findStringDiffPos.gox") 18 | 19 | testByText(rs, "4\n", getSeq(), "findStringDiffPos.gox") 20 | 21 | rs = systemCmd("gox", "-gopath", "sortByFunc.gox") 22 | 23 | testByText(rs, "[]interface {}{\"0123a\", 1, \"2.33\", 2.33, 2.5, 3, 435, \"abc\", \"zbds123\"}\n[{\"Age\":18,\"Name\":\"Jerry\"},{\"Age\":22,\"Name\":\"Jerry\"},{\"Age\":8,\"Name\":\"Peter\"},{\"Age\":18,\"Name\":\"Tom\"}]\n", getSeq(), "sortByFunc.gox") 24 | 25 | rs = systemCmd("gox", "-gopath", "anonymousFunc.gox") 26 | 27 | testByStartsWith(rs, "Hi! Nice to see you.\ncount= \n3\n8\n17\nCode stack:", getSeq(), "anonymousFunc.gox") 28 | 29 | rs = systemCmd("gox", "-gopath", "anyQueue.gox") 30 | 31 | testByReg(rs, `(?sm).*?&tk.AnyQueue{.*got 20018.*`, getSeq(), "anyQueue.gox") 32 | -------------------------------------------------------------------------------- /scripts/testCharlang.gox: -------------------------------------------------------------------------------- 1 | vmT, errT = newChar(` 2 | param (...vargs) 3 | 4 | println(vargs) 5 | 6 | try { 7 | 8 | a := 1 9 | 10 | println("abc") 11 | 12 | f := vargs[3]["test"] 13 | 14 | b := f(2, 3) 15 | 16 | println("b=", b) 17 | 18 | return "zzz" 19 | 20 | } catch err { 21 | printf("%+v\n", err) 22 | } 23 | 24 | 25 | 26 | `) 27 | 28 | if errT != nil { 29 | pl("compile failed: %v", errT) 30 | exit() 31 | } 32 | 33 | func test(x, y) { 34 | pl("x+y=%v", x+y) 35 | return x+y, nil 36 | } 37 | 38 | mapT = make(charlang.Map) 39 | 40 | mapT["a"] = charlang.ConvertToObject("abv") 41 | mapT["test"] = newCharFunc(test) 42 | 43 | plv(mapT) 44 | 45 | r, err := runChar(vmT, nil, nil, *newCharAny(w), msiToCharMap(fromJSON(`{"start": "1", "count": "10"}`)), mapT) 46 | 47 | plvsr(r, err) 48 | -------------------------------------------------------------------------------- /scripts/testWebView2.gox: -------------------------------------------------------------------------------- 1 | w = newWebView2("-title=Test WebView2", "-width=1024", "-height=768", "-icon=2", "-centerTrue") 2 | 3 | plo(w) 4 | 5 | if w == nil { 6 | pl("failed to create window") 7 | exit() 8 | } 9 | 10 | defer w.Destroy() 11 | 12 | w.SetSize(800, 600, webview2.HintNone) 13 | 14 | func delegate1(argsA...) { 15 | if len(argsA) < 1 { 16 | pl("not enough parameters") 17 | return "" 18 | } 19 | 20 | cmdT = argsA[0] 21 | 22 | if cmdT == "showNav" { 23 | pl("name: %v, value: %v", argsA[1], argsA[2]) 24 | } elif cmdT == "pl" { 25 | pl(argsA[1], argsA[2:]...) 26 | } 27 | 28 | return "" 29 | } 30 | 31 | w.Bind("delegateDo", newFuncIsI(delegate1)) 32 | 33 | // w.Navigate("http://example.com") 34 | 35 | htmlT = ` 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 107 | 108 | 109 |
110 | 111 | 112 | 113 |
114 |
115 |
116 | 117 | 118 | ` 119 | 120 | w.setHtml(htmlT) 121 | 122 | w.Run() 123 | 124 | pl("window exit") -------------------------------------------------------------------------------- /scripts/tmp.gox: -------------------------------------------------------------------------------- 1 | appleT = { 2 | "Type": "apple", 3 | "Color": "Red", 4 | "Weight": 10, 5 | "canEat": true, 6 | "Ingredients" : [ 7 | { 8 | "Name": "Protein", 9 | "Amount": 0.3, 10 | }, 11 | { 12 | "Name": "Sugar", 13 | "Amount": 10.4, 14 | }, 15 | ], 16 | } 17 | 18 | pv("appleT") 19 | println("\n---\n") 20 | 21 | newJSONT, errT = tk.ToJSON(appleT) 22 | 23 | if errT != nil { 24 | println("failed to generate JSON:", errT) 25 | return 26 | } 27 | 28 | pl("JSON: %v", newJSONT) 29 | 30 | println("\n---\n") 31 | 32 | nodeT = tk.GetJSONNode(newJSONT, "Color") 33 | pv("nodeT") 34 | 35 | println("\n---\n") 36 | 37 | node1T = tk.GetJSONNode(newJSONT, "canEat") 38 | pv("node1T") 39 | 40 | println("\n---\n") 41 | 42 | node2T = tk.GetJSONNodeAny(newJSONT, "Ingredients") 43 | pl("Value type: %v", node2T.ValueType()) 44 | 45 | println("\n---\n") 46 | 47 | pv("node2T") 48 | 49 | subNode1T = tk.GetJSONSubNode(node2T, 0, "Name") 50 | 51 | println("\n---\n") 52 | 53 | pv("subNode1T") 54 | 55 | subNode2T = tk.GetJSONNode(newJSONT, "Ingredients", 1, "Amount") 56 | 57 | println("\n---\n") 58 | pv("subNode2T") 59 | 60 | subNode3T = tk.GetJSONNode(newJSONT, "Ingredients", "*") 61 | 62 | println("\n---\n") 63 | pv("subNode3T") 64 | 65 | subSubNodeT = tk.GetJSONSubNode(subNode3T[0], "Name") 66 | 67 | println("\n---\n") 68 | pv("subSubNodeT") 69 | 70 | subNode4T = tk.GetJSONNodeAny(newJSONT, "Ingredients", 3, "Name") 71 | 72 | println("\n---\n") 73 | pv("subNode4T") 74 | 75 | pl("Value type: %v", subNode4T.ValueType()) 76 | 77 | pl("Last Error: %v", subNode4T.LastError()) -------------------------------------------------------------------------------- /scripts/toFromXml.gox: -------------------------------------------------------------------------------- 1 | // XML string to parse 2 | xmlT = ` 3 | 4 | 5 | 6 | Michael 7 | Johnson 8 | Reminder 9 | Don't forget the meeting! 10 | 11 | 12 | Louis 13 | 27 14 | 15 | 16 | Lisa 17 | 23 18 | 19 | 20 | Tom 21 | 31 22 | 23 | 24 | 25 | 26 | ` 27 | 28 | // parse XML and get the root node of the XML 29 | rootT = fromXML(xmlT) 30 | 31 | if isErr(rootT) { 32 | pl("failed to parse XML") 33 | return 34 | } 35 | 36 | // get the full tag of the node 37 | pl("root element is: %v", rootT.FullTag()) 38 | 39 | // get the child node text of the node 40 | pl("heading is: %v", rootT.SelectElement("heading").Text()) 41 | 42 | // get child elements 43 | membersT = rootT.SelectElement("members").ChildElements() 44 | 45 | // enumerate the child elements 46 | for i, v = range membersT { 47 | pl("[%v] name(%v): %v, age: %v", i, v.SelectElement("name").SelectAttrValue("lang", ""), v.SelectElement("name").Text(), v.SelectElement("age").Text()) 48 | } 49 | 50 | // find node/nodes using XPath 51 | tomT = rootT.FindElement(`//members/member[name='Lisa']`) 52 | 53 | // examples of native function: toXML 54 | pl("[to 1]%v", toXML(tomT)) 55 | 56 | pl("[to 2] %v", toXML(`abc 剑荡四方红树林 <1> "list"`)) 57 | 58 | pl("[to 3a] %v", toXML({"f1": "v1", "f2": {"f21":18, "f22": "v22", "f23": [{"itemName": "item1", "weight": 99}, {"itemName": "item2", "weight": 36}]}}, "-indent=2", "-root=test", `-rootAttr={"attr1": 69}`)) 59 | pl("[to 3b] %v", toXML({"f1": "v1", "f2": {"f21":18, "f22": "v22", "f23": [{"itemName": "item1", "weight": 99}, {"itemName": "item2", "weight": 36}]}})) 60 | 61 | pl("[to 4a] %v", toXML([1, 2, 3, "abc"], "-root=root", "-indent=2")) 62 | pl("[to 4b] %v", toXML([1, 2, 3, "abc"])) 63 | 64 | pass() 65 | -------------------------------------------------------------------------------- /scripts/undefined.gox: -------------------------------------------------------------------------------- 1 | 2 | a = 1.2 3 | 4 | pln("a defined:", isDefined(a)) 5 | 6 | pln("b defined:", isDefined(b)) 7 | 8 | pln("a undefined:", isUndefined(a)) 9 | 10 | pln("b undefined:", isUndefined(b)) 11 | -------------------------------------------------------------------------------- /scripts/urlValues.gox: -------------------------------------------------------------------------------- 1 | t = tk 2 | u = net_url 3 | 4 | v1 = make(u.Values) 5 | 6 | v1.Set("a", "123") 7 | 8 | t.Pl("%#v", v1) 9 | 10 | v2 = new(u.Values) 11 | 12 | t.Pl("%#v", v2) 13 | 14 | v2.Set("a", "123") 15 | 16 | t.Pl("%#v", v2) 17 | 18 | -------------------------------------------------------------------------------- /scripts/uselib.gox: -------------------------------------------------------------------------------- 1 | t = tk 2 | u = net_url 3 | 4 | v = make(u.Values) 5 | 6 | v.Set("a", "123") 7 | 8 | t.Pl("%#v", v) -------------------------------------------------------------------------------- /scripts/varInGoroutine.gox: -------------------------------------------------------------------------------- 1 | 2 | func f1(m) { 3 | i = 0 4 | v = 0 5 | 6 | c = [1 * m, 2 * m, 3 * m] 7 | 8 | for { 9 | for i, v = range c { 10 | pln(m, i, v) 11 | } 12 | 13 | sleep(toFloat(m) / 100) 14 | } 15 | 16 | } 17 | 18 | go f1(1) 19 | 20 | go f1(2) 21 | 22 | go f1(2.3) 23 | 24 | d = ["a", "b", "c", "d"] 25 | 26 | for { 27 | for i, v = range d { 28 | pln(0, i, v) 29 | } 30 | 31 | sleep(1.7) 32 | } 33 | -------------------------------------------------------------------------------- /scripts/variable.gox: -------------------------------------------------------------------------------- 1 | a = 1.6 2 | b = 12 3 | 4 | pln( a + b) 5 | 6 | c // define a variable but not assign the value 7 | 8 | c = 19 9 | -------------------------------------------------------------------------------- /scripts/viewLines.gox: -------------------------------------------------------------------------------- 1 | // view the specified line in a text file along with the lines nearby 2 | 3 | // get file name to view from command line 4 | fileNameT = getParameter(argsG, 1, "") 5 | 6 | if fileNameT == "" { 7 | pl("not enough paramters") 8 | exit() 9 | } 10 | 11 | // get the line number 12 | lineNumberT = getIntSwitch(argsG, "-line=", 1) 13 | 14 | // get the range of the nearby lines 15 | rangeT = getIntSwitch(argsG, "-range=", 3) 16 | 17 | // open the file for read 18 | f, err = os.Open(fileNameT) 19 | 20 | // ensure close the file 21 | defer f.Close() 22 | 23 | // create a reader of the text file 24 | r = bufio.NewReader(f) 25 | 26 | // the index of lines 27 | i := 0 28 | 29 | // loop reading lines 30 | for true { 31 | line, err = r.ReadString('\n') 32 | 33 | i ++ 34 | 35 | // control the range 36 | if i < lineNumberT - rangeT { 37 | continue 38 | } 39 | 40 | if i > lineNumberT + rangeT { 41 | break 42 | } 43 | 44 | // if reach the end of file 45 | if err == io.EOF { 46 | break 47 | } 48 | 49 | // output the line number and content 50 | pl("[%v] %v", i, strings.TrimRight(line, "\r\n")) 51 | 52 | // if error occured, terminate the program 53 | checkErrf("failed to read content: %v, line: %v", err, line) 54 | 55 | } -------------------------------------------------------------------------------- /scripts/webServer.gox: -------------------------------------------------------------------------------- 1 | http = net_http 2 | filepath = path_filepath 3 | 4 | portG = ":8080" 5 | sslPortG = ":8443" 6 | 7 | basePathG = `c:\web` 8 | 9 | muxG = nil 10 | 11 | staticFS = nil 12 | 13 | func serveStaticDirHandler(w, r) { 14 | if staticFS == nil { 15 | staticFS = http.FileServer(http.Dir(filepath.Join(basePathG, "pages"))) 16 | } 17 | 18 | old = r.URL.Path 19 | 20 | name = filepath.Join(basePathG, "pages", path.Clean(old)) 21 | 22 | info, err = os.Lstat(name) 23 | if err == nil { 24 | if !info.IsDir() { 25 | staticFS.ServeHTTP(w, r) 26 | } else { 27 | if tk.IfFileExists(filepath.Join(name, "index.html")) { 28 | staticFS.ServeHTTP(w, r) 29 | } else { 30 | http.NotFound(w, r) 31 | } 32 | } 33 | } else { 34 | http.NotFound(w, r) 35 | } 36 | 37 | } 38 | 39 | func startHttpsServer(portA) { 40 | pl("trying to start https server on %v...", portA) 41 | 42 | err = http.ListenAndServeTLS(portA, filepath.Join(basePathG, "server.crt"), filepath.Join(basePathG, "server.key"), muxG) 43 | if err != nil { 44 | pl("failed to start https server: %v", err) 45 | } 46 | 47 | } 48 | 49 | // main code 50 | 51 | muxG = http.NewServeMux() 52 | 53 | muxG.HandleFunc("/", serveStaticDirHandler) 54 | 55 | go startHttpsServer(sslPortG) 56 | 57 | pl("trying to start http server on %v...", portG) 58 | 59 | err = http.ListenAndServe(portG, muxG) 60 | 61 | if err != nil { 62 | pl("failed to start http server: %v", err) 63 | } 64 | 65 | -------------------------------------------------------------------------------- /scripts/webServerCompact.gox: -------------------------------------------------------------------------------- 1 | muxG = net_http.NewServeMux() 2 | 3 | handlerT = newObj("staticHttpHandler", path_filepath.Join(getHomeDir(), "pages")) 4 | 5 | checkErrX(handlerT) 6 | 7 | muxG.HandleFunc("/", handlerT) 8 | 9 | go plErr(net_http.ListenAndServeTLS(":8443", path_filepath.Join(getHomeDir(), "server.crt"), path_filepath.Join(getHomeDir(), "server.key"), muxG)) 10 | 11 | checkErrf("failed to start http server: %v", net_http.ListenAndServe(":8080", muxG)) 12 | 13 | -------------------------------------------------------------------------------- /scripts/webServerStatic.gox: -------------------------------------------------------------------------------- 1 | staticFS = net_http.FileServer(net_http.Dir(path_filepath.Join(`c:\web`, "pages"))) 2 | 3 | func serveStaticDirHandler(w, r) { 4 | name = path_filepath.Join(`c:\web`, "pages", path.Clean(r.URL.Path)) 5 | 6 | info, err = os.Lstat(name) 7 | if err == nil && (!info.IsDir() || tk.IfFileExists(path_filepath.Join(name, "index.html"))) { 8 | staticFS.ServeHTTP(w, r) 9 | } else { 10 | net_http.NotFound(w, r) 11 | } 12 | 13 | } 14 | 15 | muxG = net_http.NewServeMux() 16 | 17 | muxG.HandleFunc("/", serveStaticDirHandler) 18 | 19 | go plerr(net_http.ListenAndServeTLS(":8443", path_filepath.Join(`c:\web`, "server.crt"), path_filepath.Join(`c:\web`, "server.key"), muxG)) 20 | 21 | checkErrf("failed to start http server: %v", net_http.ListenAndServe(":8080", muxG)) 22 | 23 | -------------------------------------------------------------------------------- /scripts/webView.gox: -------------------------------------------------------------------------------- 1 | // 设置github.com/webview/webview包的简称 2 | webView = github_webview_webview 3 | 4 | // 创建一个webView,参数是是否允许debug 5 | w := webView.New(true) 6 | 7 | // 确认退出时关闭webView 8 | defer w.Destroy() 9 | 10 | // 设置webView窗口标题 11 | w.SetTitle("Hello") 12 | 13 | // 设置窗口大小 14 | // hint的取值:HintNone 设定的宽度和高度(前两个参数)是窗口默认大小, 15 | // HintFixed 窗口大小不能变更 16 | // HintMin 设定的宽度和高度(前两个参数)是窗口最小大小 17 | // HintMax 设定的宽度和高度(前两个参数)是窗口最大大小 18 | w.SetSize(400, 300, webView.HintNone) 19 | 20 | // 定义一个准备在JavaScript中调用的函数 21 | func goPr(valueA) { 22 | pl("%v", valueA) 23 | return "", nil 24 | } 25 | 26 | goPrP = newFuncIIE(goPr) 27 | 28 | w.Bind("pr", goPrP) 29 | 30 | func goHex(valueA) { 31 | if !isValid(valueA, "string") { 32 | return "", errf("无效参数,应为一个字符串,收到的类型是%T", valueA) 33 | } 34 | 35 | rs = hexEncode(valueA) 36 | 37 | return rs, nil 38 | } 39 | 40 | goHexP = newFuncIIE(goHex) 41 | 42 | w.Bind("hex", goHexP) 43 | 44 | // func goAdd(valueA) { 45 | // rs = valueA+"a" 46 | 47 | // return rs, errf("abc") 48 | // } 49 | 50 | // goAddP = newFuncSSE(goAdd) 51 | 52 | // w.Bind("add", goAddP) 53 | 54 | func myQuit() { 55 | w.Terminate() 56 | } 57 | 58 | myQuitP = newFunc(myQuit) 59 | w.Bind("quit", myQuitP) 60 | 61 | htmlT = ` 62 | 63 | 64 | 65 | 66 | 67 |
hello
68 |
69 |
70 | 71 | 72 | 73 | 74 | 75 | 97 | 98 | ` 99 | 100 | // htmlT = strReplace(htmlT, "+", "%2B") 101 | 102 | // htmlT = net_url.PathEscape(htmlT) 103 | 104 | plv(htmlT) 105 | 106 | // w.Navigate(`data:text/html;charset=utf-8,` + htmlT) 107 | // w.Navigate(`data:text/html;base64,` + base64Encode([]byte(htmlT))) 108 | 109 | // w.Navigate(`data:text/text,` + htmlT) 110 | // w.Navigate(`data:text/html,` + net_url.QueryEscape(htmlT)) 111 | // w.Navigate(`data:text/html,` + htmlT) 112 | w.Navigate(`data:text/html;charset=UTF-8,` + htmlT) 113 | 114 | // w.Navigate("file:///D:/tmpx/test.html") 115 | // w.Navigate("http://shupei.fltrp.com") 116 | 117 | w.Run() 118 | -------------------------------------------------------------------------------- /scripts/xie1.gox: -------------------------------------------------------------------------------- 1 | scriptT = ` 2 | var a 3 | 4 | assign $a abc 5 | 6 | strAdd $a ||||sdjkfhdk 7 | 132312234 8 | 风扇电机开发的时刻 9 | |||| 10 | 11 | strAdd $a ||||^*^*^*||(&@#)|||| 12 | pass 13 | pln $last 14 | ` 15 | 16 | resultT = runXie(scriptT) 17 | 18 | pln("result:", resultT) -------------------------------------------------------------------------------- /scripts/xml.gox: -------------------------------------------------------------------------------- 1 | etree = github_beevik_etree 2 | 3 | reshapeXMLX = fn(xmlA) { 4 | treeT = etree.NewDocument() 5 | 6 | if treeT == nil { 7 | return tk.GenerateErrorStringF("create XML tree failed") 8 | } 9 | 10 | errT = treeT.ReadFromString(xmlA) 11 | 12 | if errT != nil { 13 | return tk.GenerateErrorStringF("invalid XML: %v", errT) 14 | } 15 | 16 | treeT.Indent(2) 17 | 18 | outputT, errT = treeT.WriteToString() 19 | 20 | if errT != nil { 21 | return tk.GenerateErrorStringF("failed to reshape XML: %v", errT) 22 | } 23 | 24 | return outputT 25 | 26 | } 27 | 28 | flattenXML = fn(xmlA, nodeA) { 29 | treeT = etree.NewDocument() 30 | 31 | if treeT == nil { 32 | return tk.GenerateErrorStringF("create XML tree failed") 33 | } 34 | 35 | errT = treeT.ReadFromString(xmlA) 36 | 37 | if errT != nil { 38 | return tk.GenerateErrorStringF("invalid XML: %v", errT) 39 | } 40 | 41 | rootNodeT = treeT.FindElement("//" + nodeA) 42 | 43 | if rootNodeT == nil { 44 | return tk.GenerateErrorStringF("node not found: %v", nodeA) 45 | } 46 | 47 | nodesT = rootNodeT.ChildElements() 48 | 49 | bufT = new(strings.Builder) 50 | 51 | for i, v = range nodesT { 52 | if i > 0 { 53 | bufT.WriteString("\n") 54 | } 55 | 56 | bufT.WriteString(tk.Spr("%v: %v", v.Tag, v.Text())) 57 | } 58 | 59 | return bufT.String() 60 | 61 | } 62 | 63 | getMSSFromXML = fn(xmlA, nodeA) { 64 | treeT = etree.NewDocument() 65 | 66 | if treeT == nil { 67 | return nil, tk.Errf("create XML tree failed") 68 | } 69 | 70 | errT = treeT.ReadFromString(xmlA) 71 | 72 | if errT != nil { 73 | return nil, tk.Errf("invalid XML: %v", errT) 74 | } 75 | 76 | rootNodeT = treeT.FindElement("//" + nodeA) 77 | 78 | if rootNodeT == nil { 79 | return nil, tk.Errf("node not found: %v", nodeA) 80 | } 81 | 82 | nodesT = rootNodeT.ChildElements() 83 | 84 | mapT = make(map[string]string, len(nodesT)) 85 | for _, jv = range nodesT { 86 | mapT[jv.Tag] = jv.Text() 87 | } 88 | 89 | return mapT, nil 90 | } 91 | 92 | getMSSArrayFromXML = fn(xmlA, nodeA) { 93 | treeT = etree.NewDocument() 94 | 95 | if treeT == nil { 96 | return nil, tk.Errf("create XML tree failed") 97 | } 98 | 99 | errT = treeT.ReadFromString(xmlA) 100 | 101 | if errT != nil { 102 | return nil, tk.Errf("invalid XML: %v", errT) 103 | } 104 | 105 | rootNodeT = treeT.FindElement("//" + nodeA) 106 | 107 | if rootNodeT == nil { 108 | return nil, tk.Errf("node not found: %v", nodeA) 109 | } 110 | 111 | nodesT = rootNodeT.ChildElements() 112 | 113 | aryT = make([]map[string]string, 0) 114 | 115 | for _, v = range nodesT { 116 | internalNodesT = v.ChildElements() 117 | 118 | mapT = make(map[string]string, len(internalNodesT)) 119 | for _, jv = range internalNodesT { 120 | mapT[jv.Tag] = jv.Text() 121 | } 122 | 123 | aryT = append(aryT, mapT) 124 | } 125 | 126 | return aryT, nil 127 | } 128 | 129 | 130 | xmlT = ` 131 | 132 | 133 | 北京大学 134 | 简称:北大 135 | 136 | 137 | 138 | 139 | 140 | ` 141 | 142 | resultT = reshapeXMLX(xmlT) 143 | 144 | println(resultT) 145 | 146 | println("\n-----\n") 147 | 148 | resultT = flattenXML(xmlT, "ZvendorNameFuzquery") 149 | 150 | println(resultT) 151 | 152 | println("\n-----\n") 153 | 154 | resultT, errT = getMSSFromXML(xmlT, "ZvendorNameFuzquery") 155 | 156 | println(resultT, errT) 157 | 158 | println("\n-----\n") 159 | 160 | xmlT = ` 161 | 162 | 163 | 164 | 北京大学 165 | 简称:北大 166 | 167 | 168 | 169 | 170 | 171 | 清华大学 172 | 173 | 地址 174 | 175 | 176 | 177 | 178 | 179 | ` 180 | 181 | resultT = getMSSArrayFromXML(xmlT, "ZvendorNameFuzquery") 182 | 183 | println(resultT) 184 | 185 | -------------------------------------------------------------------------------- /sysspec_nonwindows.go: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | 3 | package gox 4 | 5 | import ( 6 | "github.com/topxeq/qlang" 7 | ) 8 | 9 | func GetSystemMetrics(nIndex int) int { 10 | return 0 11 | } 12 | 13 | func GetScreenResolution() (int, int) { 14 | return 0, 0 15 | } 16 | 17 | func InitSysspec() { 18 | var sysspecExports = map[string]interface{}{ 19 | "GetScreenResolution": GetScreenResolution, 20 | "GetSystemMetrics": GetSystemMetrics, 21 | } 22 | 23 | qlang.Import("sysspec", sysspecExports) 24 | } 25 | -------------------------------------------------------------------------------- /sysspec_windows.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package gox 4 | 5 | import ( 6 | "syscall" 7 | 8 | "github.com/topxeq/qlang" 9 | ) 10 | 11 | var ( 12 | user32 *syscall.LazyDLL 13 | getSystemMetrics *syscall.LazyProc 14 | ) 15 | 16 | const ( 17 | SM_CXSCREEN = 0 18 | SM_CYSCREEN = 1 19 | ) 20 | 21 | func GetSystemMetrics(nIndex int) int { 22 | if user32 == nil { 23 | user32 = syscall.NewLazyDLL("User32.dll") 24 | } 25 | 26 | if getSystemMetrics == nil { 27 | getSystemMetrics = user32.NewProc("GetSystemMetrics") 28 | 29 | } 30 | 31 | index := uintptr(nIndex) 32 | ret, _, _ := getSystemMetrics.Call(index) 33 | return int(ret) 34 | } 35 | 36 | func GetScreenResolution() (int, int) { 37 | return GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN) 38 | } 39 | 40 | func InitSysspec() { 41 | var sysspecExports = map[string]interface{}{ 42 | "GetScreenResolution": GetScreenResolution, 43 | "GetSystemMetrics": GetSystemMetrics, 44 | } 45 | 46 | qlang.Import("sysspec", sysspecExports) 47 | } 48 | -------------------------------------------------------------------------------- /tutorial/anonymfn/anonym.ql: -------------------------------------------------------------------------------- 1 | defer fn { 2 | println("x:", x) 3 | } 4 | 5 | defer fn { 6 | x; x = 2 7 | } 8 | 9 | x = 1 -------------------------------------------------------------------------------- /tutorial/calc/calc.ql: -------------------------------------------------------------------------------- 1 | 2 | grammar = ` 3 | 4 | term = factor *('*' factor/mul | '/' factor/quo | '%' factor/mod) 5 | 6 | doc = term *('+' term/add | '-' term/sub) 7 | 8 | factor = 9 | FLOAT/pushFloat | 10 | '-' factor/neg | 11 | '(' doc ')' | 12 | (IDENT '(' doc %= ','/ARITY ')')/call 13 | ` 14 | 15 | Stack = class { 16 | 17 | fn _init() { 18 | this.stk = [] 19 | } 20 | 21 | fn clear() { 22 | this.stk = this.stk[:0] 23 | } 24 | 25 | fn pop() { 26 | n = len(this.stk) 27 | if n > 0 { 28 | v = this.stk[n-1] 29 | this.stk = this.stk[:n-1] 30 | return v, true 31 | } 32 | return nil, false 33 | } 34 | 35 | fn push(v) { 36 | this.stk = append(this.stk, v) 37 | } 38 | 39 | fn popArgs(arity) { 40 | n = len(this.stk) 41 | if n < arity { 42 | panic("Stack.popArgs: unexpected") 43 | } 44 | args = make([]var, arity) 45 | copy(args, this.stk[n-arity:]) 46 | this.stk = this.stk[:n-arity] 47 | return args 48 | } 49 | } 50 | 51 | Calculator = class { 52 | 53 | fn _init() { 54 | this.stk = new Stack 55 | } 56 | 57 | fn grammar() { 58 | return grammar 59 | } 60 | 61 | fn stack() { 62 | return this.stk 63 | } 64 | 65 | fn fntable() { 66 | return fntable 67 | } 68 | 69 | fn ret() { 70 | v, _ = this.stk.pop() 71 | this.stk.clear() 72 | return v 73 | } 74 | 75 | fn call(name) { 76 | f = fntable[name] 77 | if f == undefined { 78 | panic("function not found: " + name) 79 | } 80 | arity, _ = this.stk.pop() 81 | args = this.stk.popArgs(arity) 82 | ret = f(args...) 83 | this.stk.push(ret) 84 | } 85 | } 86 | 87 | fntable = { 88 | "sin": sin, 89 | "cos": cos, 90 | "pow": pow, 91 | "max": max, 92 | "min": min, 93 | 94 | "$mul": fn(a, b) { return a*b }, 95 | "$quo": fn(a, b) { return a/b }, 96 | "$mod": fn(a, b) { return a%b }, 97 | "$add": fn(a, b) { return a+b }, 98 | "$sub": fn(a, b) { return a-b }, 99 | "$neg": fn(a) { return -a }, 100 | 101 | "$call": Calculator.call, 102 | "$pushFloat": Stack.push, 103 | "$ARITY": Stack.push, 104 | } 105 | -------------------------------------------------------------------------------- /tutorial/calc/main.ql: -------------------------------------------------------------------------------- 1 | include "calc.ql" 2 | 3 | main { // 使用main关键字将主程序括起来,是为了避免其中用的局部变量比如 err 对其他函数造成影响 4 | 5 | calc = new Calculator 6 | engine, err = interpreter(calc, nil) 7 | if err != nil { 8 | fprintln(os.Stderr, err) 9 | return 1 10 | } 11 | 12 | scanner = bufio.NewScanner(os.Stdin) 13 | for scanner.Scan() { 14 | line = strings.Trim(scanner.Text(), " \t\r\n") 15 | if line != "" { 16 | err = engine.Eval(line) 17 | if err != nil { 18 | fprintln(os.Stderr, err) 19 | } else { 20 | printf("> %v\n\n", calc.ret()) 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /tutorial/chan/chan.ql: -------------------------------------------------------------------------------- 1 | ch = make(chan bool, 2) 2 | x = 1 3 | 4 | go fn { 5 | defer ch <- true 6 | println("in goroutine1: x =", x) 7 | x; x++ 8 | } 9 | 10 | go fn { 11 | defer ch <- true 12 | println("in goroutine2: x =", x) 13 | x; x++ 14 | } 15 | 16 | <-ch 17 | <-ch 18 | 19 | // 结果并不一定是3,因为x++没有做到线程安全 20 | // 21 | println("in main routine: x =", x) 22 | printf("chan cap=%d, len=%d\n", cap(ch), len(ch)) 23 | 24 | -------------------------------------------------------------------------------- /tutorial/closure/closure.ql: -------------------------------------------------------------------------------- 1 | 2 | test = fn() { 3 | g = 1 4 | return class { 5 | fn f() { 6 | return g 7 | } 8 | } 9 | } 10 | 11 | main { 12 | Foo = test() 13 | foo = new Foo 14 | g = 2 15 | println("foo.f:", foo.f()) 16 | } 17 | -------------------------------------------------------------------------------- /tutorial/defer/file.ql: -------------------------------------------------------------------------------- 1 | 2 | f, err = os.Open("file.ql") 3 | if err != nil { 4 | fprintln(os.Stderr, err) 5 | return 1 6 | } 7 | defer println("exit!") 8 | defer f.Close() 9 | 10 | b = make([]byte, 8) 11 | n, err = f.Read(b) 12 | if err != nil { 13 | fprintln(os.Stderr, "Read failed:", err) 14 | return 2 15 | } 16 | 17 | println(string(b[:n])) 18 | -------------------------------------------------------------------------------- /tutorial/flowctrl/flowctrl.ql: -------------------------------------------------------------------------------- 1 | weekday = "Friday" 2 | 3 | switch weekday { 4 | case "Monday": 5 | v = 1 6 | case "Tuesday": 7 | v = 2 8 | case "Wednesday": 9 | v = 3 10 | case "Thursday": 11 | v = 4 12 | case "Friday": 13 | v = 5 14 | case "Saterday": 15 | v = 6 16 | case "Sunday": 17 | v = 7 18 | default: 19 | v = 0 20 | } 21 | println(weekday, "=>", v) 22 | 23 | a = 3 24 | b = 7 25 | if a < b { 26 | min = a 27 | } else { 28 | min = b 29 | } 30 | println("min", a, b, ":", min) 31 | 32 | -------------------------------------------------------------------------------- /tutorial/for_range/for_range.ql: -------------------------------------------------------------------------------- 1 | 2 | sumi = 0 3 | sumv = 0 4 | 5 | for i, v = range [10, 20, 30, 40, 50, 60, 70, 80, 90] { 6 | sumi += i 7 | sumv += v 8 | if i == 4 { 9 | break 10 | } 11 | } 12 | 13 | println("sumi:", sumi, "sumv:", sumv) 14 | 15 | -------------------------------------------------------------------------------- /tutorial/goroutine/goroutine.ql: -------------------------------------------------------------------------------- 1 | 2 | runtime.GOMAXPROCS(8) 3 | 4 | wg = sync.NewWaitGroup() 5 | wg.Add(2) 6 | 7 | x = 1 8 | 9 | go fn { 10 | defer wg.Done() 11 | println("in goroutine1: x =", x) 12 | x++ 13 | } 14 | 15 | go fn { 16 | defer wg.Done() 17 | println("in goroutine2: x =", x) 18 | x++ 19 | } 20 | 21 | wg.Wait() 22 | 23 | // 结果并不一定是3,因为x++没有做到线程安全 24 | // 25 | println("in main routine: x =", x) 26 | -------------------------------------------------------------------------------- /tutorial/http/httpserver.ql: -------------------------------------------------------------------------------- 1 | mux = http.NewServeMux() 2 | mux.Handle("/404", http.NotFoundHandler()) 3 | mux.HandleFunc("/", fn(w, req) { 4 | fprintln(w, "host:", req.Host, "path:", req.URL) 5 | }) 6 | 7 | err = http.ListenAndServe(":8888", mux) 8 | if err != nil { 9 | fprintln(os.Stderr, err) 10 | } 11 | -------------------------------------------------------------------------------- /tutorial/if/if.ql: -------------------------------------------------------------------------------- 1 | 2 | today = 6 3 | 4 | if today == 1 { 5 | today = "Mon" 6 | } elif today == 2 { 7 | today = "Tue" 8 | } elif today == 3 { 9 | today = "Wed" 10 | } 11 | 12 | println(today) 13 | -------------------------------------------------------------------------------- /tutorial/include/a/foo.ql: -------------------------------------------------------------------------------- 1 | foo = fn(a) { 2 | println("in func foo:", a, b) 3 | } 4 | 5 | -------------------------------------------------------------------------------- /tutorial/include/a/main.ql: -------------------------------------------------------------------------------- 1 | 2 | println("in script A") 3 | 4 | a = 1 5 | b = 2 6 | 7 | include "foo.ql" 8 | 9 | export b, foo 10 | 11 | -------------------------------------------------------------------------------- /tutorial/include/b.ql: -------------------------------------------------------------------------------- 1 | include "a" 2 | 3 | println("in script B:", a, b) 4 | foo(3) 5 | 6 | include "bar.ql" 7 | bar() 8 | 9 | -------------------------------------------------------------------------------- /tutorial/include/bar.ql: -------------------------------------------------------------------------------- 1 | bar = fn() { 2 | println("in func bar:", a, b) 3 | } 4 | 5 | -------------------------------------------------------------------------------- /tutorial/include/run.sh: -------------------------------------------------------------------------------- 1 | qlang b.ql 2 | 3 | -------------------------------------------------------------------------------- /tutorial/maxprime/maxprime.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | primes = [2, 3] 4 | n = 1 5 | limit = 9 6 | 7 | def isPrime(v): 8 | i = 0 9 | while i < n: 10 | if v % primes[i] == 0: 11 | return False 12 | i += 1 13 | return True 14 | 15 | def listPrimes(max): 16 | global n, limit 17 | v = 5 18 | while True: 19 | while v < limit: 20 | if isPrime(v): 21 | primes.append(v) 22 | if v * v >= max: 23 | return 24 | v += 2 25 | v += 2 26 | n += 1 27 | limit = primes[n] * primes[n] 28 | 29 | def maxPrimeOf(max): 30 | global n 31 | if max % 2 == 0: 32 | max -= 1 33 | listPrimes(max) 34 | n = len(primes) 35 | while True: 36 | if isPrime(max): 37 | return max 38 | max -= 2 39 | 40 | if len(sys.argv) < 2: 41 | print 'Usage: maxprime ' 42 | sys.exit(1) 43 | 44 | max = int(sys.argv[1]) 45 | if max < 8: 46 | sys.exit(2) 47 | 48 | max -= 1 49 | v = maxPrimeOf(max) 50 | print v 51 | 52 | -------------------------------------------------------------------------------- /tutorial/maxprime/maxprime.ql: -------------------------------------------------------------------------------- 1 | 2 | primes = [2, 3] 3 | n = 1 4 | limit = 9 5 | 6 | isPrime = fn(v) { 7 | for i = 0; i < n; i++ { 8 | if v % primes[i] == 0 { 9 | return false 10 | } 11 | } 12 | return true 13 | } 14 | 15 | listPrimes = fn(max) { 16 | 17 | v = 5 18 | for { 19 | for v < limit { 20 | if isPrime(v) { 21 | primes = append(primes, v) 22 | if v * v >= max { 23 | return 24 | } 25 | } 26 | v += 2 27 | } 28 | v += 2 29 | n; n++ 30 | limit = primes[n] * primes[n] 31 | } 32 | } 33 | 34 | maxPrimeOf = fn(max) { 35 | 36 | if max % 2 == 0 { 37 | max-- 38 | } 39 | 40 | listPrimes(max) 41 | n; n = len(primes) 42 | 43 | for { 44 | if isPrime(max) { 45 | return max 46 | } 47 | max -= 2 48 | } 49 | } 50 | 51 | // Usage: maxprime 52 | // 53 | if len(os.Args) < 2 { 54 | fprintln(os.Stderr, "Usage: maxprime ") 55 | return 56 | } 57 | 58 | max, err = strconv.ParseInt(os.Args[1], 10, 64) 59 | if err != nil { 60 | fprintln(os.Stderr, err) 61 | return 1 62 | } 63 | if max < 8 { // <8 的情况下,可直接建表,答案略 64 | return 65 | } 66 | 67 | max-- 68 | v = maxPrimeOf(max) 69 | println(v) 70 | -------------------------------------------------------------------------------- /tutorial/module/c.ql: -------------------------------------------------------------------------------- 1 | import "internal/a" 2 | import "internal/a" as g 3 | 4 | b = 3 5 | 6 | g.b = 4 7 | println("in script C:", a.b, g.b) 8 | a.foo(b) 9 | 10 | println("\nnow, we will panic") 11 | println(a.a) // 因为 module a 并没有导出变量 a 12 | -------------------------------------------------------------------------------- /tutorial/module/internal/a/foo.ql: -------------------------------------------------------------------------------- 1 | foo = fn(a) { 2 | println("in func foo:", a, b) 3 | } 4 | -------------------------------------------------------------------------------- /tutorial/module/internal/a/main.ql: -------------------------------------------------------------------------------- 1 | 2 | println("in script A") 3 | 4 | a = 1 5 | b = 2 6 | 7 | include "foo.ql" 8 | 9 | export b, foo 10 | 11 | -------------------------------------------------------------------------------- /tutorial/module/run.sh: -------------------------------------------------------------------------------- 1 | QLANG_PATH=`pwd` qlang c.ql 2 | 3 | -------------------------------------------------------------------------------- /tutorial/qlang/main.ql: -------------------------------------------------------------------------------- 1 | include "qlang.ql" 2 | 3 | main { // 使用main关键字将主程序括起来,是为了避免其中用的局部变量比如 err 对其他函数造成影响 4 | 5 | ipt = new Interpreter 6 | 7 | if len(os.Args) > 1 { 8 | engine, err = interpreter(ipt, insertSemis) 9 | if err != nil { 10 | fprintln(os.Stderr, err) 11 | return 1 12 | } 13 | fname = os.Args[1] 14 | b, err = ioutil.ReadFile(fname) 15 | if err != nil { 16 | fprintln(os.Stderr, err) 17 | return 2 18 | } 19 | err = engine.Exec(b, fname) 20 | if err != nil { 21 | fprintln(os.Stderr, err) 22 | return 3 23 | } 24 | return 25 | } 26 | 27 | engine, err = interpreter(ipt, nil) 28 | if err != nil { 29 | fprintln(os.Stderr, err) 30 | return 1 31 | } 32 | 33 | scanner = bufio.NewScanner(os.Stdin) 34 | for scanner.Scan() { 35 | line = strings.Trim(scanner.Text(), " \t\r\n") 36 | if line != "" { 37 | err = engine.Eval(line) 38 | if err != nil { 39 | fprintln(os.Stderr, err) 40 | } else { 41 | printf("> %v\n\n", ipt.ret()) 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tutorial/shell/shell.ql: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env qlang 2 | 3 | println("Command Line:", os.Args) 4 | -------------------------------------------------------------------------------- /tutorial/sync/sync.ql: -------------------------------------------------------------------------------- 1 | mutex = sync.NewMutex() 2 | 3 | n = 10 4 | x = 1 5 | 6 | wg = sync.NewWaitGroup() 7 | wg.Add(n) 8 | 9 | for i = 0; i < n; i++ { 10 | go fn { 11 | defer wg.Done() 12 | 13 | mutex.Lock() 14 | defer mutex.Unlock() 15 | x; x++ 16 | } 17 | } 18 | 19 | wg.Wait() 20 | 21 | println("x:", x) 22 | -------------------------------------------------------------------------------- /tutorial/terminal/calc.ql: -------------------------------------------------------------------------------- 1 | include "../calc/calc.ql" 2 | 3 | main { // 使用main关键字将主程序括起来,是为了避免其中用的局部变量比如 err 对其他函数造成影响 4 | 5 | calc = new Calculator 6 | engine, err = interpreter(calc, nil) 7 | if err != nil { 8 | fprintln(os.Stderr, err) 9 | return 1 10 | } 11 | 12 | historyFile = os.Getenv("HOME") + "/.qcalc.history" 13 | term = terminal.New(">>> ", "... ", nil) 14 | term.LoadHistroy(historyFile) 15 | defer term.SaveHistroy(historyFile) 16 | 17 | println(`Q-Calculator - http://qlang.io, version 1.0.00 18 | Copyright (C) 2015 Qiniu.com - Shanghai Qiniu Information Technologies Co., Ltd. 19 | Use Ctrl-D (i.e. EOF) to exit. 20 | `) 21 | 22 | for { 23 | expr, err = term.Scan() 24 | if err != nil { 25 | if err == terminal.ErrPromptAborted { 26 | continue 27 | } elif err == io.EOF { 28 | println("^D") 29 | break 30 | } 31 | fprintln(os.Stderr, err) 32 | continue 33 | } 34 | expr = strings.TrimSpace(expr) 35 | if expr == "" { 36 | continue 37 | } 38 | err = engine.Eval(expr) 39 | if err != nil { 40 | fprintln(os.Stderr, err) 41 | } else { 42 | println(calc.ret()) 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tutorial/terminal/qlang.ql: -------------------------------------------------------------------------------- 1 | include "../qlang/qlang.ql" 2 | 3 | main { // 使用main关键字将主程序括起来,是为了避免其中用的局部变量比如 err 对其他函数造成影响 4 | 5 | ipt = new Interpreter 6 | engine, err = interpreter(ipt, nil) 7 | if err != nil { 8 | fprintln(os.Stderr, err) 9 | return 1 10 | } 11 | 12 | historyFile = os.Getenv("HOME") + "/.qlang.history" 13 | term = terminal.New(">>> ", "... ", nil) 14 | term.LoadHistroy(historyFile) 15 | defer term.SaveHistroy(historyFile) 16 | 17 | println(`Q-language - http://qlang.io, version 1.0.00 18 | Copyright (C) 2015 Qiniu.com - Shanghai Qiniu Information Technologies Co., Ltd. 19 | Use Ctrl-D (i.e. EOF) to exit. 20 | `) 21 | 22 | for { 23 | expr, err = term.Scan() 24 | if err != nil { 25 | if err == terminal.ErrPromptAborted { 26 | continue 27 | } elif err == io.EOF { 28 | println("^D") 29 | break 30 | } 31 | fprintln(os.Stderr, err) 32 | continue 33 | } 34 | expr = strings.TrimSpace(expr) 35 | if expr == "" { 36 | continue 37 | } 38 | err = engine.Eval(expr) 39 | if err != nil { 40 | fprintln(os.Stderr, err) 41 | } else { 42 | println(ipt.ret()) 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /webview2_nonwindows.go: -------------------------------------------------------------------------------- 1 | //go:build !windows 2 | // +build !windows 3 | 4 | package gox 5 | 6 | func newWebView2(optsA ...string) interface{} { 7 | return nil 8 | } 9 | -------------------------------------------------------------------------------- /webview2_windows.go: -------------------------------------------------------------------------------- 1 | //go:build windows 2 | // +build windows 3 | 4 | package gox 5 | 6 | import ( 7 | "github.com/jchv/go-webview2" 8 | tk "github.com/topxeq/tkc" 9 | ) 10 | 11 | func newWebView2(optsA ...string) interface{} { 12 | if ServerModeG { 13 | return nil 14 | } 15 | 16 | titleT := tk.GetSwitch(optsA, "-title=", "Gox "+VersionG) 17 | widthT := uint(tk.ToInt(tk.GetSwitch(optsA, "-width=", "800"), 800)) 18 | heightT := uint(tk.ToInt(tk.GetSwitch(optsA, "-height=", "600"), 600)) 19 | iconT := uint(tk.ToInt(tk.GetSwitch(optsA, "-icon=", "2"), 2)) 20 | centerT := tk.IfSwitchExistsWhole(optsA, "-center") 21 | debugT := tk.IfSwitchExistsWhole(optsA, "-debug") 22 | 23 | w := webview2.NewWithOptions(webview2.WebViewOptions{ 24 | Debug: debugT, 25 | AutoFocus: true, 26 | WindowOptions: webview2.WindowOptions{ 27 | Title: titleT, 28 | Width: widthT, 29 | Height: heightT, 30 | IconId: iconT, // icon resource id 31 | Center: centerT, 32 | }, 33 | }) 34 | 35 | return w 36 | } 37 | --------------------------------------------------------------------------------