how to properly json serialzie/deserialize DateTime?

2023-09-05 Thread aiac
when i try to json ser/deser DateTime, i get the compile error:


/root/.local/share/rtx/installs/nim/2.0.0/lib/pure/json.nim(1253, 23) 
Error: type mismatch
Expression: initFromJson(dst.zonedTimeFromTimeImpl,
 getOrDefault(jsonNode, "zonedTimeFromTimeImpl"), jsonPath)
  [1] dst.zonedTimeFromTimeImpl: proc (x: Time): ZonedTime{.closure, 
gcsafe.}
  [2] getOrDefault(jsonNode, "zonedTimeFromTimeImpl"): JsonNode
  [3] jsonPath: string

and my code:

```nim
import std/times
import std/json
import std/jsonutils

proc toJsonHook(dt: DateTime, opt = initToJsonOptions()): JsonNode =
  return newJString $dt

proc fromJsonHook(dt: var DateTime, jsonNode: JsonNode) =
  dt = parse($jsonNode, "-MM-dd'T'HH:mm:sszzz", utc())

let dt = now().utc
let jn = dt.toJson
var jnn = parseJson($jn)
let dtt = jnn.to(DateTime)
echo dtt
```


how to properly json serialzie/deserialize DateTime?

2023-09-05 Thread aiac
it works nice, thanks ;-)


Does seq have a method to get mutable ref element?

2023-09-09 Thread aiac
thanks ;-)


Does seq have a method to get mutable ref element?

2023-09-09 Thread aiac
> How to implement this in nim


import sequtils
import sugar

var list = @[1,2,3]

var found = list.filterIt ( it==2 )
var foundPtr = addr found[0]

foundPtr.* = 3

echo list # expected: [1,3,3]


Run


Does seq have a method to get mutable ref element?

2023-09-09 Thread aiac
thanks ;-)


how to compare rune with char?

2023-09-13 Thread aiac
`import std/unicode let str = “你好/hi” for c in str.runes(): case c: of '/': # 
compile error here, since c is type of distinct RuneImpl echo " '/' found" 
break `

Run


how to compare rune with char ?

2023-09-13 Thread aiac
`import std/unicode let str = “你好:hi” for c in str.runes(): case c: of `

Run


how to compare rune with char

2023-09-13 Thread aiac
thanks a lot ;-)

There is always a problem with the code snippet render. I have to use pictures, 
and then it becomes normal again.


how to compare rune with char

2023-09-13 Thread aiac

import std/unicode

let str = “你好/hi”

for c in str.runes():
  case c:
of '/':  # compile error here, since c is type of distinct RuneImpl
 echo " '/' found"
 break


Run


how to static linking sqlite ?

2023-09-26 Thread aiac
  * error info








Run

  * my Dockerfile




FROM nimlang/nim:2.0.0-alpine as builder

WORKDIR /project

RUN apk add --update --no-cache --force-overwrite sqlite-dev sqlite-static

COPY . .

RUN nimble build -d:beast -d:release --mm:refc -d:nimDebugDlOpen 
--passL:-static --verbose -y



FROM alpine:latest

WORKDIR /app

COPY --from=builder --chmod=777 /project/test_happyx ./bin/
COPY --from=builder /project/fighter.db ./

EXPOSE 5000/tcp

ENTRYPOINT ["./bin/test_happyx"]


Run


how to static linking sqlite ?

2023-09-26 Thread aiac
I don’t know why, but the forum’s markdown editor keeps eating my text.

error info here when start container :


Dynamic loading not supported
Dynamic loading not supported
could not load: libsqlite3.so(|.0)


Run


how to static linking sqlite ?

2023-09-26 Thread aiac
Thanks a lot, it seems helpful for compiling sqlite3.a.

In my case, we have already got it by 


 add sqlite-static

Run

so I found that I just need to modify it like the following and it will work 
well

> 
> RUN nimble build -d:beast -d:release --mm:refc -d:nimDebugDlOpen 
> --dynlibOverride:sqlite3 --passL:/usr/lib/libsqlite3.a --passL:-static 
> --verbose -y
> 
> 
> Run


how to pass --cc options to compiler by nimble?

2023-09-28 Thread aiac
  * command




nimble build --verbose --mm:refc -d:beast -d:release \
  --cc:clang --clang.exe:zigcc --clang.linkerexe:zigcc \
  --passC="--target x86_64-linux-musl" --passL="--target x86_64-linux-musl"


