Change stdlib imports to use std prefix in most examples (#17202)

This commit is contained in:
Danil Yarantsev 2021-03-01 00:17:19 +03:00 • committed by GitHub
commit 56461c280f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
45 changed files with 127 additions and 127 deletions

View file

@ -29,7 +29,7 @@ To install SDL2 you can use ``nimble install sdl2``.
import sdl2 import sdl2
#*** import the hotcodereloading stdlib module *** #*** import the hotcodereloading stdlib module ***
import hotcodereloading import std/hotcodereloading
var runGame*: bool = true var runGame*: bool = true
var window: WindowPtr var window: WindowPtr

View file

@ -5941,7 +5941,7 @@ imported:
:test: "nim c $1" :test: "nim c $1"
:status: 1 :status: 1
import strutils except `%`, toUpperAscii import std/strutils except `%`, toUpperAscii
# doesn't work then: # doesn't work then:
echo "$1" % "abc".toUpperAscii echo "$1" % "abc".toUpperAscii
@ -5984,7 +5984,7 @@ Module names in imports
A module alias can be introduced via the ``as`` keyword: A module alias can be introduced via the ``as`` keyword:
.. code-block:: nim .. code-block:: nim
import strutils as su, sequtils as qu import std/strutils as su, std/sequtils as qu
echo su.format("$1", "lalelu") echo su.format("$1", "lalelu")
@ -6048,7 +6048,7 @@ full qualification:
.. code-block:: nim .. code-block:: nim
:test: "nim c $1" :test: "nim c $1"
from strutils import `%` from std/strutils import `%`
echo "$1" % "abc" echo "$1" % "abc"
# always possible: full qualification: # always possible: full qualification:

View file

@ -29,7 +29,7 @@ the passed expression on the thread pool and returns a `data flow variable`:idx:
variables at the same time: variables at the same time:
.. code-block:: nim .. code-block:: nim
import threadpool, ... import std/threadpool, ...
# wait until 2 out of 3 servers received the update: # wait until 2 out of 3 servers received the update:
proc main = proc main =
@ -56,7 +56,7 @@ Example:
.. code-block:: nim .. code-block:: nim
# Compute PI in an inefficient way # Compute PI in an inefficient way
import strutils, math, threadpool import std/[strutils, math, threadpool]
proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1) proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1)

View file

@ -1459,7 +1459,7 @@ macro expandMacros*(body: typed): untyped =
## For instance, ## For instance,
## ##
## .. code-block:: nim ## .. code-block:: nim
## import sugar, macros ## import std/[sugar, macros]
## ##
## let ## let
## x = 10 ## x = 10
@ -1657,7 +1657,7 @@ proc extractDocCommentsAndRunnables*(n: NimNode): NimNode =
## Example: ## Example:
## ##
## .. code-block:: nim ## .. code-block:: nim
## import macros ## import std/macros
## macro transf(a): untyped = ## macro transf(a): untyped =
## result = quote do: ## result = quote do:
## proc fun2*() = discard ## proc fun2*() = discard

View file

@ -31,7 +31,7 @@
## ---------------------------------- ## ----------------------------------
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import db_mysql ## import std/db_mysql
## let db = open("localhost", "user", "password", "dbname") ## let db = open("localhost", "user", "password", "dbname")
## db.close() ## db.close()
## ##
@ -56,7 +56,7 @@
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## ##
## import db_mysql, math ## import std/[db_mysql, math]
## ##
## let theDb = open("localhost", "nim", "nim", "test") ## let theDb = open("localhost", "nim", "nim", "test")
## ##

View file

@ -37,7 +37,7 @@
## ---------------------------------- ## ----------------------------------
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import db_odbc ## import std/db_odbc
## var db = open("localhost", "user", "password", "dbname") ## var db = open("localhost", "user", "password", "dbname")
## db.close() ## db.close()
## ##
@ -62,7 +62,7 @@
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## ##
## import db_odbc, math ## import std/[db_odbc, math]
## ##
## var theDb = open("localhost", "nim", "nim", "test") ## var theDb = open("localhost", "nim", "nim", "test")
## ##

View file

@ -47,7 +47,7 @@
## To use Unix sockets with `db_postgres`, change the server address to the socket file path: ## To use Unix sockets with `db_postgres`, change the server address to the socket file path:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path ## import std/db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path
## let db = db_postgres.open("/run/postgresql", "user", "password", "database") ## let db = db_postgres.open("/run/postgresql", "user", "password", "database")
## echo db.getAllRows(sql"SELECT version();") ## echo db.getAllRows(sql"SELECT version();")
## db.close() ## db.close()
@ -64,7 +64,7 @@
## ---------------------------------- ## ----------------------------------
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import db_postgres ## import std/db_postgres
## let db = open("localhost", "user", "password", "dbname") ## let db = open("localhost", "user", "password", "dbname")
## db.close() ## db.close()
## ##

View file

@ -35,7 +35,7 @@
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## ##
## import db_sqlite ## import std/db_sqlite
## ##
## # user, password, database name can be empty. ## # user, password, database name can be empty.
## # These params are not used on db_sqlite module. ## # These params are not used on db_sqlite module.
@ -66,7 +66,7 @@
## ##
## .. code-block:: nim ## .. code-block:: nim
## ##
## import db_sqlite, math ## import std/[db_sqlite, math]
## ##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
@ -99,7 +99,7 @@
## ##
## .. code-block:: nim ## .. code-block:: nim
## ##
## import random ## import std/random
## ##
## ## Generate random float datas ## ## Generate random float datas
## var orig = newSeq[float64](150) ## var orig = newSeq[float64](150)

View file

@ -26,7 +26,7 @@ when defined(js):
## ##
## .. code-block:: nim ## .. code-block:: nim
## ##
## import nre except toSeq ## import std/nre except toSeq
## ##
## ##
## Licencing ## Licencing

View file

