### niminst File Installation Example
Source: https://nim-lang.org/1.0.0/niminst.html
Example of how to specify files to be installed using the 'files' key in different sections of the niminst configuration. Supports wildcards and directory installation.
```nimconfig
[Config]
Files: "configDir"
Files: "otherconfig/*.conf;otherconfig/*.cfg"
```
--------------------------------
### niminst InnoSetup Flag Example
Source: https://nim-lang.org/1.0.0/niminst.html
Example of setting the 'InnoSetup' flag in the Windows section to enable generation of an Inno Setup installer.
```nimconfig
InnoSetup: "Yes"
```
--------------------------------
### Example: Creating and Closing a String Stream
Source: https://nim-lang.org/1.0.0/streams.html
Demonstrates the creation of a StringStream with initial content and its subsequent closing. This example is a setup for further stream operations.
```nim
var strm = newStringStream("The first line\nthe second line\nthe third line")
```
--------------------------------
### CGI Application Example
Source: https://nim-lang.org/1.0.0/cgi.html
Demonstrates reading, validating, and writing data for a CGI application. Includes conditional debugging setup.
```nim
import strtabs, cgi
# Fill the values when debugging:
when debug:
setTestData("name", "Klaus", "password", "123456")
# read the data into `myData`
var myData = readData()
# check that the data's variable names are "name" or "password"
validateData(myData, "name", "password")
# start generating content:
writeContentType()
# generate content:
write(stdout, "<\n")
write(stdout, "
Test\n")
writeLine(stdout, "your name: " & myData["name"])
writeLine(stdout, "your password: " & myData["password"])
writeLine(stdout, "")
```
--------------------------------
### InnoSetup Configuration
Source: https://nim-lang.org/1.0.0/niminst.html
Configures the Inno Setup compiler path and flags for creating Windows installers.
```niminst
[InnoSetup]
path = r"c:\Program Files (x86)\Inno Setup 5\iscc.exe"
flags = "/Q"
```
--------------------------------
### Match Examples
Source: https://nim-lang.org/1.0.0/nre.html
Examples demonstrating the usage of the `match` procedure for regular expressions.
```nim
doAssert "foo".match(re"f").isSome
doAssert "foo".match(re"o").isNone
```
--------------------------------
### Procedure Documentation with Usage Example
Source: https://nim-lang.org/1.0.0/contributing.html
Document procedures starting with a capital letter and in present tense. Include usage examples using `runnableExamples` or `code-block`.
```nim
proc example1*(x: int) =
## Prints the value of `x`.
echo x
```
```nim
proc addThree*(x, y, z: int8): int =
## Adds three `int8` values, treating them as unsigned and
## truncating the result.
##
## .. code-block::
## # things that aren't suitable for a `runnableExamples` go in code-block:
## echo execCmdEx("git pull")
## drawOnScreen()
runnableExamples:
# `runnableExamples` is usually preferred to `code-block`, when possible.
doAssert addThree(3, 125, 6) == -122
result = x +% y +% z
```
--------------------------------
### Basic Hot Code Reloading Setup with SDL2
Source: https://nim-lang.org/1.0.0/hcr.html
This snippet demonstrates setting up hot code reloading for a logic module that is reloaded when F9 is pressed. Ensure SDL2 is installed via 'nimble install sdl2'.
```nim
# logic.nim
import sdl2/sdl
#*** import the hotcodereloading stdlib module ***
import hotcodereloading
var runGame*: bool = true
var window: Window
var renderer: Renderer
proc init*() =
discard sdl.init(INIT_EVERYTHING)
window = createWindow("testing", WINDOWPOS_UNDEFINED.cint, WINDOWPOS_UNDEFINED.cint, 640, 480, 0'u32)
assert(window != nil, $sdl.getError())
renderer = createRenderer(window, -1, RENDERER_SOFTWARE)
assert(renderer != nil, $sdl.getError())
proc destroy*() =
destroyRenderer(renderer)
destroyWindow(window)
var posX = 1
var posY = 0
var dX = 1
var dY = 1
proc update*() =
for evt in events():
if evt.kind == QUIT:
runGame = false
break
if evt.kind == KEY_DOWN:
if evt.key.keysym.scancode == SCANCODE_ESCAPE: runGame = false
elif evt.key.keysym.scancode == SCANCODE_F9:
#*** reload this logic.nim module on the F9 keypress ***
performCodeReload()
# draw a bouncing rectangle:
posX += dX
posY += dY
if posX >= 640: dX = -2
if posX <= 0: dX = +2
if posY >= 480: dY = -2
if posY <= 0: dY = +2
discard renderer.setRenderDrawColor(0, 0, 255, 255)
discard renderer.renderClear()
discard renderer.setRenderDrawColor(255, 128, 128, 0)
var rect: Rect(x: posX - 25, y: posY - 25, w: 50, h: 50)
discard renderer.renderFillRect(rect.addr)
delay(16)
renderer.renderPresent()
```
```nim
# mymain.nim
import logic
proc main() =
init()
while runGame:
update()
destroy()
main()
```
--------------------------------
### niminst InstallScript Flag Example
Source: https://nim-lang.org/1.0.0/niminst.html
Example of setting the 'InstallScript' flag in the Unix section to enable generation of an installation shell script.
```nimconfig
InstallScript: "Yes"
```
--------------------------------
### Create a Console Logger
Source: https://nim-lang.org/1.0.0/logging.html
Instantiate a logger that outputs messages to the console. This is the basic setup for starting with the logging module.
```nim
import logging
var logger = newConsoleLogger()
```
--------------------------------
### Split Examples
Source: https://nim-lang.org/1.0.0/nre.html
Examples demonstrating the usage of the `split` procedure for regular expressions.
```nim
doAssert "123".split(re"") == @["1", "2", "3"]
doAssert "12".split(re"(\d)") == @["", "1", "", "2", ""]
doAssert "1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]
```
--------------------------------
### Configuration File Content Example
Source: https://nim-lang.org/1.0.0/parsecfg.html
Provides an example of the content that can be present in a configuration file, including character set, package details, and author information.
```nim
charset = "utf-8"
[Package]
name = "hello"
--threads:on
[Author]
name = "lihf8515"
qq = "10214028"
email = "lihaifeng@wxm.com"
```
--------------------------------
### Add Runnable Documentation Examples
Source: https://nim-lang.org/1.0.0/contributing.html
Include runnable code examples within documentation comments using the `runnableExamples` block. These examples are automatically tested by `nim doc` and `testament`.
```nim
proc addBar*(a: string): string =
## Adds "Bar" to `a`.
runnableExamples:
assert "baz".addBar == "bazBar"
result = a & "Bar"
```
--------------------------------
### skMacro Example
Source: https://nim-lang.org/1.0.0/idetools.html
Example output for a macro, including its qualified name, signature, and an empty docstring.
```nim
proc testMacro() =
expect(EArithmetic):
--> col 2: idetools_api.expect
col 3: proc (varargs[expr], stmt): stmt
col 7: ""
```
--------------------------------
### Define a Test Suite with Setup and Tests
Source: https://nim-lang.org/1.0.0/unittest.html
Demonstrates defining a test suite with setup and teardown logic, and includes tests using `require`, `check`, and `expect` for assertions and error handling.
```nim
suite "description for this stuff":
echo "suite setup: run once before the tests"
setup:
echo "run before each test"
teardown:
echo "run after each test"
test "essential truths":
# give up and stop if this fails
require(true)
test "slightly less obvious stuff":
# print a nasty message and move on, skipping
# the remainder of this block
check(1 != 1)
check("asd"[2] == 'd')
test "out of bounds error is thrown on bad access":
let v = @[1, 2, 3] # you can do initialization here
expect(IndexError):
discard v[4]
echo "suite teardown: run once after the tests"
```
--------------------------------
### Comprehensive Database Operations Example
Source: https://nim-lang.org/1.0.0/db_odbc.html
A large example demonstrating table creation, transaction handling, bulk insertion, data retrieval, and insertion with ID retrieval.
```nim
import db_odbc, math
var theDb = open("localhost", "nim", "nim", "test")
theDb.exec(sql"Drop table if exists myTestTbl")
theDb.exec(sql("create table myTestTbl (" &
" Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " &
" Name VARCHAR(50) NOT NULL, " &
" i INT(11), " &
" f DECIMAL(18,10))"))
theDb.exec(sql"START TRANSACTION")
for i in 1..1000:
theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
"Item#" & $i, i, sqrt(i.float))
theDb.exec(sql"COMMIT")
for x in theDb.fastRows(sql"select * from myTestTbl"):
echo x
let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
"Item#1001", 1001, sqrt(1001.0))
echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
theDb.close()
```
--------------------------------
### Define a Test Suite with Setup
Source: https://nim-lang.org/1.0.0/unittest.html
Use the `suite` template to group related tests. The `setup` block runs before each test within the suite.
```nim
template suite(name, body) {...}{.dirty.}
suite "test suite for addition":
setup:
let result = 4
test "2 + 2 = 4":
check(2+2 == result)
test "(2 + -2) != 4":
check(2 + -2 != result)
# No teardown needed
```
--------------------------------
### skConst Example
Source: https://nim-lang.org/1.0.0/idetools.html
Example output for a constant symbol, showing its module, name, type, and an empty docstring.
```nim
const SOME_SEQUENCE = @[1, 2]
--> col 2: $MODULE.SOME_SEQUENCE
col 3: seq[int]
col 7: ""
```
--------------------------------
### Standalone NimScript: Installation Script
Source: https://nim-lang.org/1.0.0/nims.html
This script demonstrates using NimScript for standalone tasks like installing software. It uses `exec` to run shell commands and `withDir` to change directories.
```nim
mode = ScriptMode.Verbose
var id = 0
while dirExists("nimble" & $id):
inc id
exec "git clone https://github.com/nim-lang/nimble.git nimble" & $id
withDir "nimble" & $id & "/src":
exec "nim c nimble"
mvFile "nimble" & $id & "/src/nimble".toExe, "bin/nimble".toExe
```
--------------------------------
### Set Install Files Variable
Source: https://nim-lang.org/1.0.0/nimscript.html
Nimble metadata: Specifies files to be installed.
```nim
installFiles: seq[string] = @[]
```
--------------------------------
### Set Install Directories Variable
Source: https://nim-lang.org/1.0.0/nimscript.html
Nimble metadata: Specifies directories to be installed.
```nim
installDirs: seq[string] = @[]
```
--------------------------------
### Basic Async HTTP Server Setup
Source: https://nim-lang.org/1.0.0/asynchttpserver.html
Creates an HTTP server on port 8080 that responds to all requests with 'Hello World'. Requires importing asynchttpserver and asyncdispatch.
```nim
import asynchttpserver, asyncdispatch
var server = newAsyncHttpServer()
proc cb(req: Request) {.async.} =
await req.respond(Http200, "Hello World")
waitFor server.serve(Port(8080), cb)
```
--------------------------------
### Set Install Extensions Variable
Source: https://nim-lang.org/1.0.0/nimscript.html
Nimble metadata: Specifies file extensions to be installed.
```nim
installExt: seq[string] = @[]
```
--------------------------------
### Initialize and Parse Options with getopt
Source: https://nim-lang.org/1.0.0/parseopt.html
Initializes an OptParser with a sequence of parameters and iterates through them using the getopt iterator. This example demonstrates handling different argument kinds like cmdArgument, cmdLongOption, and cmdShortOption, including specific actions for help and version flags. It also shows a fallback to display help if no filename is provided.
```nim
proc writeHelp() = discard
proc writeVersion() = discard
var filename: string
let params = @["--left", "--debug:3", "-l", "-r:2"]
for kind, key, val in getopt(params):
case kind
of cmdArgument:
filename = key
of cmdLongOption, cmdShortOption:
case key
of "help", "h": writeHelp()
of "version", "v": writeVersion()
of cmdEnd: assert(false) # cannot happen
if filename == "":
# no filename has been written, so we show the help
writeHelp()
```
--------------------------------
### Get XML Element Tag Example
Source: https://nim-lang.org/1.0.0/xmltree.html
Demonstrates getting the tag name of an element and its child.
```nim
var a = newElement("firstTag")
a.add newElement("childTag")
assert $a == ""
assert a.tag == "firstTag"
```
--------------------------------
### Async HTTP Server Request Handler Example
Source: https://nim-lang.org/1.0.0/asynchttpserver.html
An example request handler that responds with JSON for '/hello-world' and 'Not Found' for other paths. It demonstrates setting content type and responding with different HTTP codes.
```nim
import json
proc handler(req: Request) {.async.} =
if req.url.path == "/hello-world":
let msg = %* {"message": "Hello World"}
let headers = newHttpHeaders([("Content-Type","application/json")])
await req.respond(Http200, $msg, headers)
else:
await req.respond(Http404, "Not Found")
```
--------------------------------
### Get XML Node Text Example
Source: https://nim-lang.org/1.0.0/xmltree.html
Demonstrates getting the text content of a comment node.
```nim
var c = newComment("my comment")
assert $c == ""
assert c.text == "my comment"
```
--------------------------------
### GeneralTokenizer Usage Example
Source: https://nim-lang.org/1.0.0/highlite.html
Example demonstrating how to use the GeneralTokenizer to iterate through tokens in a code string and apply syntax highlighting.
```APIDOC
## GeneralTokenizer Usage Example
### Description
This example shows how to use the `GeneralTokenizer` to parse a code string, identify different token types, and process them. It includes handling for end-of-file, whitespace, operators, and other token kinds.
### Usage
```nim
let code = """for x in $int.high: echo x.ord mod 2 == 0"""
var toknizr: GeneralTokenizer
initGeneralTokenizer(toknizr, code)
while true:
getNextToken(toknizr, langNim)
case toknizr.kind
of gtEof: break # End Of File (or string)
of gtWhitespace:
echo gtWhitespace # Maybe you want "visible" whitespaces?.
echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1)
of gtOperator:
echo gtOperator # Maybe you want Operators to use a specific color?.
echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1)
# of gtSomeSymbol: syntaxHighlight("Comic Sans", "bold", "99px", "pink")
else:
echo toknizr.kind # All the kinds of tokens can be processed here.
echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1)
```
```
--------------------------------
### Create and Open a New Memory Mapped File
Source: https://nim-lang.org/1.0.0/memfiles.html
Example demonstrating how to create a new memory-mapped file with a specified size and then open it for read/write access.
```nim
var
mm, mm_full, mm_half: MemFile
mm = memfiles.open("/tmp/test.mmap", mode = fmWrite, newFileSize = 1024) # Create a new file
mm.close()
# Read the whole file, would fail if newFileSize was set
mm_full = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = -1)
```
--------------------------------
### Use strutils.replace
Source: https://nim-lang.org/1.0.0/manual.html
Demonstrates fully qualified access to module functions.
```nim
echo strutils.replace("abc", "a", "z")
```
--------------------------------
### Create and Populate a Table
Source: https://nim-lang.org/1.0.0/tables.html
Demonstrates creating a table from two sequences and populating it with key-value pairs. Requires importing 'tables' and 'sequtils'.
```nim
import tables
from sequtils import zip
let
names = ["John", "Paul", "George", "Ringo"]
years = [1940, 1942, 1943, 1940]
var beatles = initTable[string, int]()
for pairs in zip(names, years):
let (name, birthYear) = pairs
beatles[name] = birthYear
echo beatles
# {"George": 1943, "Ringo": 1940, "Paul": 1942, "John": 1940}
```
--------------------------------
### Get Foreign Dependency Installation Command
Source: https://nim-lang.org/1.0.0/distros.html
Returns the native command line for installing a specified foreign package and a boolean indicating if root privileges are required.
```nim
proc foreignDepInstallCmd(foreignPackageName: string): (string, bool) {...}{.raises: [],
tags: [].}
```
--------------------------------
### Get Node Kind Example
Source: https://nim-lang.org/1.0.0/xmltree.html
Demonstrates checking the kind of an element node and a text node.
```nim
var a = newElement("firstTag")
assert a.kind == xnElement
var b = newText("my text")
assert b.kind == xnText
```
--------------------------------
### Create and Use a String Table
Source: https://nim-lang.org/1.0.0/strtabs.html
Demonstrates basic creation, insertion, and checking for keys in a default case-sensitive string table.
```nim
var t = newStringTable()
t["name"] = "John"
t["city"] = "Monaco"
doAssert t.len == 2
doAssert t.hasKey "name"
doAssert "name" in t
```
--------------------------------
### Get Number of Children Example
Source: https://nim-lang.org/1.0.0/xmltree.html
Demonstrates counting the children of an element after adding and inserting nodes.
```nim
var f = newElement("myTag")
f.add newElement("first")
f.insert(newElement("second"), 0)
assert len(f) == 2
```
--------------------------------
### Module-Level Documentation Example
Source: https://nim-lang.org/1.0.0/contributing.html
Place module-level documentation at the top of the file using double hashes. Include a description and optionally authorship and copyright information.
```nim
## The `universe` module computes the answer to life, the universe, and everything.
##
## .. code-block::
## doAssert computeAnswerString() == 42
```
```nim
## This is the best module ever. It provides answers to everything!
##
## :Author: Steve McQueen
## :Copyright: 1965
##
```
--------------------------------
### Creating a TCP server
Source: https://nim-lang.org/1.0.0/net.html
Sets up a TCP server by binding to a port and starting to listen for incoming connections.
```APIDOC
## bindAddr and listen
### Description
Binds the socket to a specific port and starts listening for incoming connections to create a server.
### Signature
`proc bindAddr*(s: Socket, port: Port)`
`proc listen*(s: Socket)`
### Example
```nim
var socket = newSocket()
socket.bindAddr(Port(1234))
socket.listen()
```
```
--------------------------------
### Retrieve a website using HTTP GET
Source: https://nim-lang.org/1.0.0/httpclient.html
Use `newHttpClient` for synchronous GET requests. For asynchronous operations, use `newAsyncHttpClient` and `await`.
```nim
import httpClient
var client = newHttpClient()
echo client.getContent("http://google.com")
```
```nim
import httpClient
var client = newAsyncHttpClient()
echo await client.getContent("http://google.com")
```
--------------------------------
### Larger example
Source: https://nim-lang.org/1.0.0/db_sqlite.html
A comprehensive example demonstrating opening a connection, creating a table, inserting multiple rows within a transaction, iterating through results, inserting a row and retrieving its ID, and finally closing the connection.
```APIDOC
## Larger example
### Description
Demonstrates a more extensive usage pattern including transactions and data retrieval.
### Example
```nim
import db_sqlite, math
let db = open("mytest.db", "", "", "")
db.exec(sql"DROP TABLE IF EXISTS my_table")
db.exec(sql"""CREATE TABLE my_table (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
i INT(11),
f DECIMAL(18, 10)
)""")
db.exec(sql"BEGIN")
for i in 1..1000:
db.exec(sql"INSERT INTO my_table (name, i, f) VALUES (?, ?, ?)",
"Item#" & $i, i, sqrt(i.float))
db.exec(sql"COMMIT")
for x in db.fastRows(sql"SELECT * FROM my_table"):
echo x
let id = db.tryInsertId(sql"""INSERT INTO my_table (name, i, f)
VALUES (?, ?, ?)""",
"Item#1001", 1001, sqrt(1001.0))
echo "Inserted item: ", db.getValue(sql"SELECT name FROM my_table WHERE id=?", id)
db.close()
```
```
--------------------------------
### open
Source: https://nim-lang.org/1.0.0/iup.html
Initializes the IUP library.
```APIDOC
## open
### Description
Initializes the IUP library. This must be called before any other IUP function.
### Method
N/A (Procedure call)
### Parameters
- **argc** (ptr cint) - Pointer to the argument count.
- **argv** (ptr cstringArray) - Pointer to the argument values.
### Response
Returns an integer indicating success (1) or failure (0).
```
--------------------------------
### Reading a Configuration File
Source: https://nim-lang.org/1.0.0/parsecfg.html
Demonstrates how to load an existing configuration file and retrieve specific values using their section and key. The retrieved values are then printed to the console.
```nim
import parsecfg
var dict = loadConfig("config.ini")
var charset = dict.getSectionValue("","charset")
var threads = dict.getSectionValue("Package","--threads")
var pname = dict.getSectionValue("Package","name")
var name = dict.getSectionValue("Author","name")
var qq = dict.getSectionValue("Author","qq")
var email = dict.getSectionValue("Author","email")
echo pname & "\n" & name & "\n" & qq & "\n" & email
```
--------------------------------
### Get Inner Text Example
Source: https://nim-lang.org/1.0.0/xmltree.html
Demonstrates retrieving the combined inner text from an element containing text, a comment, and an entity.
```nim
var f = newElement("myTag")
f.add newText("my text")
f.add newComment("my comment")
f.add newEntity("my entity")
assert $f == "my text&my entity;"
assert innerText(f) == "my textmy entity"
```
--------------------------------
### Example: Accessing and Verifying Deque Elements
Source: https://nim-lang.org/1.0.0/deques.html
Demonstrates initializing a deque, adding elements, and accessing them by index. Includes a check for out-of-bounds access.
```nim
var a = initDeque[int]()
for i in 1 .. 5:
a.addLast(10 * i)
assert a[0] == 10
assert a[3] == 40
doAssertRaises(IndexError, echo a[8])
```
--------------------------------
### Get Capture Bounds
Source: https://nim-lang.org/1.0.0/pegs.html
Retrieves the start and end indices (bounds) of a specific captured group within a match. The index `i` is 0-based.
```nim
proc bounds(c: Captures; i: range[0 .. 20 - 1]): tuple[first, last: int] {...}{.raises: [],
tags: [].}
```
--------------------------------
### Comprehensive MySQL Operations Example
Source: https://nim-lang.org/1.0.0/db_mysql.html
Demonstrates a larger workflow including table creation, transaction, bulk insertion, data retrieval, and insertion with ID retrieval. Requires 'math' and 'db_mysql' imports.
```nim
import db_mysql, math
let theDb = open("localhost", "nim", "nim", "test")
theDb.exec(sql"Drop table if exists myTestTbl")
theDb.exec(sql("create table myTestTbl (" &
" Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " &
" Name VARCHAR(50) NOT NULL, " &
" i INT(11), " &
" f DECIMAL(18,10))"))
theDb.exec(sql"START TRANSACTION")
for i in 1..1000:
theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
"Item#" & $i, i, sqrt(i.float))
theDb.exec(sql"COMMIT")
for x in theDb.fastRows(sql"select * from myTestTbl"):
echo x
let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
"Item#1001", 1001, sqrt(1001.0))
echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
theDb.close()
```
--------------------------------
### Substring Extraction with Default Start
Source: https://nim-lang.org/1.0.0/system.html
Copies a slice of a string starting from the beginning up to a specified index.
```nim
proc substr(s: string; first = 0): string {...}{.raises: [], tags: []}
```
--------------------------------
### Getting Capture Bounds by Index
Source: https://nim-lang.org/1.0.0/nre.html
Demonstrates retrieving the start and end indices (inclusive) of a captured substring using its numerical index.
```nim
"abc".match(re"(\w)").get.captureBounds[0] == 0 .. 0
```
--------------------------------
### Conditional Compilation Example
Source: https://nim-lang.org/1.0.0/system.html
An example demonstrating the use of the 'defined' procedure for conditional compilation based on build-time flags.
```nim
when not defined(release):
# Do here programmer friendly expensive sanity checks.
```
--------------------------------
### Get Current Exception Example
Source: https://nim-lang.org/1.0.0/tut2.html
Shows how to access the current exception object and message within an `except` block using `getCurrentException` and `getCurrentExceptionMsg`.
```nim
try:
doSomethingHere()
except:
let
e = getCurrentException()
msg = getCurrentExceptionMsg()
echo "Got exception ", repr(e), " with message ", msg
```
--------------------------------
### Get Rune Length at Byte Index in Nim
Source: https://nim-lang.org/1.0.0/unicode.html
Returns the number of bytes a rune starting at a specific byte index takes. Useful for understanding string encoding.
```nim
proc runeLenAt(s: string; i: Natural): int {...}{.raises: [], tags: [].}
let a = "añyóng"
doAssert a.runeLenAt(0) == 1
doAssert a.runeLenAt(1) == 2
```
--------------------------------
### runnableExamples
Source: https://nim-lang.org/1.0.0/system.html
Marks code blocks as runnable examples that are compiled and tested during documentation generation. These examples are ignored in normal builds.
```APIDOC
## proc runnableExamples(body: untyped)
Marks code blocks as runnable examples. These examples are compiled and tested during documentation generation but ignored in normal builds. They are collected into separate files to ensure they do not rely on non-exported symbols.
```
--------------------------------
### Combine Strip and StdTmpl Filters with Pipe Operator
Source: https://nim-lang.org/1.0.0/filters.html
Chain multiple filters using the pipe operator `|`. This example first strips lines starting with '<' and then applies the `stdtmpl` filter.
```nim
#? strip(startswith="<") | stdtmpl
#proc generateXML(name, age: string): string =
# result = ""
$name
$age
```
--------------------------------
### Get Mimetype by Extension
Source: https://nim-lang.org/1.0.0/mimetypes.html
Retrieves the MIME type associated with a given file extension. Returns a default value if the extension is not found. The extension is case-insensitive and can optionally start with a dot.
```nim
func getMimetype(mimedb: MimeDB; ext: string; default = "text/plain"): string {...}{
raises: [], tags: [].
}
```
--------------------------------
### Send Email with STARTTLS
Source: https://nim-lang.org/1.0.0/smtp.html
Example showing how to send an email using STARTTLS for a secure connection. This is useful for servers that do not support direct SSL connections on port 465. Ensure OpenSSL is available if using SSL.
```nim
var msg = createMessage("Hello from Nim's SMTP",
"Hello!.\n Is this awesome or what?",
@["foo@gmail.com"])
let smtpConn = newSmtp(debug=true)
smtpConn.connect("smtp.mailtrap.io", Port 2525)
smtpConn.startTls()
smtpConn.auth("username", "password")
smtpConn.sendmail("username@gmail.com", @["foo@gmail.com"], $msg)
```
--------------------------------
### Add and Get Logging Handlers
Source: https://nim-lang.org/1.0.0/logging.html
Demonstrates how to create a console logger, add it to the system, and verify its registration using getHandlers. Ensure a logger is initialized before adding it.
```nim
var logger = newConsoleLogger()
addHandler(logger)
doAssert logger in getHandlers()
```
--------------------------------
### Send Email via Gmail SMTP
Source: https://nim-lang.org/1.0.0/smtp.html
Example demonstrating how to send an email using Gmail's SMTP server with SSL enabled. Ensure you have OpenSSL installed and compile with -d:ssl for SSL support.
```nim
var msg = createMessage("Hello from Nim's SMTP",
"Hello!.\n Is this awesome or what?",
@["foo@gmail.com"])
let smtpConn = newSmtp(useSsl = true, debug=true)
smtpConn.connect("smtp.gmail.com", Port 465)
smtpConn.auth("username", "password")
smtpConn.sendmail("username@gmail.com", @["foo@gmail.com"], $msg)
```
--------------------------------
### contains(s: string; pattern: Peg; start = 0): bool
Source: https://nim-lang.org/1.0.0/pegs.html
Returns true if `s` starts with the pattern `prefix`. Same as `find(s, pattern, start) >= 0`.
```APIDOC
## contains(s: string; pattern: Peg; start = 0): bool
### Description
Returns true if `s` starts with the pattern `prefix`. Same as `find(s, pattern, start) >= 0`.
### Parameters
#### Path Parameters
- `s` (string) - The string to search within.
- `pattern` (Peg) - The pattern to search for.
- `start` (int) - Optional. The starting position for the search. Defaults to 0.
### Returns
- `bool` - True if the string contains the pattern, false otherwise.
```
--------------------------------
### Asynchronous File Operations Example
Source: https://nim-lang.org/1.0.0/asyncfile.html
Demonstrates basic asynchronous file read and write operations using openAsync, write, setFilePos, readAll, and close. Requires asyncfile, asyncdispatch, and os imports.
```nim
import asyncfile, asyncdispatch, os
proc main() {.async.} =
var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite)
await file.write("test")
file.setFilePos(0)
let data = await file.readAll()
doAssert data == "test"
file.close()
waitFor main()
```
--------------------------------
### contains(s: string; pattern: Peg; matches: var openArray[string]; start = 0): bool
Source: https://nim-lang.org/1.0.0/pegs.html
Returns true if `s` starts with the pattern `prefix`. Same as `find(s, pattern, matches, start) >= 0`.
```APIDOC
## contains(s: string; pattern: Peg; matches: var openArray[string]; start = 0): bool
### Description
Returns true if `s` starts with the pattern `prefix`. Same as `find(s, pattern, matches, start) >= 0`.
### Parameters
#### Path Parameters
- `s` (string) - The string to search within.
- `pattern` (Peg) - The pattern to search for.
- `matches` (var openArray[string]) - An array to store captured substrings.
- `start` (int) - Optional. The starting position for the search. Defaults to 0.
### Returns
- `bool` - True if the string contains the pattern, false otherwise.
```
--------------------------------
### Start PostgreSQL Connection
Source: https://nim-lang.org/1.0.0/postgres.html
Initiates a PostgreSQL connection using connection information string.
```nim
proc pqconnectStart(conninfo: cstring): PPGconn {...}{.cdecl, dynlib: dllName,
importc: "PQconnectStart".}
```
--------------------------------
### startAnchor
Source: https://nim-lang.org/1.0.0/pegs.html
Constructs a PEG that matches the start of the input.
```APIDOC
## startAnchor
### Description
Constructs a PEG that matches the start of the input ('^').
### Method
```nim
proc startAnchor(): Peg
```
```
--------------------------------
### Examples of gcd for integers
Source: https://nim-lang.org/1.0.0/math.html
Provides examples of calculating the GCD for pairs of integers.
```nim
doAssert gcd(12, 8) == 4
doAssert gcd(17, 63) == 1
```
--------------------------------
### Example: Adding Elements to the Front of a Deque
Source: https://nim-lang.org/1.0.0/deques.html
Demonstrates initializing an empty deque and then adding multiple elements to its beginning. The final state of the deque is asserted.
```nim
var a = initDeque[int]()
for i in 1 .. 5:
a.addFirst(10 * i)
assert $a == "[50, 40, 30, 20, 10]"
```
--------------------------------
### Contains Examples
Source: https://nim-lang.org/1.0.0/nre.html
Examples demonstrating the usage of the `contains` procedure for regular expressions.
```nim
doAssert "abc".contains(re"bc") == true
doAssert "abc".contains(re"cd") == false
doAssert "abc".contains(re"a", start = 1) == false
```
--------------------------------
### Create and Drop Table
Source: https://nim-lang.org/1.0.0/db_odbc.html
Illustrates how to create a table and drop it if it already exists.
```nim
db.exec(sql"DROP TABLE IF EXISTS myTable")
db.exec(sql("""CREATE TABLE myTable (
id integer,
name varchar(50) not null)""""))
```
--------------------------------
### Start a New Process in Nim
Source: https://nim-lang.org/1.0.0/osproc.html
Starts a new process with specified command, working directory, arguments, environment, and options. Ensure to close the process when done. Note that args cannot be used with poEvalCommand.
```nim
proc startProcess(command: string; workingDir: string = "";
args: openArray[string] = []; env: StringTableRef = nil;
options: set[ProcessOption] = {poStdErrToStdOut}): owned(Process) {...}{.gcsafe, extern: "nosp$1", tags: [ExecIOEffect, ReadEnvEffect, RootEffect],
raises: [OSError, Exception, ValueError].}
```
--------------------------------
### Create String Table from Constructor
Source: https://nim-lang.org/1.0.0/strtabs.html
Shows how to initialize a string table using a table constructor, providing initial key-value pairs.
```nim
var t = {"name": "John", "city": "Monaco"}.newStringTable
```
--------------------------------
### Install MinGW-w64 Toolchain
Source: https://nim-lang.org/1.0.0/nimc.html
Commands to install the MinGW-w64 toolchain on Ubuntu, CentOS, and macOS.
```shell
Ubuntu: apt install mingw-w64
CentOS: yum install mingw32-gcc | mingw64-gcc - requires EPEL
OSX: brew install mingw-w64
```
--------------------------------
### Parameter Substitution Example
Source: https://nim-lang.org/1.0.0/db_odbc.html
Demonstrates the use of '?' for parameter substitution in SQL queries.
```nim
sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
```
--------------------------------
### Runnable Examples in Nim
Source: https://nim-lang.org/1.0.0/system.html
Use `runnableExamples` to mark code that should be compiled and tested as part of documentation generation. This code is ignored in normal builds.
```nim
proc runnableExamples(body: untyped) {...}{.magic: "RunnableExamples".}
```
```nim
proc double*(x: int): int =
## This proc doubles a number.
runnableExamples:
## at module scope
assert double(5) == 10
block: ## at block scope
defer: echo "done"
result = 2 * x
```
--------------------------------
### NSIS Configuration
Source: https://nim-lang.org/1.0.0/niminst.html
Sets flags for the NSIS (Nullsoft Scriptable Install System) installer.
```niminst
[NSIS]
flags = "/V0"
```
--------------------------------
### installFiles Variable
Source: https://nim-lang.org/1.0.0/nimscript.html
Nimble metadata.
```APIDOC
## Variable: installFiles
Type: `seq[string]`
Nimble metadata.
```
--------------------------------
### Example of gcd for floats
Source: https://nim-lang.org/1.0.0/math.html
Shows an example of calculating the GCD for two float values.
```nim
doAssert gcd(13.5, 9.0) == 4.5
```
--------------------------------
### Start Nim Serve with Stdin/Stdout
Source: https://nim-lang.org/1.0.0/idetools.html
Launches the Nim serve server using stdin/stdout for communication. This is useful for integrating with tools that can pipe input and output.
```bash
nim serve --server.type:stdin proj.nim
```
--------------------------------
### skLet Example
Source: https://nim-lang.org/1.0.0/idetools.html
Example output for a let-bound variable, showing its qualified name and type.
```nim
let
text = "some text"
--> col 2: $MODULE.text
col 3: TaintedString
col 7: ""
```
--------------------------------
### CPU
Source: https://nim-lang.org/1.0.0/theindex.html
Represents CPU-related examples.
```APIDOC
## CPU
### Description
Represents CPU-related examples.
### Module
- `Examples`
```
--------------------------------
### skLabel Example
Source: https://nim-lang.org/1.0.0/idetools.html
Example output for a label, showing its qualified name and empty type/docstring.
```nim
proc test(text: string) =
var found = -1
block loops:
--> col 2: $MODULE.test.loops
col 3: ""
col 7: ""
```
--------------------------------
### SSL Initialization and Configuration
Source: https://nim-lang.org/1.0.0/openssl.html
Procedures for initializing the SSL library, loading error strings, and configuring SSL contexts.
```APIDOC
## SSL_library_init
### Description
Initializes SSL using OPENSSL_init_ssl for OpenSSL >= 1.1.0, otherwise uses SSL_library_init.
### Signature
```nim
proc SSL_library_init(): cint {...}{.discardable, raises: [Exception], tags: [RootEffect].}
```
```
```APIDOC
## SSL_load_error_strings
### Description
Loads the SSL error strings.
### Signature
```nim
proc SSL_load_error_strings() {...}{.raises: [Exception], tags: [RootEffect].}
```
```
```APIDOC
## OpenSSL_add_all_algorithms
### Description
Adds all available OpenSSL algorithms.
### Signature
```nim
proc OpenSSL_add_all_algorithms() {...}{.raises: [Exception], tags: [RootEffect].}
```
```
```APIDOC
## SSL_CTX_new
### Description
Creates a new SSL context using the specified SSL method.
### Parameters
#### Path Parameters
- **meth** (PSSL_METHOD) - Description of the SSL method to use.
### Signature
```nim
proc SSL_CTX_new(meth: PSSL_METHOD): SslCtx {...}{.cdecl, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_load_verify_locations
### Description
Loads trusted certificate locations for verifying client certificates.
### Parameters
#### Path Parameters
- **ctx** (SslCtx) - The SSL context.
- **CAfile** (cstring) - Path to a file containing a bundle of trusted CA certificates.
- **CApath** (cstring) - Path to a directory containing trusted CA certificates.
### Signature
```nim
proc SSL_CTX_load_verify_locations(ctx: SslCtx; CAfile: cstring; CApath: cstring): cint {...}{.cdecl, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_set_verify
### Description
Sets the verification mode and callback for the SSL context.
### Parameters
#### Path Parameters
- **s** (SslCtx) - The SSL context.
- **mode** (int) - The verification mode.
- **cb** (proc (a: int; b: pointer): int) - The verification callback procedure.
### Signature
```nim
proc SSL_CTX_set_verify(s: SslCtx; mode: int; cb: proc (a: int; b: pointer): int {...}{.cdecl.}): cint {...}{.cdecl, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_set_cipher_list
### Description
Sets the list of ciphers to be used by the SSL context.
### Parameters
#### Path Parameters
- **s** (SslCtx) - The SSL context.
- **ciphers** (cstring) - A string specifying the cipher list.
### Signature
```nim
proc SSL_CTX_set_cipher_list(s: SslCtx; ciphers: cstring): cint {...}{.cdecl, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_use_certificate_file
### Description
Uses a certificate file for the SSL context.
### Parameters
#### Path Parameters
- **ctx** (SslCtx) - The SSL context.
- **filename** (cstring) - The path to the certificate file.
- **typ** (cint) - The type of the certificate file.
### Signature
```nim
proc SSL_CTX_use_certificate_file(ctx: SslCtx; filename: cstring; typ: cint): cint {...}{.stdcall, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_use_certificate_chain_file
### Description
Uses a certificate chain file for the SSL context.
### Parameters
#### Path Parameters
- **ctx** (SslCtx) - The SSL context.
- **filename** (cstring) - The path to the certificate chain file.
### Signature
```nim
proc SSL_CTX_use_certificate_chain_file(ctx: SslCtx; filename: cstring): cint {...}{.stdcall, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_use_PrivateKey_file
### Description
Uses a private key file for the SSL context.
### Parameters
#### Path Parameters
- **ctx** (SslCtx) - The SSL context.
- **filename** (cstring) - The path to the private key file.
- **typ** (cint) - The type of the private key file.
### Signature
```nim
proc SSL_CTX_use_PrivateKey_file(ctx: SslCtx; filename: cstring; typ: cint): cint {...}{.cdecl, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_check_private_key
### Description
Checks if the private key in the SSL context matches the associated certificate.
### Parameters
#### Path Parameters
- **ctx** (SslCtx) - The SSL context.
### Signature
```nim
proc SSL_CTX_check_private_key(ctx: SslCtx): cint {...}{.cdecl, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_get_ex_new_index
### Description
Gets a new index for storing application-specific data in the SSL context.
### Parameters
#### Path Parameters
- **argl** (clong) - Argument.
- **argp** (pointer) - Argument.
- **new_func** (pointer) - Function pointer.
- **dup_func** (pointer) - Function pointer.
- **free_func** (pointer) - Function pointer.
### Signature
```nim
proc SSL_CTX_get_ex_new_index(argl: clong; argp: pointer; new_func: pointer; dup_func: pointer; free_func: pointer): cint {...}{.cdecl, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_set_ex_data
### Description
Sets application-specific data for the SSL context at a given index.
### Parameters
#### Path Parameters
- **ssl** (SslCtx) - The SSL context.
- **idx** (cint) - The index for the data.
- **arg** (pointer) - The data to set.
### Signature
```nim
proc SSL_CTX_set_ex_data(ssl: SslCtx; idx: cint; arg: pointer): cint {...}{.cdecl, dynlib: DLLSSLName, importc.}
```
```
```APIDOC
## SSL_CTX_get_ex_data
### Description
Gets application-specific data from the SSL context at a given index.
### Parameters
#### Path Parameters
- **ssl** (SslCtx) - The SSL context.
- **idx** (cint) - The index of the data.
### Signature
```nim
proc SSL_CTX_get_ex_data(ssl: SslCtx; idx: cint): pointer {...}{.cdecl, dynlib: DLLSSLName, importc.}
```
```
--------------------------------
### async
Source: https://nim-lang.org/1.0.0/theindex.html
Starts an asynchronous procedure.
```APIDOC
## async
### Description
Starts an asynchronous procedure. The specific implementation depends on the module.
### Signatures
`proc async(prc: untyped): untyped` (Module: `asyncdispatch`)
`proc async(arg: untyped): untyped` (Module: `asyncjs`)
```
--------------------------------
### Integer Modulo Examples
Source: https://nim-lang.org/1.0.0/system.html
Demonstrates the integer modulo operation with various combinations of positive and negative numbers.
```nim
( 7 mod 5) == 2
(-7 mod 5) == -2
( 7 mod -5) == 2
(-7 mod -5) == -2
```
--------------------------------
### Get Filename from JsonParser
Source: https://nim-lang.org/1.0.0/parsejson.html
Gets the filename of the file that the parser processes. This procedure is inlined.
```nim
proc getFilename(my: JsonParser): string {...}{.inline, raises: [], tags: [].}
```
--------------------------------
### init
Source: https://nim-lang.org/1.0.0/mysql.html
Initializes a MySQL connection handle.
```APIDOC
## init
### Description
Initializes a MySQL connection handle.
### Parameters
- **MySQL** (PMySQL) - Required - A pointer to a PMySQL structure to be initialized.
```
--------------------------------
### Construct PEG for Start of Input Anchor
Source: https://nim-lang.org/1.0.0/pegs.html
Creates a PEG that matches the start of the input string.
```nim
proc startAnchor(): Peg {...}{.inline, raises: [], tags: [].}
```
--------------------------------
### Integer Division Examples
Source: https://nim-lang.org/1.0.0/system.html
Illustrates the behavior of integer division with positive and negative numbers.
```nim
( 1 div 2) == 0
( 2 div 2) == 1
( 3 div 2) == 1
( 7 div 3) == 2
(-7 div 3) == -2
( 7 div -3) == -2
(-7 div -3) == 2
```
--------------------------------
### Nim Unix Installation Scripts
Source: https://nim-lang.org/1.0.0/niminst.html
Indicates the presence of installation and uninstallation scripts for Unix-like systems.
```niminst
[Unix]
InstallScript: "yes"
UninstallScript: "yes"
```
--------------------------------
### Execute Program with Argument List and Environment
Source: https://nim-lang.org/1.0.0/posix.html
Replaces the current process with a new program, using an argument list and a custom environment. Requires the "" header and supports varargs.
```nim
proc execle(a1, a2: cstring): cint {...}{
varargs, importc,
header: "".
}
```