Run

  * error info




Error: arguments can only be given if the '--run' option is selected
nimble.nim(229)  buildFromDir


Run


how to pass --cc options to compiler by nimble?

2023-09-28 Thread aiac
thanks ;-)


how to pass --cc options to compiler by nimble?

2023-09-28 Thread aiac
Thanks, it works great 😊

nimble provides useless error messages btw 🤣


how to pass --cc options to compiler by nimble?

2023-09-28 Thread aiac
Thanks, it works great 😊

nimble provides useless error messages btw 🤣


undeclared identifier error when using string format in template

2023-12-12 Thread aiac
`import std/[strformat,strutils] import std/[enumutils] template 
printEnumMembers(E: typedesc[enum]) = for i in E.items: echo "[$1]: $2 -> ord: 
$3, $$: $4" % [$(i.symbolRank), $(i.symbolName), $(i.ord), $i] # it works # it 
failed with undeclared identifie 'i' # echo fmt"{i.symbolRank}: {i.symbolName} 
-> ord: {i.ord}, $: {i}" type Color = enum red, green, blue printEnumMembers 
Color `

Run


undeclared identifier error when using string format in template

2023-12-12 Thread aiac
thanks ;)


SIGSEGV: Illegal storage access. (Attempt to read from nil?) in coroutines

2023-12-15 Thread aiac
  * code:




import std/[strformat]
  import std/[os]
  import std/[times,monotimes]
  import std/[coro]
  
  
  var fibers: seq[CoroutineRef] = @[]
  
  proc doSleep() = sleep 3000
  
  let st = getMonoTime()
  
  for i in 0..<10:
fibers.add start(doSleep)
  
  for i in fibers.items:
i.wait
  
  let ed = getMonoTime()
  
  echo fmt"elapsed: {(ed-st).inMilliseconds}ms"



Run

  * error:




SIGSEGV: Illegal storage access. (Attempt to read from nil?)
Segmentation fault


Run


What is the difference between std/atomics and threading/atomics, which one is recommended?

2023-12-15 Thread aiac
as title


error occurred when add thread to seq

2023-12-16 Thread aiac
  * code:




import std/[strformat]
  import std/[os]
  import std/typedthreads
  import std/[monotimes, times]
  
  var threads: seq[Thread[void]] = @[]
  
  let st = getMonoTime()
  
  proc doSleep() =
sleep 3000
  
  for i in 0 ..< 10:
var t: Thread[void]
createThread(t, doSleep)
threads.add t
  
  for t in threads.items:
t.joinThread
  
  let ed = getMonoTime()
  
  echo fmt"elapsed: {(ed-st).inMilliseconds}ms"



Run

  * error:




Error: '=dup' is not available for type , which is infe
rred from unavailable '=copy'; requires a copy because it's not the last 
read of 't'; routine: thread



Run


error occurred when add thread to seq

2023-12-16 Thread aiac
My guess is that the Thread object is allocated on the stack, but does not 
support copy, which means that its lifetime cannot be safely expanded.


error occurred when add thread to seq

2023-12-16 Thread aiac
Thank you for your suggestion, but I want to know why the standard library 
stuff is not recommended to be used directly?


error occurred when add thread to seq

2023-12-16 Thread aiac
If the number of thread instances required is unknown, how can we define it in 
a global variable?


SIGSEGV: Illegal storage access. (Attempt to read from nil?) in coroutines

2023-12-21 Thread aiac
**UPDATE** :


import std/[strformat,strutils]
  import std/[os,cmdline]
  import std/[times,monotimes]
  import std/[coro]
  
  
  let fiberCount = try: paramStr(1).parseInt except: 1024
  
  echo fmt"{fiberCount = }"
  
  var fibers: seq[CoroutineRef] = @[]
  
  proc doSleep() = suspend 3.0
  
  let st = getMonoTime()
  
  for i in 0..

SIGSEGV: Illegal storage access. (Attempt to read from nil?) in coroutines

2023-12-21 Thread aiac
I think CoroutineRef is a ref object that can be moved instead of Thread object 
and Coroutine should have nothing to do with OS


SIGSEGV: Illegal storage access. (Attempt to read from nil?) in coroutines

2023-12-22 Thread aiac



specify lib dir by `--passL` can not work

2023-12-30 Thread aiac



specify lib dir by `--passL` can not work

2023-12-30 Thread aiac
Trying them under gitbash are also failed