@ -274,7 +274,7 @@ proc match*(s: string, pattern: Regex, matches: var openArray[string],
## returned. ## returned.
## ##
runnableExamples: runnableExamples:
import sequtils import std/sequtils
var matches: array[2, string] var matches: array[2, string]
if match("abcdefg", re"c(d)ef(g)", matches, 2): if match("abcdefg", re"c(d)ef(g)", matches, 2):
doAssert toSeq(matches) == @["d", "g"] doAssert toSeq(matches) == @["d", "g"]
@ -494,7 +494,7 @@ iterator split*(s: string, sep: Regex; maxsplit = -1): string =
## Substrings are separated by the regular expression `sep` ## Substrings are separated by the regular expression `sep`
## (and the portion matched by `sep` is not returned). ## (and the portion matched by `sep` is not returned).
runnableExamples: runnableExamples:
import sequtils import std/sequtils
doAssert toSeq(split("00232this02939is39an22example111", re"\d+")) == doAssert toSeq(split("00232this02939is39an22example111", re"\d+")) ==
@["", "this", "is", "an", "example", ""] @["", "this", "is", "an", "example", ""]
var last = 0 var last = 0

View file

@ -1089,7 +1089,7 @@ template onSignal*(signals: varargs[cint], body: untyped) =
## Example: ## Example:
## ##
## .. code-block:: ## .. code-block::
## from posix import SIGINT, SIGTERM, onSignal ## from std/posix import SIGINT, SIGTERM, onSignal
## onSignal(SIGINT, SIGTERM): ## onSignal(SIGINT, SIGTERM):
## echo "bye from signal ", sig ## echo "bye from signal ", sig

View file

@ -117,7 +117,7 @@ proc osReleaseFile*(): Config {.since: (1, 5).} =
## `os-release` file is not available on Windows and OS X by design. ## `os-release` file is not available on Windows and OS X by design.
## * https://www.freedesktop.org/software/systemd/man/os-release.html ## * https://www.freedesktop.org/software/systemd/man/os-release.html
runnableExamples: runnableExamples:
import parsecfg import std/parsecfg
when defined(linux): when defined(linux):
let data = osReleaseFile() let data = osReleaseFile()
echo "OS name: ", data.getSectionValue("", "NAME") ## the data is up to each distro. echo "OS name: ", data.getSectionValue("", "NAME") ## the data is up to each distro.

View file

@ -10,7 +10,7 @@
## This module implements asynchronous file reading and writing. ## This module implements asynchronous file reading and writing.
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import asyncfile, asyncdispatch, os ## import std/[asyncfile, asyncdispatch, os]
## ##
## proc main() {.async.} = ## proc main() {.async.} =
## var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite) ## var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite)

View file

@ -22,7 +22,7 @@
## connect to an FTP server. You can do so with the `connect` procedure. ## connect to an FTP server. You can do so with the `connect` procedure.
## ##
## .. code-block::nim ## .. code-block::nim
## import asyncdispatch, asyncftpclient ## import std/[asyncdispatch, asyncftpclient]
## proc main() {.async.} = ## proc main() {.async.} =
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test") ## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
## await ftp.connect() ## await ftp.connect()
@ -42,7 +42,7 @@
## instead specify an absolute path. ## instead specify an absolute path.
## ##
## .. code-block::nim ## .. code-block::nim
## import asyncdispatch, asyncftpclient ## import std/[asyncdispatch, asyncftpclient]
## proc main() {.async.} = ## proc main() {.async.} =
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test") ## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
## await ftp.connect() ## await ftp.connect()
@ -63,7 +63,7 @@
## `progressInterval` milliseconds. ## `progressInterval` milliseconds.
## ##
## .. code-block::nim ## .. code-block::nim
## import asyncdispatch, asyncftpclient ## import std/[asyncdispatch, asyncftpclient]
## ##
## proc onProgressChanged(total, progress: BiggestInt, ## proc onProgressChanged(total, progress: BiggestInt,
## speed: float) {.async.} = ## speed: float) {.async.} =

View file

@ -19,7 +19,7 @@ runnableExamples:
# respond to all requests with a `200 OK` response code and "Hello World" # respond to all requests with a `200 OK` response code and "Hello World"
# as the response body. Run locally with: # as the response body. Run locally with:
# `nim doc --doccmd:-d:nimAsyncHttpServerEnableTest --lib:lib lib/pure/asynchttpserver.nim` # `nim doc --doccmd:-d:nimAsyncHttpServerEnableTest --lib:lib lib/pure/asynchttpserver.nim`
import asyncdispatch import std/asyncdispatch
if defined(nimAsyncHttpServerEnableTest): if defined(nimAsyncHttpServerEnableTest):
proc main {.async.} = proc main {.async.} =
const port = 8080 const port = 8080
@ -78,9 +78,9 @@ func getSocket*(a: AsyncHttpServer): AsyncSocket {.since: (1, 5, 1).} =
## Useful for identifying what port the AsyncHttpServer is bound to, if it ## Useful for identifying what port the AsyncHttpServer is bound to, if it
## was chosen automatically. ## was chosen automatically.
runnableExamples: runnableExamples:
from asyncdispatch import Port from std/asyncdispatch import Port
from asyncnet import getFd from std/asyncnet import getFd
from nativesockets import getLocalAddr, AF_INET from std/nativesockets import getLocalAddr, AF_INET
let server = newAsyncHttpServer() let server = newAsyncHttpServer()
server.listen(Port(0)) # Socket is not bound until this point server.listen(Port(0)) # Socket is not bound until this point
let port = getLocalAddr(server.getSocket.getFd, AF_INET)[1] let port = getLocalAddr(server.getSocket.getFd, AF_INET)[1]
@ -113,7 +113,7 @@ proc respond*(req: Request, code: HttpCode, content: string,
## Example: ## Example:
## ##
## .. code-block::nim ## .. code-block::nim
## import json ## import std/json
## proc handler(req: Request) {.async.} = ## proc handler(req: Request) {.async.} =
## if req.url.path == "/hello-world": ## if req.url.path == "/hello-world":
## let msg = %* {"message": "Hello World"} ## let msg = %* {"message": "Hello World"}

View file

@ -67,7 +67,7 @@
## ##
## .. code-block::nim ## .. code-block::nim
## ##
## import asyncnet, asyncdispatch ## import std/[asyncnet, asyncdispatch]
## ##
## var clients {.threadvar.}: seq[AsyncSocket] ## var clients {.threadvar.}: seq[AsyncSocket]
## ##

View file

@ -24,14 +24,14 @@
## ------------- ## -------------
## ##
## .. code-block::nim ## .. code-block::nim
## import base64 ## import std/base64
## let encoded = encode("Hello World") ## let encoded = encode("Hello World")
## assert encoded == "SGVsbG8gV29ybGQ=" ## assert encoded == "SGVsbG8gV29ybGQ="
## ##
## Apart from strings you can also encode lists of integers or characters: ## Apart from strings you can also encode lists of integers or characters:
## ##
## .. code-block::nim ## .. code-block::nim
## import base64 ## import std/base64
## let encodedInts = encode([1,2,3]) ## let encodedInts = encode([1,2,3])
## assert encodedInts == "AQID" ## assert encodedInts == "AQID"
## let encodedChars = encode(['h','e','y']) ## let encodedChars = encode(['h','e','y'])
@ -42,7 +42,7 @@
## ------------- ## -------------
## ##
## .. code-block::nim ## .. code-block::nim
## import base64 ## import std/base64
## let decoded = decode("SGVsbG8gV29ybGQ=") ## let decoded = decode("SGVsbG8gV29ybGQ=")
## assert decoded == "Hello World" ## assert decoded == "Hello World"
## ##
@ -50,7 +50,7 @@
## --------------- ## ---------------
## ##
## .. code-block::nim ## .. code-block::nim
## import base64 ## import std/base64
## doAssert encode("c\xf7>", safe = true) == "Y_c-" ## doAssert encode("c\xf7>", safe = true) == "Y_c-"
## doAssert encode("c\xf7>", safe = false) == "Y/c+" ## doAssert encode("c\xf7>", safe = false) == "Y/c+"
## ##

View file

@ -11,7 +11,7 @@
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## ##
## import strtabs, cgi ## import std/[strtabs, cgi]
## ##
## # Fill the values when debugging: ## # Fill the values when debugging:
## when debug: ## when debug:

View file

@ -13,7 +13,7 @@
## (A crit bit tree is a form of `radix tree`:idx: or `patricia trie`:idx:.) ## (A crit bit tree is a form of `radix tree`:idx: or `patricia trie`:idx:.)
runnableExamples: runnableExamples:
from sequtils import toSeq from std/sequtils import toSeq
var critbitAsSet: CritBitTree[void] = ["kitten", "puppy"].toCritBitTree var critbitAsSet: CritBitTree[void] = ["kitten", "puppy"].toCritBitTree
doAssert critbitAsSet.len == 2 doAssert critbitAsSet.len == 2
@ -335,7 +335,7 @@ iterator leaves[T](n: Node[T]): Node[T] =
iterator keys*[T](c: CritBitTree[T]): string = iterator keys*[T](c: CritBitTree[T]): string =
## Yields all keys in lexicographical order. ## Yields all keys in lexicographical order.
runnableExamples: runnableExamples:
from sequtils import toSeq from std/sequtils import toSeq
let c = {"key1": 1, "key2": 2}.toCritBitTree let c = {"key1": 1, "key2": 2}.toCritBitTree
doAssert toSeq(c.keys) == @["key1", "key2"] doAssert toSeq(c.keys) == @["key1", "key2"]
@ -349,7 +349,7 @@ iterator values*[T](c: CritBitTree[T]): T =
## **See also:** ## **See also:**
## * `mvalues iterator <#mvalues.i,CritBitTree[T]>`_ ## * `mvalues iterator <#mvalues.i,CritBitTree[T]>`_
runnableExamples: runnableExamples:
from sequtils import toSeq from std/sequtils import toSeq
let c = {"key1": 1, "key2": 2}.toCritBitTree let c = {"key1": 1, "key2": 2}.toCritBitTree
doAssert toSeq(c.values) == @[1, 2] doAssert toSeq(c.values) == @[1, 2]
@ -375,7 +375,7 @@ iterator pairs*[T](c: CritBitTree[T]): tuple[key: string, val: T] =
## **See also:** ## **See also:**
## * `mpairs iterator <#mpairs.i,CritBitTree[T]>`_ ## * `mpairs iterator <#mpairs.i,CritBitTree[T]>`_
runnableExamples: runnableExamples:
from sequtils import toSeq from std/sequtils import toSeq
let c = {"key1": 1, "key2": 2}.toCritBitTree let c = {"key1": 1, "key2": 2}.toCritBitTree
doAssert toSeq(c.pairs) == @[(key: "key1", val: 1), (key: "key2", val: 2)] doAssert toSeq(c.pairs) == @[(key: "key1", val: 1), (key: "key2", val: 2)]
@ -407,7 +407,7 @@ proc allprefixedAux[T](c: CritBitTree[T], key: string): Node[T] =
iterator keysWithPrefix*[T](c: CritBitTree[T], prefix: string): string = iterator keysWithPrefix*[T](c: CritBitTree[T], prefix: string): string =
## Yields all keys starting with `prefix`. ## Yields all keys starting with `prefix`.
runnableExamples: runnableExamples:
from sequtils import toSeq from std/sequtils import toSeq
let c = {"key1": 42, "key2": 43}.toCritBitTree let c = {"key1": 42, "key2": 43}.toCritBitTree
doAssert toSeq(c.keysWithPrefix("key")) == @["key1", "key2"] doAssert toSeq(c.keysWithPrefix("key")) == @["key1", "key2"]
@ -422,7 +422,7 @@ iterator valuesWithPrefix*[T](c: CritBitTree[T], prefix: string): T =
## **See also:** ## **See also:**
## * `mvaluesWithPrefix iterator <#mvaluesWithPrefix.i,CritBitTree[T],string>`_ ## * `mvaluesWithPrefix iterator <#mvaluesWithPrefix.i,CritBitTree[T],string>`_
runnableExamples: runnableExamples:
from sequtils import toSeq from std/sequtils import toSeq
let c = {"key1": 42, "key2": 43}.toCritBitTree let c = {"key1": 42, "key2": 43}.toCritBitTree
doAssert toSeq(c.valuesWithPrefix("key")) == @[42, 43] doAssert toSeq(c.valuesWithPrefix("key")) == @[42, 43]
@ -451,7 +451,7 @@ iterator pairsWithPrefix*[T](c: CritBitTree[T],
## **See also:** ## **See also:**
## * `mpairsWithPrefix iterator <#mpairsWithPrefix.i,CritBitTree[T],string>`_ ## * `mpairsWithPrefix iterator <#mpairsWithPrefix.i,CritBitTree[T],string>`_
runnableExamples: runnableExamples:
from sequtils import toSeq from std/sequtils import toSeq
let c = {"key1": 42, "key2": 43}.toCritBitTree let c = {"key1": 42, "key2": 43}.toCritBitTree
doAssert toSeq(c.pairsWithPrefix("key")) == @[(key: "key1", val: 42), (key: "key2", val: 43)] doAssert toSeq(c.pairsWithPrefix("key")) == @[(key: "key1", val: 42), (key: "key2", val: 43)]

View file

@ -200,7 +200,7 @@ iterator items*[T](deq: Deque[T]): T =
## **See also:** ## **See also:**
## * `mitems iterator <#mitems,Deque[T]>`_ ## * `mitems iterator <#mitems,Deque[T]>`_
runnableExamples: runnableExamples:
from sequtils import toSeq from std/sequtils import toSeq
let a = [10, 20, 30, 40, 50].toDeque let a = [10, 20, 30, 40, 50].toDeque
assert toSeq(a.items) == @[10, 20, 30, 40, 50] assert toSeq(a.items) == @[10, 20, 30, 40, 50]
@ -230,7 +230,7 @@ iterator mitems*[T](deq: var Deque[T]): var T =
iterator pairs*[T](deq: Deque[T]): tuple[key: int, val: T] = iterator pairs*[T](deq: Deque[T]): tuple[key: int, val: T] =
## Yields every `(position, value)`-pair of `deq`. ## Yields every `(position, value)`-pair of `deq`.
runnableExamples: runnableExamples:
from sequtils import toSeq from std/sequtils import toSeq
let a = [10, 20, 30].toDeque let a = [10, 20, 30].toDeque
assert toSeq(a.pairs) == @[(0, 10), (1, 20), (2, 30)] assert toSeq(a.pairs) == @[(0, 10), (1, 20), (2, 30)]

View file

@ -165,7 +165,7 @@ proc newSinglyLinkedNode*[T](value: T): <//>(SinglyLinkedNode[T]) =
func toSinglyLinkedList*[T](elems: openArray[T]): SinglyLinkedList[T] {.since: (1, 5, 1).} = func toSinglyLinkedList*[T](elems: openArray[T]): SinglyLinkedList[T] {.since: (1, 5, 1).} =
## Creates a new `SinglyLinkedList` from members of `elems`. ## Creates a new `SinglyLinkedList` from members of `elems`.
runnableExamples: runnableExamples:
import sequtils import std/sequtils
let a = [1, 2, 3, 4, 5].toSinglyLinkedList let a = [1, 2, 3, 4, 5].toSinglyLinkedList
assert a.toSeq == [1, 2, 3, 4, 5] assert a.toSeq == [1, 2, 3, 4, 5]
result = initSinglyLinkedList[T]() result = initSinglyLinkedList[T]()
@ -175,7 +175,7 @@ func toSinglyLinkedList*[T](elems: openArray[T]): SinglyLinkedList[T] {.since: (
func toDoublyLinkedList*[T](elems: openArray[T]): DoublyLinkedList[T] {.since: (1, 5, 1).} = func toDoublyLinkedList*[T](elems: openArray[T]): DoublyLinkedList[T] {.since: (1, 5, 1).} =
## Creates a new `DoublyLinkedList` from members of `elems`. ## Creates a new `DoublyLinkedList` from members of `elems`.
runnableExamples: runnableExamples:
import sequtils import std/sequtils
let a = [1, 2, 3, 4, 5].toDoublyLinkedList let a = [1, 2, 3, 4, 5].toDoublyLinkedList
assert a.toSeq == [1, 2, 3, 4, 5] assert a.toSeq == [1, 2, 3, 4, 5]
result = initDoublyLinkedList[T]() result = initDoublyLinkedList[T]()
@ -359,7 +359,7 @@ proc prepend*[T: SomeLinkedList](a: var T, b: T) {.since: (1, 5, 1).} =
## * `prependMoved proc <#prependMoved,DoublyLinkedList[T],DoublyLinkedList[T]>`_ ## * `prependMoved proc <#prependMoved,DoublyLinkedList[T],DoublyLinkedList[T]>`_
## for moving the second list instead of copying ## for moving the second list instead of copying
runnableExamples: runnableExamples:
import sequtils import std/sequtils
var a = [4, 5].toSinglyLinkedList var a = [4, 5].toSinglyLinkedList
let b = [1, 2, 3].toSinglyLinkedList let b = [1, 2, 3].toSinglyLinkedList
a.prepend b a.prepend b
@ -476,7 +476,7 @@ proc prepend*[T](L: var SinglyLinkedList[T], value: T) {.inline.} =
func copy*[T](a: SinglyLinkedList[T]): SinglyLinkedList[T] {.since: (1, 5, 1).} = func copy*[T](a: SinglyLinkedList[T]): SinglyLinkedList[T] {.since: (1, 5, 1).} =
## Creates a shallow copy of `a`. ## Creates a shallow copy of `a`.
runnableExamples: runnableExamples:
import sequtils import std/sequtils
type Foo = ref object type Foo = ref object
x: int x: int
var var
@ -675,7 +675,7 @@ proc add*[T: SomeLinkedList](a: var T, b: T) {.since: (1, 5, 1).} =
## * `addMoved proc <#addMoved,DoublyLinkedList[T],DoublyLinkedList[T]>`_ ## * `addMoved proc <#addMoved,DoublyLinkedList[T],DoublyLinkedList[T]>`_
## for moving the second list instead of copying ## for moving the second list instead of copying
runnableExamples: runnableExamples:
import sequtils import std/sequtils
var a = [1, 2, 3].toSinglyLinkedList var a = [1, 2, 3].toSinglyLinkedList
let b = [4, 5].toSinglyLinkedList let b = [4, 5].toSinglyLinkedList
a.add b a.add b

View file

@ -39,7 +39,7 @@
## `method call syntax<manual.html#procedures-method-call-syntax>`_. ## `method call syntax<manual.html#procedures-method-call-syntax>`_.
runnableExamples: runnableExamples:
import sugar import std/sugar
# Creating a sequence from 1 to 10, multiplying each member by 2, # Creating a sequence from 1 to 10, multiplying each member by 2,
# keeping only the members which are not divisible by 6. # keeping only the members which are not divisible by 6.
@ -62,7 +62,7 @@ runnableExamples:
runnableExamples: runnableExamples:
from strutils import join from std/strutils import join
let let
vowels = @"aeiou" vowels = @"aeiou"

View file

@ -774,7 +774,7 @@ iterator allValues*[A, B](t: Table[A, B]; key: A): B {.deprecated:
## `add proc<#add,Table[A,B],A,sinkB>`_). ## `add proc<#add,Table[A,B],A,sinkB>`_).
## ##
runnableExamples: runnableExamples:
import sequtils, algorithm import std/[sequtils, algorithm]
var a = {'a': 3, 'b': 5}.toTable var a = {'a': 3, 'b': 5}.toTable
for i in 1..3: a.add('z', 10*i) for i in 1..3: a.add('z', 10*i)

View file

@ -24,7 +24,7 @@
## ##
## .. code-block::nim ## .. code-block::nim
## ##
## import dynlib ## import std/dynlib
## ##
## type ## type
## greetFunction = proc(): cstring {.gcsafe, stdcall.} ## greetFunction = proc(): cstring {.gcsafe, stdcall.}

View file

@ -32,11 +32,11 @@
## .. code-block:: Nim ## .. code-block:: Nim
## :test: ## :test:
## ##
## import htmlparser ## import std/htmlparser
## import xmltree # To use '$' for XmlNode ## import std/xmltree # To use '$' for XmlNode
## import strtabs # To access XmlAttributes ## import std/strtabs # To access XmlAttributes
## import os # To use splitFile ## import std/os # To use splitFile
## import strutils # To use cmpIgnoreCase ## import std/strutils # To use cmpIgnoreCase
## ##
## proc transformHyperlinks() = ## proc transformHyperlinks() =
## let html = loadHtml("input.html") ## let html = loadHtml("input.html")
@ -365,7 +365,7 @@ proc htmlTag*(s: string): HtmlTag =
proc runeToEntity*(rune: Rune): string = proc runeToEntity*(rune: Rune): string =
## converts a Rune to its numeric HTML entity equivalent. ## converts a Rune to its numeric HTML entity equivalent.
runnableExamples: runnableExamples:
import unicode import std/unicode
doAssert runeToEntity(Rune(0)) == "" doAssert runeToEntity(Rune(0)) == ""
doAssert runeToEntity(Rune(-1)) == "" doAssert runeToEntity(Rune(-1)) == ""
doAssert runeToEntity("Ü".runeAt(0)) == "#220" doAssert runeToEntity("Ü".runeAt(0)) == "#220"
@ -378,7 +378,7 @@ proc entityToRune*(entity: string): Rune =
## or `&#x000DC;` to its UTF-8 equivalent. ## or `&#x000DC;` to its UTF-8 equivalent.
## Rune(0) is returned if the entity name is unknown. ## Rune(0) is returned if the entity name is unknown.
runnableExamples: runnableExamples:
import unicode import std/unicode
doAssert entityToRune("") == Rune(0) doAssert entityToRune("") == Rune(0)
doAssert entityToRune("a") == Rune(0) doAssert entityToRune("a") == Rune(0)
doAssert entityToRune("gt") == ">".runeAt(0) doAssert entityToRune("gt") == ">".runeAt(0)

View file

@ -17,7 +17,7 @@
## `http://google.com`: ## `http://google.com`:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import httpclient ## import std/httpclient
## var client = newHttpClient() ## var client = newHttpClient()
## echo client.getContent("http://google.com") ## echo client.getContent("http://google.com")
## ##
@ -25,7 +25,7 @@
## `AsyncHttpClient`: ## `AsyncHttpClient`:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import asyncdispatch, httpclient ## import std/[asyncdispatch, httpclient]
## ##
## proc asyncProc(): Future[string] {.async.} = ## proc asyncProc(): Future[string] {.async.} =
## var client = newAsyncHttpClient() ## var client = newAsyncHttpClient()
@ -74,7 +74,7 @@
## and uses a json object for the body ## and uses a json object for the body
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import httpclient, json ## import std/[httpclient, json]
## ##
## let client = newHttpClient() ## let client = newHttpClient()
## client.headers = newHttpHeaders({ "Content-Type": "application/json" }) ## client.headers = newHttpHeaders({ "Content-Type": "application/json" })
@ -92,7 +92,7 @@
## progress of the HTTP request. ## progress of the HTTP request.
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import asyncdispatch, httpclient ## import std/[asyncdispatch, httpclient]
## ##
## proc onProgressChanged(total, progress, speed: BiggestInt) {.async.} = ## proc onProgressChanged(total, progress, speed: BiggestInt) {.async.} =
## echo("Downloaded ", progress, " of ", total) ## echo("Downloaded ", progress, " of ", total)
@ -149,7 +149,7 @@
## Here is how to set a timeout when creating an `HttpClient` instance: ## Here is how to set a timeout when creating an `HttpClient` instance:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import httpclient ## import std/httpclient
## ##
## let client = newHttpClient(timeout = 42) ## let client = newHttpClient(timeout = 42)
## ##
@ -163,7 +163,7 @@
## Some examples on how to configure a Proxy for `HttpClient`: ## Some examples on how to configure a Proxy for `HttpClient`:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import httpclient ## import std/httpclient
## ##
## let myProxy = newProxy("http://myproxy.network") ## let myProxy = newProxy("http://myproxy.network")
## let client = newHttpClient(proxy = myProxy) ## let client = newHttpClient(proxy = myProxy)
@ -171,7 +171,7 @@
## Get Proxy URL from environment variables: ## Get Proxy URL from environment variables:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import httpclient ## import std/httpclient
## ##
## var url = "" ## var url = ""
## try: ## try:
@ -195,7 +195,7 @@
## Here you can see an example about how to set the `maxRedirects` of `HttpClient`: ## Here you can see an example about how to set the `maxRedirects` of `HttpClient`:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import httpclient ## import std/httpclient
## ##
## let client = newHttpClient(maxRedirects = 0) ## let client = newHttpClient(maxRedirects = 0)
## ##
@ -573,7 +573,7 @@ proc newHttpClient*(userAgent = defUserAgent, maxRedirects = 5,
## ##
## `headers` specifies the HTTP Headers. ## `headers` specifies the HTTP Headers.
runnableExamples: runnableExamples:
import asyncdispatch, httpclient, strutils import std/[asyncdispatch, httpclient, strutils]
proc asyncProc(): Future[string] {.async.} = proc asyncProc(): Future[string] {.async.} =
var client = newAsyncHttpClient() var client = newAsyncHttpClient()

View file

@ -34,7 +34,7 @@
## the ``[]`` operator. The following example shows how to do this: ## the ``[]`` operator. The following example shows how to do this:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import json ## import std/json
## ##
## let jsonNode = parseJson("""{"key": 3.14}""") ## let jsonNode = parseJson("""{"key": 3.14}""")
## ##
@ -55,7 +55,7 @@
## To retrieve the value of ``"key"`` you can do the following: ## To retrieve the value of ``"key"`` you can do the following:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import json ## import std/json
## ##
## let jsonNode = parseJson("""{"key": 3.14}""") ## let jsonNode = parseJson("""{"key": 3.14}""")
## ##
@ -72,7 +72,7 @@
## type's default value when called on ``nil``. ## type's default value when called on ``nil``.
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import json ## import std/json
## ##
## let jsonNode = parseJson("{}") ## let jsonNode = parseJson("{}")
## ##
@ -88,7 +88,7 @@
## you to fallback to a default value should the key's values be ``null``: ## you to fallback to a default value should the key's values be ``null``:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import json ## import std/json
## ##
## let jsonNode = parseJson("""{"key": 3.14, "key2": null}""") ## let jsonNode = parseJson("""{"key": 3.14, "key2": null}""")
## ##
@ -106,8 +106,8 @@
## responses, and backticks around keys with a reserved keyword as name. ## responses, and backticks around keys with a reserved keyword as name.
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import json ## import std/json
## import options ## import std/options
## ##
## type ## type
## User = object ## User = object
@ -127,7 +127,7 @@
## operator: ## operator:
## ##
## .. code-block:: nim ## .. code-block:: nim
## import json ## import std/json
## ##
## var hisName = "John" ## var hisName = "John"
## let herAge = 31 ## let herAge = 31

View file

@ -18,7 +18,7 @@
## To get started, first create a logger: ## To get started, first create a logger:
## ##
## .. code-block:: ## .. code-block::
## import logging ## import std/logging
## ##
## var logger = newConsoleLogger() ## var logger = newConsoleLogger()
## ##
@ -60,7 +60,7 @@
## in the following example: ## in the following example:
## ##
## .. code-block:: ## .. code-block::
## import logging ## import std/logging
## ##
## var consoleLog = newConsoleLogger() ## var consoleLog = newConsoleLogger()
## var fileLog = newFileLogger("errors.log", levelThreshold=lvlError) ## var fileLog = newFileLogger("errors.log", levelThreshold=lvlError)
@ -118,7 +118,7 @@
## The following example illustrates how to use format strings: ## The following example illustrates how to use format strings:
## ##
## .. code-block:: ## .. code-block::
## import logging ## import std/logging
## ##
## var logger = newConsoleLogger(fmtStr="[$time] - $levelname: ") ## var logger = newConsoleLogger(fmtStr="[$time] - $levelname: ")
## logger.log(lvlInfo, "this is a message") ## logger.log(lvlInfo, "this is a message")

View file

@ -1593,7 +1593,7 @@ proc execCmdEx*(command: string, options: set[ProcessOption] = {
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## var result = execCmdEx("nim r --hints:off -", options = {}, input = "echo 3*4") ## var result = execCmdEx("nim r --hints:off -", options = {}, input = "echo 3*4")
## import strutils, strtabs ## import std/[strutils, strtabs]
## stripLineEnd(result[0]) ## portable way to remove trailing newline, if any ## stripLineEnd(result[0]) ## portable way to remove trailing newline, if any
## doAssert result == ("12", 0) ## doAssert result == ("12", 0)
## doAssert execCmdEx("ls --nonexistant").exitCode != 0 ## doAssert execCmdEx("ls --nonexistant").exitCode != 0

View file

@ -22,7 +22,7 @@
## ##
## .. code-block:: nim ## .. code-block:: nim
## ##
## import os, parsecfg, strutils, streams ## import std/[os, parsecfg, strutils, streams]
## ##
## var f = newFileStream(paramStr(1), fmRead) ## var f = newFileStream(paramStr(1), fmRead)
## if f != nil: ## if f != nil:
@ -66,7 +66,7 @@
## ----------------------------- ## -----------------------------
## .. code-block:: nim ## .. code-block:: nim
## ##
## import parsecfg ## import std/parsecfg
## var dict=newConfig() ## var dict=newConfig()
## dict.setSectionKey("","charset","utf-8") ## dict.setSectionKey("","charset","utf-8")
## dict.setSectionKey("Package","name","hello") ## dict.setSectionKey("Package","name","hello")
@ -80,7 +80,7 @@
## ---------------------------- ## ----------------------------
## .. code-block:: nim ## .. code-block:: nim
## ##
## import parsecfg ## import std/parsecfg
## var dict = loadConfig("config.ini") ## var dict = loadConfig("config.ini")
## var charset = dict.getSectionValue("","charset") ## var charset = dict.getSectionValue("","charset")
## var threads = dict.getSectionValue("Package","--threads") ## var threads = dict.getSectionValue("Package","--threads")
@ -94,7 +94,7 @@
## ------------------------------ ## ------------------------------
## .. code-block:: nim ## .. code-block:: nim
## ##
## import parsecfg ## import std/parsecfg
## var dict = loadConfig("config.ini") ## var dict = loadConfig("config.ini")
## dict.setSectionKey("Author","name","lhf") ## dict.setSectionKey("Author","name","lhf")
## dict.writeConfig("config.ini") ## dict.writeConfig("config.ini")
@ -103,7 +103,7 @@
## ---------------------------------------------- ## ----------------------------------------------
## .. code-block:: nim ## .. code-block:: nim
## ##
## import parsecfg ## import std/parsecfg
## var dict = loadConfig("config.ini") ## var dict = loadConfig("config.ini")
## dict.delSectionKey("Author","email") ## dict.delSectionKey("Author","email")
## dict.writeConfig("config.ini") ## dict.writeConfig("config.ini")
@ -115,7 +115,7 @@
# taken from https://docs.python.org/3/library/configparser.html#supported-ini-file-structure # taken from https://docs.python.org/3/library/configparser.html#supported-ini-file-structure
runnableExamples: runnableExamples:
import streams import std/streams
var dict = loadConfig(newStringStream("""[Simple Values] var dict = loadConfig(newStringStream("""[Simple Values]
key=value key=value

View file

@ -14,9 +14,9 @@
## =========== ## ===========
## ##
## .. code-block:: nim ## .. code-block:: nim
## import parsecsv ## import std/parsecsv
## from os import paramStr ## from std/os import paramStr
## from streams import newFileStream ## from std/streams import newFileStream
## ##
## var s = newFileStream(paramStr(1), fmRead) ## var s = newFileStream(paramStr(1), fmRead)
## if s == nil: ## if s == nil:
@ -34,7 +34,7 @@
## reference for item access with `rowEntry <#rowEntry,CsvParser,string>`_: ## reference for item access with `rowEntry <#rowEntry,CsvParser,string>`_:
## ##
## .. code-block:: nim ## .. code-block:: nim
## import parsecsv ## import std/parsecsv
## ##
## # Prepare a file ## # Prepare a file
## let content = """One,Two,Three,Four ## let content = """One,Two,Three,Four
@ -120,7 +120,7 @@ proc open*(my: var CsvParser, input: Stream, filename: string,
## * `open proc <#open,CsvParser,string,char,char,char>`_ which creates the ## * `open proc <#open,CsvParser,string,char,char,char>`_ which creates the
## file stream for you ## file stream for you
runnableExamples: runnableExamples:
import streams import std/streams
var strm = newStringStream("One,Two,Three\n1,2,3\n10,20,30") var strm = newStringStream("One,Two,Three\n1,2,3\n10,20,30")
var parser: CsvParser var parser: CsvParser
parser.open(strm, "tmp.csv") parser.open(strm, "tmp.csv")
@ -142,7 +142,7 @@ proc open*(my: var CsvParser, filename: string,
## Similar to the `other open proc<#open,CsvParser,Stream,string,char,char,char>`_, ## Similar to the `other open proc<#open,CsvParser,Stream,string,char,char,char>`_,
## but creates the file stream for you. ## but creates the file stream for you.
runnableExamples: runnableExamples:
from os import removeFile from std/os import removeFile
writeFile("tmp.csv", "One,Two,Three\n1,2,3\n10,20,300") writeFile("tmp.csv", "One,Two,Three\n1,2,3\n10,20,300")
var parser: CsvParser var parser: CsvParser
parser.open("tmp.csv") parser.open("tmp.csv")
@ -203,7 +203,7 @@ proc processedRows*(my: var CsvParser): int =
## But even if `readRow <#readRow,CsvParser,int>`_ arrived at EOF then ## But even if `readRow <#readRow,CsvParser,int>`_ arrived at EOF then
## processed rows counter is incremented. ## processed rows counter is incremented.
runnableExamples: runnableExamples:
import streams import std/streams
var strm = newStringStream("One,Two,Three\n1,2,3") var strm = newStringStream("One,Two,Three\n1,2,3")
var parser: CsvParser var parser: CsvParser
@ -229,7 +229,7 @@ proc readRow*(my: var CsvParser, columns = 0): bool =
## ##
## Blank lines are skipped. ## Blank lines are skipped.
runnableExamples: runnableExamples:
import streams import std/streams
var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30") var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30")
var parser: CsvParser var parser: CsvParser
parser.open(strm, "tmp.csv") parser.open(strm, "tmp.csv")
@ -296,7 +296,7 @@ proc readHeaderRow*(my: var CsvParser) =
## See also: ## See also:
## * `rowEntry proc <#rowEntry,CsvParser,string>`_ ## * `rowEntry proc <#rowEntry,CsvParser,string>`_
runnableExamples: runnableExamples:
import streams import std/streams
var strm = newStringStream("One,Two,Three\n1,2,3") var strm = newStringStream("One,Two,Three\n1,2,3")
var parser: CsvParser var parser: CsvParser
@ -325,7 +325,7 @@ proc rowEntry*(my: var CsvParser, entry: string): var string =
## ##
## If specified `entry` does not exist, raises KeyError. ## If specified `entry` does not exist, raises KeyError.
runnableExamples: runnableExamples:
import streams import std/streams
var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30") var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30")
var parser: CsvParser var parser: CsvParser
parser.open(strm, "tmp.csv") parser.open(strm, "tmp.csv")

View file

@ -49,7 +49,7 @@
## Here is an example: ## Here is an example:
## ##
## .. code-block:: ## .. code-block::
## import parseopt ## import std/parseopt
## ##
## var p = initOptParser("-ab -e:5 --foo --bar=20 file.txt") ## var p = initOptParser("-ab -e:5 --foo --bar=20 file.txt")
## while true: ## while true:
@ -99,7 +99,7 @@
## arguments for those two parameters: ## arguments for those two parameters:
## ##
## .. code-block:: ## .. code-block::
## import parseopt ## import std/parseopt
## ##
## proc printToken(kind: CmdLineKind, key: string, val: string) = ## proc printToken(kind: CmdLineKind, key: string, val: string) =
## case kind ## case kind

View file

@ -26,7 +26,7 @@
## ##
## .. code-block:: nim ## .. code-block:: nim
## :test: ## :test:
## from strutils import Digits, parseInt ## from std/strutils import Digits, parseInt
## ##
## let ## let
## input1 = "2019 school start" ## input1 = "2019 school start"

View file

@ -941,7 +941,7 @@ template eventParser*(pegAst, handlers: untyped): (proc(s: string): int) =
## evaluates an arithmetic expression defined by a simple PEG: ## evaluates an arithmetic expression defined by a simple PEG:
## ##
## .. code-block:: nim ## .. code-block:: nim
## import strutils, pegs ## import std/[strutils, pegs]
## ##
## let ## let
## pegAst = """ ## pegAst = """

View file

@ -29,7 +29,7 @@
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## ##
## import streams ## import std/streams
## ##
## var strm = newStringStream("""The first line ## var strm = newStringStream("""The first line
## the second line ## the second line
@ -54,7 +54,7 @@
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## ##
## import streams ## import std/streams
## ##
## var strm = newFileStream("somefile.txt", fmWrite) ## var strm = newFileStream("somefile.txt", fmWrite)
## var line = "" ## var line = ""
@ -74,7 +74,7 @@
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## ##
## import streams ## import std/streams
## ##
## var strm = newFileStream("somefile.txt", fmRead) ## var strm = newFileStream("somefile.txt", fmRead)
## var line = "" ## var line = ""
@ -144,7 +144,7 @@ proc flush*(s: Stream) =
## See also: ## See also:
## * `close proc <#close,Stream>`_ ## * `close proc <#close,Stream>`_
runnableExamples: runnableExamples:
from os import removeFile from std/os import removeFile
var strm = newFileStream("somefile.txt", fmWrite) var strm = newFileStream("somefile.txt", fmWrite)
@ -1387,7 +1387,7 @@ proc newFileStream*(filename: string, mode: FileMode = fmRead,
## * `openFileStream proc <#openFileStream,string,FileMode,int>`_ creates a ## * `openFileStream proc <#openFileStream,string,FileMode,int>`_ creates a
## file stream from the file name and the mode. ## file stream from the file name and the mode.
runnableExamples: runnableExamples:
from os import removeFile from std/os import removeFile
var strm = newFileStream("somefile.txt", fmWrite) var strm = newFileStream("somefile.txt", fmWrite)
if not isNil(strm): if not isNil(strm):
strm.writeLine("The first line") strm.writeLine("The first line")

View file

@ -89,7 +89,7 @@ proc newPipeOutStream*[T](s: sink (ref T)): owned PipeOutStream[T] =
## Example: ## Example:
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import osproc, streamwrapper ## import std/[osproc, streamwrapper]
## var ## var
## p = startProcess(exePath) ## p = startProcess(exePath)
## outStream = p.outputStream().newPipeOutStream() ## outStream = p.outputStream().newPipeOutStream()

View file

@ -175,7 +175,7 @@ overloaded to handle both single characters and sets of character.
.. code-block:: nim .. code-block:: nim
import streams import std/streams
template atom(input: Stream; idx: int; c: char): bool = template atom(input: Stream; idx: int; c: char): bool =
## Used in scanp for the matching of atoms (usually chars). ## Used in scanp for the matching of atoms (usually chars).

View file

@ -38,7 +38,7 @@ runnableExamples:
## `method call syntax<manual.html#procedures-method-call-syntax>`_: ## `method call syntax<manual.html#procedures-method-call-syntax>`_:
runnableExamples: runnableExamples:
from sequtils import map from std/sequtils import map
let jenny = "867-5309" let jenny = "867-5309"
assert jenny.split('-').map(parseInt) == @[867, 5309] assert jenny.split('-').map(parseInt) == @[867, 5309]

View file

@ -21,7 +21,7 @@
======== ========
.. code-block:: nim .. code-block:: nim
import times, os import std/[times, os]
# Simple benchmarking # Simple benchmarking
let time = cpuTime() let time = cpuTime()
sleep(100) # Replace this with something to be timed sleep(100) # Replace this with something to be timed

View file

@ -280,7 +280,7 @@ proc fromJsonHook*[K, V](t: var (Table[K, V] | OrderedTable[K, V]),
## See also: ## See also:
## * `toJsonHook proc<#toJsonHook>`_ ## * `toJsonHook proc<#toJsonHook>`_
runnableExamples: runnableExamples:
import tables, json import std/[tables, json]
var foo: tuple[t: Table[string, int], ot: OrderedTable[string, int]] var foo: tuple[t: Table[string, int], ot: OrderedTable[string, int]]
fromJson(foo, parseJson(""" fromJson(foo, parseJson("""
{"t":{"two":2,"one":1},"ot":{"one":1,"three":3}}""")) {"t":{"two":2,"one":1},"ot":{"one":1,"three":3}}"""))
@ -300,7 +300,7 @@ proc toJsonHook*[K, V](t: (Table[K, V] | OrderedTable[K, V])): JsonNode =
## See also: ## See also:
## * `fromJsonHook proc<#fromJsonHook,,JsonNode>`_ ## * `fromJsonHook proc<#fromJsonHook,,JsonNode>`_
runnableExamples: runnableExamples:
import tables, json import std/[tables, json]
let foo = ( let foo = (
t: [("two", 2)].toTable, t: [("two", 2)].toTable,
ot: [("one", 1), ("three", 3)].toOrderedTable) ot: [("one", 1), ("three", 3)].toOrderedTable)
@ -316,7 +316,7 @@ proc fromJsonHook*[A](s: var SomeSet[A], jsonNode: JsonNode) =
## See also: ## See also:
## * `toJsonHook proc<#toJsonHook,SomeSet[A]>`_ ## * `toJsonHook proc<#toJsonHook,SomeSet[A]>`_
runnableExamples: runnableExamples:
import sets, json import std/[sets, json]
var foo: tuple[hs: HashSet[string], os: OrderedSet[string]] var foo: tuple[hs: HashSet[string], os: OrderedSet[string]]
fromJson(foo, parseJson(""" fromJson(foo, parseJson("""
{"hs": ["hash", "set"], "os": ["ordered", "set"]}""")) {"hs": ["hash", "set"], "os": ["ordered", "set"]}"""))
@ -336,7 +336,7 @@ proc toJsonHook*[A](s: SomeSet[A]): JsonNode =
## See also: ## See also:
## * `fromJsonHook proc<#fromJsonHook,SomeSet[A],JsonNode>`_ ## * `fromJsonHook proc<#fromJsonHook,SomeSet[A],JsonNode>`_
runnableExamples: runnableExamples:
import sets, json import std/[sets, json]
let foo = (hs: ["hash"].toHashSet, os: ["ordered", "set"].toOrderedSet) let foo = (hs: ["hash"].toHashSet, os: ["ordered", "set"].toOrderedSet)
assert $toJson(foo) == """{"hs":["hash"],"os":["ordered","set"]}""" assert $toJson(foo) == """{"hs":["hash"],"os":["ordered","set"]}"""
@ -350,7 +350,7 @@ proc fromJsonHook*[T](self: var Option[T], jsonNode: JsonNode) =
## See also: ## See also:
## * `toJsonHook proc<#toJsonHook,Option[T]>`_ ## * `toJsonHook proc<#toJsonHook,Option[T]>`_
runnableExamples: runnableExamples:
import options, json import std/[options, json]
var opt: Option[string] var opt: Option[string]
fromJsonHook(opt, parseJson("\"test\"")) fromJsonHook(opt, parseJson("\"test\""))
assert get(opt) == "test" assert get(opt) == "test"
@ -368,7 +368,7 @@ proc toJsonHook*[T](self: Option[T]): JsonNode =
## See also: ## See also:
## * `fromJsonHook proc<#fromJsonHook,Option[T],JsonNode>`_ ## * `fromJsonHook proc<#fromJsonHook,Option[T],JsonNode>`_
runnableExamples: runnableExamples:
import options, json import std/[options, json]
let optSome = some("test") let optSome = some("test")
assert $toJson(optSome) == "\"test\"" assert $toJson(optSome) == "\"test\""
let optNone = none[string]() let optNone = none[string]()
@ -385,7 +385,7 @@ proc fromJsonHook*(a: var StringTableRef, b: JsonNode) =
## See also: ## See also:
## * `toJsonHook proc<#toJsonHook,StringTableRef>`_ ## * `toJsonHook proc<#toJsonHook,StringTableRef>`_
runnableExamples: runnableExamples:
import strtabs, json import std/[strtabs, json]
var t = newStringTable(modeCaseSensitive) var t = newStringTable(modeCaseSensitive)
let jsonStr = """{"mode": 0, "table": {"name": "John", "surname": "Doe"}}""" let jsonStr = """{"mode": 0, "table": {"name": "John", "surname": "Doe"}}"""
fromJsonHook(t, parseJson(jsonStr)) fromJsonHook(t, parseJson(jsonStr))
@ -403,7 +403,7 @@ proc toJsonHook*(a: StringTableRef): JsonNode =
## See also: ## See also:
## * `fromJsonHook proc<#fromJsonHook,StringTableRef,JsonNode>`_ ## * `fromJsonHook proc<#fromJsonHook,StringTableRef,JsonNode>`_
runnableExamples: runnableExamples:
import strtabs, json import std/[strtabs, json]
let t = newStringTable("name", "John", "surname", "Doe", modeCaseSensitive) let t = newStringTable("name", "John", "surname", "Doe", modeCaseSensitive)
let jsonStr = """{"mode": "modeCaseSensitive", let jsonStr = """{"mode": "modeCaseSensitive",
"table": {"name": "John", "surname": "Doe"}}""" "table": {"name": "John", "surname": "Doe"}}"""

View file

@ -941,7 +941,7 @@ proc cmp*[T](x, y: T): int =
## This generic implementation uses the `==` and `<` operators. ## This generic implementation uses the `==` and `<` operators.
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## import algorithm ## import std/algorithm
## echo sorted(@[4, 2, 6, 5, 8, 7], cmp[int]) ## echo sorted(@[4, 2, 6, 5, 8, 7], cmp[int])
if x == y: return 0 if x == y: return 0
if x < y: return -1 if x < y: return -1
@ -1745,7 +1745,7 @@ proc instantiationInfo*(index = -1, fullPaths = false): tuple[
## Example: ## Example:
## ##
## .. code-block:: nim ## .. code-block:: nim
## import strutils ## import std/strutils
## ##
## template testException(exception, code: untyped): typed = ## template testException(exception, code: untyped): typed =
## try: ## try:

View file

@ -30,7 +30,7 @@
## # Be sure to compile with --threads:on. ## # Be sure to compile with --threads:on.
## # The channels and threads modules are part of system and should not be ## # The channels and threads modules are part of system and should not be
## # imported. ## # imported.
## import os ## import std/os
## ##
## # Channels can either be: ## # Channels can either be:
## # - declared at the module level, or ## # - declared at the module level, or

View file

@ -913,7 +913,7 @@ iterator lines*(filename: string): string {.tags: [ReadIOEffect].} =
## character(s) are removed from the iterated lines. Example: ## character(s) are removed from the iterated lines. Example:
## ##
## .. code-block:: nim ## .. code-block:: nim
## import strutils ## import std/strutils
## ##
## proc transformLetters(filename: string) = ## proc transformLetters(filename: string) =
## var buffer = "" ## var buffer = ""

View file

@ -12,7 +12,7 @@ iterator countdown*[T](a, b: T, step: Positive = 1): T {.inline.} =
## **Note**: This fails to count to `low(int)` if T = int for ## **Note**: This fails to count to `low(int)` if T = int for
## efficiency reasons. ## efficiency reasons.
runnableExamples: runnableExamples:
import sugar import std/sugar
let x = collect(newSeq): let x = collect(newSeq):
for i in countdown(7, 3): for i in countdown(7, 3):
i i
@ -49,7 +49,7 @@ iterator countup*[T](a, b: T, step: Positive = 1): T {.inline.} =
## **Note**: This fails to count to `high(int)` if T = int for ## **Note**: This fails to count to `high(int)` if T = int for
## efficiency reasons. ## efficiency reasons.
runnableExamples: runnableExamples:
import sugar import std/sugar
let x = collect(newSeq): let x = collect(newSeq):
for i in countup(3, 7): for i in countup(3, 7):
i i
@ -78,7 +78,7 @@ iterator `..`*[T](a, b: T): T {.inline.} =
## See also: ## See also:
## * [..<](#..<.i,T,T) ## * [..<](#..<.i,T,T)
runnableExamples: runnableExamples:
import sugar import std/sugar
let x = collect(newSeq): let x = collect(newSeq):
for i in 3 .. 7: for i in 3 .. 7:

View file

@ -24,7 +24,7 @@
## ##
## .. code-block:: Nim ## .. code-block:: Nim
## ##
## import locks ## import std/locks
## ##
## var ## var
## thr: array[0..4, Thread[tuple[a,b: int]]] ## thr: array[0..4, Thread[tuple[a,b: int]]]