> > 


specify lib dir by `--passL` can not work

2023-12-30 Thread aiac
it also failed


  zzz@zzz MINGW64 /e/code/me/test-nim
  $ ls libcry*
  libcrypto-1_1-x64.dll*
  
  zzz@zzz MINGW64 /e/code/me/test-nim
  $ nim c -d:release -d:ssl --clibdir:/e/scoop/global/apps/nim/current/bin 
./imgur.nim  Hint: used config file 
'E:\scoop\global\apps\nim\current\config\nim.cfg' [Conf]
  Hint: used config file 
'E:\scoop\global\apps\nim\current\config\config.nims' [Conf]
  

  Hint:  [Link]
  Hint: mm: orc; threads: on; opt: speed; options: -d:release
  75953 lines; 1.087s; 135.027MiB peakmem; proj: 
E:\code\me\test-nim\imgur.nim; out: E:\code\me\test-nim\imgur.exe [SuccessX]
  
  zzz@zzz MINGW64 /e/code/me/test-nim
  $ ./imgur.exe
  could not load: (libssl-1_1-x64|ssleay64|libssl64).dll



Run


specify lib dir by `--passL` can not work

2023-12-30 Thread aiac
Is there an example of nim static link ssl on windows?


specify lib dir by `--passL` can not work

2023-12-31 Thread aiac
> In the end, it's still failed, okay, I give up ;-)

> 
>  ╭╴🪟 $psh code\me\test-nim via 👑 v2.0.2
> ╰─❯ ls *.lib
> 
> Directory: E:\code\me\test-nim
> 
> Mode LastWriteTime Length Name
>  - -- 
> -a---   2023/3/1410:42   37865790 libcrypto_static.lib
> -a---   2023/3/1410:425767070 libssl_static.lib
> 
> ╭╴🪟 $psh code\me\test-nim via 👑 v2.0.2
> ╰─❯ rm .\imgur.exe
> ╭╴🪟 $psh code\me\test-nim via 👑 v2.0.2
> ╰─❯ rm .\imgur.pdb
> ╭╴🪟 $psh code\me\test-nim via 👑 v2.0.2
> ╰─❯
> ╭╴🪟 $psh code\me\test-nim via 👑 v2.0.2
> ╰─❯ ls *.lib
> 
> Directory: E:\code\me\test-nim
> 
> Mode LastWriteTime Length Name
>  - -- 
> -a---   2023/3/1410:42   37865790 libcrypto_static.lib
> -a---   2023/3/1410:425767070 libssl_static.lib
> 
> ╭╴🪟 $psh code\me\test-nim via 👑 v2.0.2
> ╰─❯ nim c -d:release -d:ssl -d:useOpenssl3 --cc:clang 
> --clang.exe:"zigcc.cmd" --clang.linkerexe:"zigcc.cmd" --passC:"-target 
> x86_64-windows-msvc" --passL:"-target x86_64-windows-msvc" 
> --dynlibOverride:ssl --dynlibOverride:crypto  --passL:-static --passL:-L. 
> --passL:libcrypto_static.lib --passL:libssl_static.lib  .\imgur.nim
> Hint: used config file 'E:\scoop\global\apps\nim\current\config\nim.cfg' 
> [Conf]
> Hint: used config file 
> 'E:\scoop\global\apps\nim\current\config\config.nims' [Conf]
> 
> 
> Hint:  [Link]
> 
> E:\code\me\test-nim# zig cc -o E:\code\me\test-nim\imgur.exe  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@ssys...@sexceptions.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sstd@spriv...@sdigitsutils.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@s...@sassertions.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@ssys...@sdollars.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@s...@swidestrs.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@s...@sexitprocs.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@s...@ssyncio.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@s...@ssystem.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@sparseutils.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@sunicode.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@smath.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@salgorithm.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@sstrutils.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@sstrformat.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sstd@spriv...@sntpath.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@spathnorm.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@sdynlib.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@swind...@swinlean.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@s...@soserrors.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@stimes.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sstd@spriv...@soscommon.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sstd@spriv...@sospaths2.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sstd@sprivate@swin_setenv.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@s...@senvvars.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@s...@scmdline.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@sos.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur_r\@m..@s..@s..@sscoop@sglobal@sapps@snim@scurrent@slib@sp...@snativesockets.nim.c.o
>  
> C:\Users\zzz\nimcache\imgur

specify lib dir by `--passL` can not work

2023-12-31 Thread aiac
I give up the static link. Now use Enigma Virtual Box to pack EXE and DLLS into 
a single file


Is there a more elegant approach

2023-12-31 Thread aiac

type PageNo = 1 .. 100

var a: PageNo = 1

a = if a == PageNo.low(): a  else:  (a - 1)
a = if a == PageNo.low(): a  else:  (a - 1)

echo a
 

Run


why object variants not support same field name ?

2024-01-02 Thread aiac

type CommandId = enum
  cmdSearch
  cmdDownload

type Command = object
  case id: CommandId
  of cmdSearch:
opts: SearchOpts
  of cmdDownload:
opts: DownloadOpts # Error: attempt to redefine: 'v'



Run


Maybe nappgui is best cross platform gui lib for nim

2024-01-02 Thread aiac
Rust egui is very easy to use. Hope nim also has a similar ;-)


how to get pragma of the field in macro?

2024-01-04 Thread aiac

template opt() {.pragma.}

type A = object
  name {.opt.}: string
  age: int

var a = A(name: "foo", age: 10)

# expect like below:
#
# case k
# of "name":
#   a.name = "🤔"
# else:
#   discard
#
# but result is:
#
# case k
# else:
#   discard
macro parse(a: typed; k: untyped): untyped =
  result = nnkCaseStmt.newTree(k)
  for fieldDef in a.getTypeImpl()[2]:
# unexpected: why fieldDef[0].kind is nnkSym ?
# how to get pragma of the field
if fieldDef[0].kind == nnkPragmaExpr and 
fieldDef[0][1][0].eqIdent("opt"):
  let fieldNameIdent = fieldDef[0][0]
  result.add nnkOfBranch.newTree(
  newLit(fieldNameIdent.strVal),
  nnkStmtList.newTree(
nnkAsgn.newTree(nnkDotExpr.newTree(a, fieldNameIdent), 
newLit("🤔"))
  ),
)
  result.add nnkElse.newTree(
  nnkStmtList.newTree(nnkDiscardStmt.newTree(newEmptyNode()))
)

let k = "name"
expandMacros:
  parse a, k
 

Run


how to get pragma of the field in macro?

2024-01-04 Thread aiac
Thanks for your advice ;-)

i modified code and got error as below:


macro parse(a: typed; k: untyped): untyped =
  result = nnkCaseStmt.newTree(k)
  for fieldDef in a.getTypeImpl()[2]:
let fieldNameIdent = fieldDef[0][0]
# error: Expected one of {nnkSym, nnkType, nnkBracketExpr, nnkDotExpr, 
nnkCheckedFieldExpr, nnkTypeOfExpr}, got nnkCall
if nnkDotExpr.newTree(a, fieldNameIdent).hasCustomPragma(opt):
  result.add nnkOfBranch.newTree(
  newLit(fieldNameIdent.strVal),
  nnkStmtList.newTree(
nnkAsgn.newTree(nnkDotExpr.newTree(a, fieldNameIdent), 
newLit("🤔"))
  ),
)
  result.add nnkElse.newTree(
  nnkStmtList.newTree(nnkDiscardStmt.newTree(newEmptyNode()))
)
 

Run


how to get pragma of the field in macro?

2024-01-04 Thread aiac
i found `getTypeImpl` can not get pragma info ;-(

> 
> static:
>   echo A.getTypeImpl().treeRepr()
>  
> 
> Run

result is:


ObjectTy
  Empty
  Empty
  RecList
IdentDefs
  Sym "name"
  Sym "string"
  Empty
IdentDefs
  Sym "age"
  Sym "int"
  Empty
 

Run


how to get pragma of the field in macro?

2024-01-04 Thread aiac
i try to use `fieldPairs()`, but unfortunately


macro parse(a: typed; k: untyped): untyped =
  result = nnkCaseStmt.newTree(k)
  for fk, fv in a.fieldPairs():
when fv.hasCustomPragma(opt):
  result.add nnkOfBranch.newTree(
  newLit(fk), nnkStmtList.newTree(nnkAsgn.newTree(fv, newLit("🤔")))
)
  result.add nnkElse.newTree(
  nnkStmtList.newTree(nnkDiscardStmt.newTree(newEmptyNode()))
)
 

Run

> 
> Expression: fieldPairs(a)
>   [1] a: NimNode
> 
> Expected one of (first mismatch at [position]):
> [1] iterator fieldPairs[S: tuple | object; T: tuple | object](x: S; y: 
> T): tuple[
> key: string, a, b: RootObj]
> [1] iterator fieldPairs[T: tuple | object](x: T): tuple[key: string, val: 
> RootObj]
>  
>  
> 
> Run


how to get pragma of the field in macro?

2024-01-04 Thread aiac
I don’t understand the role of `getTypeImpl`, it even can not get the type name 
(e.g. A)


how to get pragma of the field in macro?

2024-01-04 Thread aiac
thanks a lot ;-)


`nph` opinionated formatter v0.3

2024-01-04 Thread aiac
> Error: Unsatisfied dependency: nim (2.0.0)

👑 v2.0.2


fixme: the proc parameters always use Copy by default?

2024-01-06 Thread aiac
code:

> 
> proc f(t: seq[string]) =
>   echo "f:", cast[int](t.addr)
> 
> proc fv(t: var seq[string]) =
>   echo "fv:", cast[int](t.addr)
> 
> var t = @["foo", "bar"]
> echo "t:", cast[int](t.addr)
> 
> f t
> fv t
>  
>  
> 
> Run

  * result



> 
> t: 94578224415136
> f:14072456944
> fv:94578224415136
>  
> 
> Run


 Since non-var parameters cannot be modified the compiler is always free to
pass arguments by reference if it considers it can speed up execution.


Run

But I saw this sentence from Nim Manual, which made me a little puzzled 🤔


fixme: the proc parameters always use Copy by default?

2024-01-06 Thread aiac
  * code




type P = object
  x, y: int

proc f(a: P) =
  echo "f:", cast[int](a.addr)

var a = P(x: 1, y: 2)

echo "a: ", cast[int](a.addr)

f a
 

Run

  * result




a: 93922143641920
f:140728652581696


Run

for non-pointer types are also different memory addresses 🤔


fixme: the proc parameters always use Copy by default?

2024-01-07 Thread aiac
thanks ;-)


seq vs ref seq

2024-01-15 Thread aiac
what are the benefits of `seq` compared to `ref seq` , and what other scenarios 
are `ref seq` that cannot replace `seq`


how to define a zero capacity HashSet with let ?

2024-01-22 Thread aiac
we can define a zero cap HashSet by var


var a: HashSet[string]


Run

but how to do same thing by let?


how to define a zero capacity HashSet with let ?

2024-01-22 Thread aiac
It's cap seems to be 4


how to define a zero capacity HashSet with let ?

2024-01-22 Thread aiac
Seems it can work


let a = HashSet[string]()


Run


undeclared identifier: 'HashSet' error occured in macro

2024-01-22 Thread aiac
Error: undeclared identifier: 'HashSet'


nnkIdentDefs.newTree(
  newIdentNode("__tags"),
  newEmptyNode(),
  nnkCall.newTree(
nnkBracketExpr.newTree(newIdentNode("HashSet"), 
newIdentNode("string"))
  ),
)


Run

Confirm that Import std/sets


how to genernate ast from a input string?

2024-01-23 Thread aiac
for example:


let s = """it == "foo
let nimNode = genAst(s)


Run


how to use parseExpr in runtime ?

2024-01-23 Thread aiac
example run on compile time:


static:
  let expr = """it == "foo
  let n = parseExpr(expr)


Run


how to use parseExpr in runtime ?

2024-01-23 Thread aiac
thanks ;-)


howt to embed NimNode in template?

2024-01-23 Thread aiac

template foo() =
  let v = "foo"
  let n = nnkInfix.newTree(
 newIdentNode("=="),
 newIdentNode("v"),
 newLit("foo")
  )
  if n:   # here how to embed?
   echo "bingo"


Run


howt to embed NimNode in template?

2024-01-23 Thread aiac
Very useful and thank you ;-)


how to use parseExpr in runtime ?

2024-01-23 Thread aiac
Thank you very much, I will read it carefully ;-)


macro pragma: param's default value not support?

2024-01-23 Thread aiac

macro foo(tag: static string = "", p: untyped): untyped =
  result = p

proc bar() {.foo.} =## Error: invalid pragma: foo
  discard


Run


macro pragma: param's default value not support?

2024-01-24 Thread aiac
the post not allow edit

UPDATE HERE:

> 
> macro foo(tag: static string = "", p: untyped): untyped =
>   result = p
> 
> proc bar() {.foo.} =## Error: invalid pragma: foo
>   discard
> 
> proc bar() {.foo: "".} =## this works
>   discard
> 
> 
> Run


Is `concept` similar to `interface` / `trait`?

2024-01-25 Thread aiac
Are there any libraries using `concept` ?


Is `concept` similar to `interface` / `trait`?

2024-01-25 Thread aiac
If there is a translator for transforming an odd way of speaking into normal 
answers , it can be great


Is `concept` similar to `interface` / `trait`?

2024-01-26 Thread aiac
thanks


how to get lower/upper bound of Slice

2024-01-26 Thread aiac

proc getLowerBound(x: Slice[int]): int =
  x.low # ? but error


Run


How to determine whether Import expected packages?

2024-01-26 Thread aiac
For library, how to determine user code whether has imported expected packages


# user code
import std/re

# lib code
when import("std/re"):
  echo "std/re was imported"


Run


How to determine whether Import expected packages?

2024-01-26 Thread aiac
should be somethings like `Class.forName("xxx")` in Java or add features in 
Rust ?


How to determine whether Import expected packages?

2024-01-26 Thread aiac
i want to that lib import std/re and use std/re functions only when user code 
import std/re


Is `concept` similar to `interface` / `trait`?

2024-01-26 Thread aiac
Very useful, thank you ;-)


How to determine whether Import expected packages?

2024-01-26 Thread aiac
Thank you for your explanation ;-)


how to borrow iterator `items` for distinct type?

2024-04-29 Thread aiac

type A = distinct array[4, uint8]

let a: A = cast[A]([uint8 0, 0, 1, 1])

iterator items(a: A): uint8 {.borrow.}

for b in a:
  echo b



Run


/root/.local/share/mise/installs/nim/2.0.2/lib/system/iterators.nim(35, 10) 
Error: internal error: proc has no result symbol
No stack traceback available
To create a stacktrace, rerun compilation with './koch temp r ', see 
https://nim-lang.github.io/Nim/intern.html#debugging-the-compiler for details


Run


is there a good way to get unix timestamp in nim script?

2024-08-01 Thread aiac
AFAK nim script cannot use std/times, so is there a good way


is there a good way to get unix timestamp in nim script?

2024-08-01 Thread aiac
` proc unixTimeMs(): int = when defined(windows): let cmd = """powershell 
-nologo -noprofile -command 
"[DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() else: let cmd = """sh -c 
"echo $(date +%s)000 let (output, code) = gorgeEx(cmd) if code == 0: return 
output.strip().parseInt else: raise newException(OSError, "Failed to get unix 
time: " & output) `

Run


is there a good way to get unix timestamp in nim script?

2024-08-01 Thread aiac
` proc unixTimeMs(): int = when defined(windows): let cmd = """powershell 
-nologo -noprofile -command 
"[DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() else: let cmd = """sh -c 
"echo $(date +%s)000 let (output, code) = gorgeEx(cmd) if code == 0: return 
output.strip().parseInt else: raise newException(OSError, "Failed to get unix 
time: " & output) `

Run


Is there a way to write to stdout without newline in nim script?

2024-08-01 Thread aiac
I found that i cannot use stdout.write(can not find stdout symbol) in nim 
script, so is there a way...?


What's wrong with my code?

2024-08-12 Thread aiac

  proc sendResponse(req: Request, resp: AsyncResponse) {.async.} =
# send status line
discard await req.client.send("HTTP/1.1 " & $resp.code() & "\c\L")
# send headers
discard await req.sendHeaders(resp.headers)
discard await req.client.send("\c\L")
# send body
while true:
  let (hasData, data) = await resp.bodyStream.read()
  if not hasData:
break
  else:
discard await req.client.send(data)


Run

and get error:


 Error: expression '
template yieldFuture() {.redefine.} =
  yield FutureBase()

var internalTmpFuture`gensym16: FutureBase = send(req.client,
"HTTP/1.1 " & $code(resp) & "\r\n", {SafeDisconn})
yield internalTmpFuture`gensym16
read(cast[typeof(send(req.client, "HTTP/1.1 " & $code(resp) & "\r\n",
  {SafeDisconn}))](internalTmpFuture`gensym16))' has no 
type (o
r is ambiguous)



Run


can we use `method` to replace `httpMethod` and `reqMethod`?

2024-08-14 Thread aiac
I forgot about this, it should be that I hardly use OOP in Nim 😯