<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title>Posts on kdbfaq</title>
		<link>https://kdbfaq.com/posts/</link>
		<description>Recent content in Posts on kdbfaq</description>
		<generator>Hugo -- gohugo.io</generator>
		<language>en-us</language>
		<copyright>This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.</copyright>
		<lastBuildDate>Sun, 22 Nov 2020 23:53:00 +0000</lastBuildDate>
		<atom:link href="https://kdbfaq.com/posts/index.xml" rel="self" type="application/rss+xml" />
		
		<item>
			<title>Is there a free trial version of kdb available for download?</title>
			<link>https://kdbfaq.com/is-there-a-free-trial-version-of-kdb-available-for-download/</link>
			<pubDate>Sun, 22 Nov 2020 23:53:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/is-there-a-free-trial-version-of-kdb-available-for-download/</guid>
			<description>Yes. Note the following license restrictions:
 Usage is limited to personal, non-commercial use. &amp;ldquo;It may be used freely on up to 2 computers, and up to a maximum of 16 cores per computer, but is not licensed for use on any cloud, only personal computers.&amp;rdquo;&amp;quot;  The binary and complete terms of usage are here.</description>
			<content type="html"><![CDATA[<p>Yes. Note the following license restrictions:</p>
<ul>
<li>Usage is limited to personal, non-commercial use.</li>
<li>&ldquo;It may be used freely on up to 2 computers, and up to a maximum of 16 cores per computer, but is not licensed for use on any cloud, only personal computers.&rdquo;&quot;</li>
</ul>
<p>The binary and complete terms of usage are <a href="https://ondemand.kx.com/">here</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How does fby work?</title>
			<link>https://kdbfaq.com/how-does-fby-work/</link>
			<pubDate>Wed, 21 Nov 2012 20:17:26 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-does-fby-work/</guid>
			<description>According to code.kx.com, fby is short for filter-by, and it is commonly used as the q equivalent to SQL’s HAVING clause (though, like where, fby is a q function, and its use is not limited to where clauses).
What fby does is aggregate values from one list based on groups defined in another, parallel, list. For example, suppose we have one list of cities and another list with a few temperature samples for each.</description>
			<content type="html"><![CDATA[<p>According to code.kx.com, <a href="http://code.kx.com/v2/ref/fby" title="code.kx.com">fby</a> is short for filter-by, and it is commonly used as the q equivalent to <!-- raw HTML omitted -->SQL’<!-- raw HTML omitted -->s <!-- raw HTML omitted -->HAVING <!-- raw HTML omitted -->clause (though, like <a href="http://code.kx.com/v2/ref/where" title="code.kx.com">where</a>, <code>fby</code> is a q function, and its use is not limited to where clauses).</p>
<p>What fby does is aggregate values from one list based on groups defined in another, parallel, list. For example, suppose we have one list of cities and another list with a few temperature samples for each. We can use fby to calculate the minimum temperature sample for each city, and then replicate those values at each position for each corresponding city:</p>
<pre><code>q)city:`NY`NY`LA`SF`LA`SF`NY
q)temp:32 31 75 69 70 68 12
q)(min;temp) fby city
12 12 70 68 70 68 12
q)
</code></pre><p>Thus, <!-- raw HTML omitted -->NY’<!-- raw HTML omitted -->s minimum temperature, 12, appears at every index in <code>fby</code>‘s output where <code>`NY</code> appears in <code>city</code>.</p>
<p>At the core of fby (like by) is <a href="http://code.kx.com/v2/ref/group">group</a>, which organizes the distinct values in a list into a dictionary mapping those values to their indices:</p>
<pre><code>q)city:`NY`NY`LA`SF`LA`SF`NY
q)group city
NY| 0 1 6
LA| 2 4
SF| 3 5
q)
</code></pre><p>We can group the temperatures for each city together by indexing <code>temp</code> with the value of the grouped city dictionary:</p>
<pre><code>q)grouped: value group city
q)temp[grouped]
32 31 12
75 70
69 68
q)
</code></pre><p>Note that the result of indexing <code>temp</code> with <code>grouped</code> is a nested list with the same shape as <code>grouped</code>. This is a general principle: the result of an indexing operation has the shape of the index.</p>
<p>Now we can apply an aggregation function to each of the temperature groups:</p>
<pre><code>q)min each temp[grouped]
12 70 68
q)
</code></pre><p>We’re almost there. The real trick of <code>fby</code> is placing each aggregation result into a new list so that each element has the correct value per the grouping list. We can use <a href="https://code.kx.com/q/ref/amend/">@ (functional amend)</a> to get the job done (see also <a href="https://www.kdbfaq.com/how-do-i-use-the-functional-forms-of-apply-and-amend.html">the functional apply/amend faq</a>):</p>
<pre><code>q)@[temp; grouped; :; min each temp[grouped] ]
12 12 70 68 70 68 12
q)
</code></pre><p>The real fby is just slightly more complicated to ensure that the first argument to @ has the correct type.</p>
]]></content>
		</item>
		
		<item>
			<title>What does it mean for a table to be a flipped dictionary?</title>
			<link>https://kdbfaq.com/what-does-it-mean-for-a-table-to-be-a-flipped-dictionary/</link>
			<pubDate>Mon, 29 Oct 2012 01:52:39 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-does-it-mean-for-a-table-to-be-a-flipped-dictionary/</guid>
			<description>Short answer:
A table is a reference to a (column) dictionary.
 The internal representation of a table is nearly identical to that of a dictionary. We can use the flip command to create a table from a dictionary:
q)t: ([] a: 1 2 3; b: 4 5 6; c: 7 8 9) q)d: `a`b`c ! (1 2 3; 4 5 6; 7 8 9) q)t ~ flip d 1b q) In fact, when a dictionary is flip‘ed, the underlying core data structure remains untouched.</description>
			<content type="html"><![CDATA[<p>Short answer:</p>
<p>A table is a reference to a (column) dictionary.</p>
<hr>
<p>The internal representation of a table is nearly identical to that of a dictionary. We can use the <a href="https://code.kx.com/v2/ref/flip/" title="code.kx.com">flip</a> command to create a table from a dictionary:</p>
<pre><code>q)t: ([] a: 1 2 3; b: 4 5 6; c: 7 8 9)
q)d: `a`b`c ! (1 2 3; 4 5 6; 7 8 9)
q)t ~ flip d
1b
q)
</code></pre><p>In fact, when a dictionary is <code>flip</code>‘ed, the underlying core data structure remains untouched. The table itself is a simple, small object that refers to the original dictionary. Using <a href="https://code.kx.com/v2/ref/dotq/#qw-memory-stats">.Q.w</a>, we can measure how much more memory a table takes than the corresponding dictionary:</p>
<pre><code>q).Q.w[]`used         // memory usage baseline
112992j
q)x:`a`b`c!3 3#til 9  // create a small dictionary
q).Q.w[]`used
113424j
q)x:flip x
q).Q.w[]`used         // memory usage delta is
113456j               // just 32 more bytes
q)
</code></pre><p>No matter how large the underlying dictionary is, creating a table is fast and still takes only 32 bytes:</p>
<pre><code>q)x:`a`b`c!3 100000#til 10
q).Q.w[]`used
1686192j
q)x:flip x
q).Q.w[]`used
1686224j          // 32 = 1686224 - 1686192
q)
</code></pre><hr>
<p>Now, Let’s examine how a <strong>keyed table</strong> is related to a dictionary. We start by creating a simple keyed table:</p>
<pre><code>q)t: ([] a: 1 2 3; b: 4 5 6; c: 7 8 9)
q)keyedTable: `a`b xkey t
q)keyedTable
a b| c
---| -
1 4| 7
2 5| 8
3 6| 9
q)keys keyedTable
`a`b
q)
</code></pre><p>Since <code>keyedTable</code> is a table, one might expect it to have the same type as t but instead, q presents the following surprise:</p>
<pre><code>q)type t
98h                  // type table as expected
q)type keyedTable
99h                  // *NOT* 98h
q)
</code></pre><p>Type 99h is the <a href="https://code.kx.com/v2/basics/datatypes/" title="code.kx.com">type number</a> for dictionaries. If <code>keyedTable</code> really is a dictionary, we should be able to extract its <code>key</code> and <code>value</code>:</p>
<pre><code>q)key keyedTable
a b
---
1 4
2 5
3 6
q)value keyedTable
c
-
7
8
9
q)
</code></pre><p>Indeed, <code>keyedTable</code> is a dictionary – one that holds <strong>unkeyed</strong> tables for both its key and its value:</p>
<pre><code>q)type key keyedTable
98h
q)type value keyedTable
98h
q)
</code></pre><p>This suggests that we can create a keyed table by using the <a href="https://code.kx.com/v2/ref/dict/">! (dict)</a> operator with two unkeyed tables:</p>
<pre><code>q)(key keyedTable)!(value keyedTable)
a b| c
---| -
1 4| 7
2 5| 8
3 6| 9
q)
</code></pre><p>Lastly, joining the two flipped tables brings us back to the original dict.</p>
<pre><code>q)(flip key keyedTable),(flip value keyedTable)
a| 1 2 3
b| 4 5 6
c| 7 8 9
q)
</code></pre><p>For more information, see <a href="https://code.kx.com/v2/interfaces/c-client-for-q/">Creating dictionaries and tables from C</a> and <a href="https://code.kx.com/q/ref/join/" title="code.kx.com">, (join)</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I execute a q function call with parameters over IPC?</title>
			<link>https://kdbfaq.com/how-do-i-execute-a-q-function-call-with-parameters-over-ipc/</link>
			<pubDate>Wed, 10 Oct 2012 00:03:16 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-execute-a-q-function-call-with-parameters-over-ipc/</guid>
			<description>Short answer:
q)phandle: hopen `:serverhost:5012 q)phandle (function; arg1; arg2 ..) .. q)hclose phandle q)  To invoke a function in another q process (i.e., a function that already exists in that q process), you need the following:
 a process handle to the other q process, the name of the pre-existing function in the other process, and the parameters you want to pass.  Then all you need to do is to apply the process handle to a list whose first element is the function name (as a symbol) and whose remaining elements are the arguments.</description>
			<content type="html"><![CDATA[<p>Short answer:</p>
<pre><code>q)phandle: hopen `:serverhost:5012
q)phandle (function; arg1; arg2 ..)
..
q)hclose phandle
q)
</code></pre><hr>
<p>To invoke a function in another q process (i.e., a function that already exists in that q process), you need the following:</p>
<ol>
<li>a <a href="https://code.kx.com/q/ref/hopen/">process handle</a> to the other q process,</li>
<li>the name of the pre-existing function in the other process, and</li>
<li>the parameters you want to pass.</li>
</ol>
<p>Then all you need to do is to apply the process handle to a <strong>list</strong> whose first element is the function name (as a symbol) and whose remaining elements are the arguments.</p>
<p>For example, let’s start one q process, which will be our server, listening on <!-- raw HTML omitted -->TCP <!-- raw HTML omitted -->port 5012. In our server, we’ll define a function square (we’ll make the background color different for the server to make it easier to distinguish from the client):</p>
<pre><code>$ q -p 5012             // server
..
q)\p                    // display the listening port
5012
q)square: {x * x}
q)square 3
9
q)
</code></pre><p>Next, we’ll start up another q process (the client), create a process handle connected to the first q process (the server), and request the first process to compute <!-- raw HTML omitted -->square 5<!-- raw HTML omitted -->:</p>
<pre><code>$ q                     // client
..
q)phandle: hopen `:localhost:5012
q)phandle (`square; 5)  // remote execution
25
q)
</code></pre><p>To call a function with more parameters, simply add them to the end of the list. We’ll demonstrate by defining a 2-argument function on the server that calculates the length of a right triangle’s hypotenuse:</p>
<pre><code>q)hypotenuse: {sqrt sum square x,y}   // server
q)hypotenuse[3;4]
5f
q)
</code></pre><pre><code>q)phandle (`hypotenuse; 5; 12)    // client
13f
q)
</code></pre><p>What if the function you’re calling doesn’t take any parameters? For example, we’ll define a function in the server called <!-- raw HTML omitted -->serverTime<!-- raw HTML omitted --> that returns the local time according to the server:</p>
<pre><code>q)serverTime: {[] .z.T}    // server
q)serverTime[]
11:51:34.762
q)
</code></pre><p>You can’t pass zero parameters over <!-- raw HTML omitted -->IPC<!-- raw HTML omitted -->:</p>
<pre><code>q)phandle enlist `serverTime  // a list with just
'length                       // the function name
q)                            // is not allowed
</code></pre><p>However, you can pass whatever you like, and it won’t matter:</p>
<pre><code>q)phandle `serverTime`ignored
11:52:28.537
q)phandle (`serverTime; ())    // () is often used
11:52:40.923
q)phandle (`serverTime; ::)    // so is ::
11:52:47.338
q)
</code></pre><p>See <a href="https://code.kx.com/q/ref/identity/">:: (generic null)</a>.</p>
<p>So far, all of our examples involved a client invoking a predefined function on the server. You can also pass a function defined on the client to be executed on the server. To see this, let’s define a global variable on the server:</p>
<pre><code>q)SERVERGLOBAL: 47     // server
q)
</code></pre><p>Now, on the client, we’ll define a function called getSERVERGLOBAL to retrieve the value of <!-- raw HTML omitted -->SERVERGLOBAL <!-- raw HTML omitted -->on the server. Instead of passing the name of the function (i.e., `getSERVERGLOBAL), we pass the function’s value:</p>
<pre><code>q)getSERVERGLOBAL: {[] SERVERGLOBAL}    // client
q)getSERVERGLOBAL[]
'SERVERGLOBAL                   // not defined here
q)phandle (getSERVERGLOBAL; ::) // note the missing `
47
q)
</code></pre><p>Notice that this operation does not cause getSERVERGLOBAL to become defined on the server:</p>
<pre><code>q)getSERVERGLOBAL                 // server
'getSERVERGLOBAL
q)
</code></pre><p>This technique can be used to run built-in functions and anonymous functions (aka lambdas) on the server as well:</p>
<pre><code>q)phandle (+; 2; 4)                // client
6
q)phandle ({til SERVERGLOBAL - x}; 42)
0 1 2 3 4
q)
</code></pre><p>There is one more way to convey code to the server to run: you can pass the code in a string.</p>
<pre><code>q)phandle &quot;SERVERGLOBAL + 4&quot;      // client
51
q)
</code></pre><p>We prefer passing a function over a string, because – especially as the expression to be passed gets more complex – it’s easier to read.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I use the functional forms of apply and amend?</title>
			<link>https://kdbfaq.com/how-do-i-use-the-functional-forms-of-apply-and-amend/</link>
			<pubDate>Mon, 27 Feb 2012 03:27:37 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-use-the-functional-forms-of-apply-and-amend/</guid>
			<description>Typical qcode operates on all of the elements of a container at once:
q)container: 1 2 3 q)100 * container 100 200 300 q) Sometimes we are interested in only a subset of elements from a container:
q)container: til 10 q)container 0 1 2 3 4 5 6 7 8 9 q)container[where 0 = container mod 2] 0 2 4 6 8 q) Sometimes, however, you need to update particular elements of a structure while leaving the remaining elements unchanged.</description>
			<content type="html"><![CDATA[<p>Typical <!-- raw HTML omitted -->q<!-- raw HTML omitted --> code operates on all of the elements of a container at once:</p>
<pre><code>q)container: 1 2 3
q)100 * container
100 200 300
q)
</code></pre><p>Sometimes we are interested in only a subset of elements from a container:</p>
<pre><code>q)container: til 10
q)container
0 1 2 3 4 5 6 7 8 9
q)container[where 0 = container mod 2]
0 2 4 6 8
q)
</code></pre><p>Sometimes, however, you need to update particular elements of a structure while leaving the remaining elements unchanged. That’s what functional apply and amend are for; they transform specific elements of a container without touching the others. The variations are distinguished by 3 choices:</p>
<ol>
<li><a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@<!-- raw HTML omitted --></a> or <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->.<!-- raw HTML omitted --></a></li>
</ol>
<p>Which operator is used, <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@<!-- raw HTML omitted --></a> or <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->.<!-- raw HTML omitted --></a>, determines the interpretation of the <strong>indices</strong> used to select the elements to transform.</p>
<ol start="2">
<li>container or name</li>
</ol>
<p>The first argument is either the value of a container or the name of a global variable referring to a container. In the former case, a new object is returned; in the latter, the global variable is modified and its name is returned.</p>
<ol start="3">
<li>monadic or dyadic function</li>
</ol>
<p>If the transformation requires additional information beyond that contained in each element itself, that is accomplished by using a dyadic function and supplying the additional information in a fourth argument to the operator.</p>
<p>For a detailed discussion, please see the following faqs:</p>
<p><a href="https://www.kdbfaq.com/how-do-i-use-the-functional-form-of-at-apply.html">Functional @ (apply)</a></p>
<p><a href="https://www.kdbfaq.com/how-do-i-use-the-functional-form-of-dot-apply.html">Functional . (apply)</a></p>
<p>Lastly, note that there is another pair of overloads for <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->.<!-- raw HTML omitted --></a> – each with three arguments – called protected execution, which are invoked when the first argument to <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@<!-- raw HTML omitted --></a> or <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->.<!-- raw HTML omitted --></a> is a function or projection; protected execution is discussed in another <a href="https://www.kdbfaq.com/how-does-protected-execution-or-exception-handling-work-in-q.html">faq</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I use the functional form of @ (at) apply?</title>
			<link>https://kdbfaq.com/how-do-i-use-the-functional-form-of-at-apply/</link>
			<pubDate>Mon, 27 Feb 2012 03:26:40 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-use-the-functional-form-of-at-apply/</guid>
			<description>Short answer:
1. @[container; indices; function] 2. @[container; indices; function; second_args] (Note that there is another overload for @ with three arguments, called protected execution, which is invoked when the first argument to @ is a function or projection; protected execution is discussed in another faq.)
 In the 3-argument case, qapplies functionto those elements of containerspecified by indices, leaving the rest of containeralone. In other words, the behavior of 3-argument @ (apply) resembles that of the following function:</description>
			<content type="html"><![CDATA[<p>Short answer:</p>
<pre><code>1. @[container; indices; function]
2. @[container; indices; function; second_args]
</code></pre><p>(Note that there is another overload for <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@<!-- raw HTML omitted --></a> with three arguments, called protected execution, which is invoked when the first argument to <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@<!-- raw HTML omitted --></a> is a function or projection; protected execution is discussed in another <a href="https://www.kdbfaq.com/how-does-protected-execution-or-exception-handling-work-in-q.html">faq</a>.)</p>
<hr>
<p>In the 3-argument case, <!-- raw HTML omitted -->q<!-- raw HTML omitted --> applies <!-- raw HTML omitted -->function<!-- raw HTML omitted --> to those elements of <!-- raw HTML omitted -->container<!-- raw HTML omitted --> specified by <!-- raw HTML omitted -->indices<!-- raw HTML omitted -->, leaving the rest of <!-- raw HTML omitted -->container<!-- raw HTML omitted --> alone. In other words, the behavior of 3-argument <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (apply)<!-- raw HTML omitted --></a> resembles that of the following function:</p>
<p>Although this model breaks down when the first argument is a global variable name, it is very helpful in understanding what is going on even in that case. Let’s look at a couple of simple examples to clarify this:</p>
<pre><code>q)list: 1 + til 8
q)list
1 2 3 4 5 6 7 8
q)@[list; 0; neg]         / negate element 0
-1 2 3 4 5 6 7 8
q)list                    / list remains unmodified
1 2 3 4 5 6 7 8
q)@[list; 1 3 4; {x * x}] / square elements 1, 3, and 4
1 4 3 16 25 6 7 8
q)
</code></pre><p>The diagram below illustrates the last example above:</p>
<p><img src="/images/functional_at.jpg" alt="at"></p>
<p>Because the new container has the same type and shape as the original, <!-- raw HTML omitted -->function<!-- raw HTML omitted --> must return the same type as its argument, unless the container is a mixed list (i.e., type 0):</p>
<pre><code>q)@[list; 4 5 6 7; {x div 2}] / list is an int list
1 2 3 4 2 3 3 4
q)@[list; 4 5 6 7; {x % 2}]   / but % returns float
'type
q)mixed_list: 1 2, `3`4
q)type mixed_list
0h
q)@[mixed_list; 0 3; string] / anything goes with type 0
,&quot;1&quot;
2
`3
,&quot;4&quot;
q)
</code></pre><p>Next, we’ll consider the second case listed at the top of this faq. When <!-- raw HTML omitted -->function<!-- raw HTML omitted --> is dyadic and a fourth argument is supplied, <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (apply)<!-- raw HTML omitted --></a> behaves like the following function:</p>
<p>The basic idea is still the same, i.e., to transform selected elements while leaving the rest of the container intact. The difference is that, instead of <!-- raw HTML omitted -->function<!-- raw HTML omitted --> being modified by <a href="https://code.kx.com/q/ref/each/"><!-- raw HTML omitted -->each<!-- raw HTML omitted --></a>, it is modified by <a href="https://code.kx.com/q/ref/overloads/#quote"><!-- raw HTML omitted -->‘(each-both)<!-- raw HTML omitted --></a> (also see this <a href="https://www.kdbfaq.com/how-does-each-both-aka-multivalent-each-work.html">faq on each-both and multivalent each</a>), so that the selected elements of <!-- raw HTML omitted -->container<!-- raw HTML omitted --> are paired up with the corresponding elements from <!-- raw HTML omitted -->second_args<!-- raw HTML omitted -->:</p>
<pre><code>q)@[list; 1 3 5 7; +; 10 20 30 40]
1 12 3 24 5 36 7 48
q)@[list; (1 3 5 7; 0 2 4 6); *; 2 -2]
-2 4 -6 8 -10 12 -14 16
q)
</code></pre><p>One function often used with 4-argument <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (apply)<!-- raw HTML omitted --></a>, is <a href="https://code.kx.com/q/ref/amend/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a>. We can replace selected elements with a certain value (or values) as follows:</p>
<pre><code>q)list: 1 + til 8
q)@[list; 1 3 5 7; :; 47]
1 47 3 47 5 47 7 47
q)@[list; 1 3 5 7; :; 10 20 30 40]
1 10 3 20 5 30 7 40
q)
</code></pre><p>It might appear that the above example exposes a flaw in our model, <!-- raw HTML omitted -->apply_dyadic<!-- raw HTML omitted -->, of <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (apply)<!-- raw HTML omitted --></a>. However, recall that, <a href="https://www.kdbfaq.com/when-does-amend-not-modify-its-first-argument.html"><!-- raw HTML omitted -->when modified by an adverb, : (amend)<!-- raw HTML omitted --> does not modify its first argument:</a></p>
<pre><code>q):'[list 1 2 3; 20 30 40]
20 30 40                     / :' returns its 2nd argument
q)list                       / without modifying its 1st
1 2 3 4 5 6 7 8
q)
</code></pre><p>Where our models do break down is when, as alluded to earlier, the first argument is the name of global variable referring to a container, rather than the value of a container. In that case, the mechanics of the operation are the same, but original container is modified, and the return value is the name:</p>
<pre><code>q)list: 1 + til 8
q)@[`list; 0; neg]
`list
q)list
-1 2 3 4 5 6 7 8
q)
</code></pre><p>This behavior is handy for writing functions of your own that work in both scenarios – either creating a new value or modifying one in place – like the following:</p>
<hr>
<p>We can also use <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@<!-- raw HTML omitted --></a> to apply a function to selected entries in a dictionary:</p>
<pre><code>q)dictionary: `a`b`c`d ! `1`2, 3 4
q)dictionary
a| `1
b| `2
c| 3
d| 4
q)@[dictionary; `a`b; {&quot;I&quot;$ string x}]
a| 1
b| 2
c| 3
d| 4
q)
</code></pre><p>Tables can be transformed as well. Consider the following table:</p>
<pre><code>q)t: ([] col1: `foo`bar`baz; col2: 5 10 15f)
q)t
col1 col2
---------
foo  5
bar  10
baz  15
q)
</code></pre><p>Recall that each row of a table is a dictionary:</p>
<pre><code>q)t 0
col1| `foo
col2| 5f
q)
</code></pre><p>Thus, we can use <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (apply)<!-- raw HTML omitted --></a> to accomplish an <a href="https://code.kx.com/q/ref/update/"><!-- raw HTML omitted -->update<!-- raw HTML omitted --></a> in the following manner:</p>
<pre><code>q)update col2 - 4 from t where i &amp;gt; 0
col1 col2
---------
foo  5
bar  6
baz  11
q)@[t; 1 2; {[row] row[`col2] -: 4; row}]
col1 col2
---------
foo  5
bar  6
baz  11
q)
</code></pre><p>We could also obtain the previous result using nested calls to <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (apply)<!-- raw HTML omitted --></a>:</p>
<pre><code>q)@[t; 1 2; @[; `col2; -[; 4]]]
col1 col2
---------
foo  5
bar  6
baz  11
q)
</code></pre><p>Since we can index tables using column names, we can double all of the entries in <!-- raw HTML omitted -->col2<!-- raw HTML omitted --> as follows:</p>
<pre><code>q)@[t; `col2; 2*]
col1 col2
---------
foo  10
bar  20
baz  30
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>How do I use the functional form of . (dot) apply?</title>
			<link>https://kdbfaq.com/how-do-i-use-the-functional-form-of-dot-apply/</link>
			<pubDate>Mon, 27 Feb 2012 03:20:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-use-the-functional-form-of-dot-apply/</guid>
			<description>Short answer:
1. .[container; indices; function] 2. .[container; indices; function; second_args] Note that there is another overload for . (apply) with three arguments, called protected execution, which is invoked when the first argument to . (apply) is a function or projection; protected execution is discussed in another faq.
 In the 3-argument case, qapplies functionto those elements of containerspecified by indices, leaving the rest of containeralone.
The behavior of . (apply) is very similar to that of @ (apply) (which is described in another faq).</description>
			<content type="html"><![CDATA[<p>Short answer:</p>
<pre><code>1. .[container; indices; function]
2. .[container; indices; function; second_args]
</code></pre><p>Note that there is another overload for <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> with three arguments, called protected execution, which is invoked when the first argument to <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> is a function or projection; protected execution is discussed in another <a href="https://www.kdbfaq.com/how-does-protected-execution-or-exception-handling-work-in-q.html">faq</a>.</p>
<hr>
<p>In the 3-argument case, <!-- raw HTML omitted -->q<!-- raw HTML omitted --> applies <!-- raw HTML omitted -->function<!-- raw HTML omitted --> to those elements of <!-- raw HTML omitted -->container<!-- raw HTML omitted --> specified by <!-- raw HTML omitted -->indices<!-- raw HTML omitted -->, leaving the rest of <!-- raw HTML omitted -->container<!-- raw HTML omitted --> alone.</p>
<p>The behavior of <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> is very similar to that of <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (apply)<!-- raw HTML omitted --></a> (which is described in <a href="https://www.kdbfaq.com/how-do-i-use-the-functional-form-of-at-apply.html">another faq</a>). The only difference between <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (apply)<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> is that the indices, in the case of <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a>, are applied at depth along the dimensions of the container. The following code behaves like <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> for a two-dimensional container:</p>
<p>To explore the different treatment of the <!-- raw HTML omitted -->indices<!-- raw HTML omitted --> argument between <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (apply)<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a>, we’ll consider the simplest, multi-dimensional container: a two-dimensional list, aka a matrix.</p>
<pre><code>q)matrix: 0N 4 # til 16
q)matrix
0  1  2  3
4  5  6  7
8  9  10 11
12 13 14 15
q)
</code></pre><p>We can use simple indexing of <!-- raw HTML omitted -->matrix<!-- raw HTML omitted --> with both <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->@ (index)<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (index)<!-- raw HTML omitted --></a> to illustrate the difference:</p>
<pre><code>q)@[matrix; 0]           // fetch row 0
0 1 2 3
q)@[matrix; 0 0]         // fetch matrix[0;0] fails.  why?
0 1 2 3                  // @ cannot index more
0 1 2 3                  // than one dimension
q)
q).[matrix; 0 0]         // dot indexes &quot;at depth&quot;
0
q)
</code></pre><p>Now let’s apply a function to selected elements from <!-- raw HTML omitted -->matrix<!-- raw HTML omitted --> using <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a>:</p>
<pre><code>q).[matrix; (0; ::); 100+]
100 101 102 103
4   5   6   7
8   9   10  11
12  13  14  15
q).[matrix; 0 0; 100+]
100 1  2  3
4   5  6  7
8   9  10 11
12  13 14 15
q).[matrix; (::; 0); 100+]
100 1  2  3
104 5  6  7
108 9  10 11
112 13 14 15
q)
</code></pre><p>Notice that we used <a href="https://code.kx.com/q/ref/overloads/#colon-colon"><!-- raw HTML omitted -->::<!-- raw HTML omitted --></a> in order to elide a dimension from the indices.</p>
<p>We can also use <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> with dictionaries of lists:</p>
<pre><code>q)dict: `a`b ! (1 2 3; 4 5 6)
q).[dict; (`a; 0); 50*]
a| 50 2 3
b| 4  5 6
q).[dict; (::; 1); 50*]
a| 1 100 3
b| 4 250 6
q)
</code></pre><p>The general case of applying a function at depth via functional <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> is not implemented for tables:</p>
<pre><code>q)t: ([] a: `foo`bar; b: 5 10f)
q).[t; (0; `b); %[; 5]]
'nyi
q).[t; (`b; 0); %[; 5]]
'nyi
q)
</code></pre><p>The <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->.<!-- raw HTML omitted --></a> form of apply has another trick up its sleeve: the empty list index. When the second parameter to <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> is <!-- raw HTML omitted -->()<!-- raw HTML omitted -->, the entire container is passed to <!-- raw HTML omitted -->function<!-- raw HTML omitted --> in a single invocation, as the following example demonstrates:</p>
<pre><code>q).[matrix; (); 0N!]
(0 1 2 3;4 25 36 7;8 81 100 11;12 13 14 15)
0  1  2   3
4  25 36  7
8  81 100 11
12 13 14  15
q)
</code></pre><p>When using <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> in this manner, we can return anything from <!-- raw HTML omitted -->function<!-- raw HTML omitted -->; the type and shape do not matter:</p>
<pre><code>q).[matrix; (); {&quot;hello&quot;}]
&quot;hello&quot;
q)
</code></pre><hr>
<p>Returning to the second case, when <!-- raw HTML omitted -->function<!-- raw HTML omitted --> is dyadic, <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> takes a fourth argument (named <!-- raw HTML omitted -->second_args<!-- raw HTML omitted --> in our example), and each indexed element of <!-- raw HTML omitted -->container<!-- raw HTML omitted --> is paired with the corresponding element of <!-- raw HTML omitted -->second_args<!-- raw HTML omitted -->. This means that <!-- raw HTML omitted -->second_args<!-- raw HTML omitted --> must conform to <!-- raw HTML omitted -->indices<!-- raw HTML omitted --> (or be an atom). The following function expresses this behavior:</p>
<p>(Also see this <a href="https://www.kdbfaq.com/how-does-each-both-aka-multivalent-each-work.html">faq on each-both and multivalent each</a>.)</p>
<p>We can demonstrate how this works by altering the center square of <!-- raw HTML omitted -->matrix<!-- raw HTML omitted -->:</p>
<pre><code>q).[matrix; (1 2; 1 2); *; (10 20; 100 200)]
0  1   2    3
4  50  120  7
8  900 2000 11
12 13  14   15
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>How does each-both (aka multivalent each) work?</title>
			<link>https://kdbfaq.com/how-does-each-both-aka-multivalent-each-work/</link>
			<pubDate>Sun, 26 Feb 2012 21:34:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-does-each-both-aka-multivalent-each-work/</guid>
			<description>Short answer: It takes a function of N operands and creates a new function that applies the original to each set of corresponding elements from N same-length vectors.
 We can categorize the ways in which qhandles vectors into the following three groups:
  Treat the vector as a single entity.
  Perform an operation on each element of a vector.
  Perform an operation on each set of corresponding elements from multiple vectors of the same length.</description>
			<content type="html"><![CDATA[<p>Short answer: It takes a function of N operands and creates a new function that applies the original to each set of corresponding elements from N same-length vectors.</p>
<hr>
<p>We can categorize the ways in which <!-- raw HTML omitted -->q<!-- raw HTML omitted --> handles vectors into the following three groups:</p>
<ol>
<li>
<p>Treat the vector as a single entity.</p>
</li>
<li>
<p>Perform an operation on each element of a vector.</p>
</li>
<li>
<p>Perform an operation on each set of corresponding elements from <strong>multiple</strong> vectors of the <strong>same length</strong>.</p>
</li>
</ol>
<p>We use <a href="https://code.kx.com/q/ref/maps/#each-parallel"><!-- raw HTML omitted -->‘ (each-both)<!-- raw HTML omitted --></a> to ask <!-- raw HTML omitted -->q<!-- raw HTML omitted --> to apply a function in the third manner.</p>
<p>Let’s review a few examples to distinguish the three forms of vector handling described above. Consider the <a href="https://code.kx.com/q/ref/join/"><!-- raw HTML omitted -->, (join)<!-- raw HTML omitted --></a> operator, which takes two arguments and concatenates them. When used by itself, <a href="https://code.kx.com/q/ref/join/"><!-- raw HTML omitted -->, (join)<!-- raw HTML omitted --></a> treats a vector as a single entity:</p>
<pre><code>q)1 , 2
1 2
q)1 2 3 , 10
1 2 3 10
q)1 , 10 20 30
1 10 20 30
q)1 2 , 10 20 30
1 2 10 20 30
q)
</code></pre><p>Notice that the lengths of the two vectors to be joined doesn’t matter; in fact, they don’t have to be vectors.</p>
<p>Next, as an example of applying the same operation to each element of a vector, we can use <a href="https://code.kx.com/q/ref/maps/#each-left-and-each-right"><!-- raw HTML omitted -->\: (each-left)<!-- raw HTML omitted --></a> to append the letter “e” to each element in a vector of strings:</p>
<pre><code>q)(&quot;car&quot;; &quot;far&quot;; &quot;mar&quot;) ,\: &quot;e&quot;
&quot;care&quot;
&quot;fare&quot;
&quot;mare&quot;
q)
</code></pre><p>Lastly, we’ll use <a href="https://code.kx.com/q/ref/maps/#each-parallel"><!-- raw HTML omitted -->‘ (each-both)<!-- raw HTML omitted --></a> to join corresponding elements from two vectors of the same length (like zip from <a href="http://docs.python.org/library/functions.html#zip">Python</a> or <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#g:19">Haskell</a>):</p>
<pre><code>q)1 2 3 ,' 10 20 30
1 10
2 20
3 30
q)
</code></pre><p>As an aside, the use of <a href="https://code.kx.com/q/ref/maps/#each-parallel"><!-- raw HTML omitted -->‘ (each-both)<!-- raw HTML omitted --></a> is not needed for many built-in functions in <!-- raw HTML omitted -->q<!-- raw HTML omitted -->, because those functions (sometimes referred to as atomic functions in kx documentation) automatically assume that this is the desired behavior when presented with same-length vectors as arguments. The <!-- raw HTML omitted -->+<!-- raw HTML omitted --> operator is a good example:</p>
<pre><code>q)1 2 3 + 10 20 30
11 22 33
q)
</code></pre><p>Even a user defined function, if that function’s body is exclusively made up of applications of atomic functions, does not require the use of <a href="https://code.kx.com/q/ref/maps/#each-parallel"><!-- raw HTML omitted -->‘ (each-both)<!-- raw HTML omitted --></a> to display this behavior:</p>
<pre><code>q)atomic: {[x; y] (x * x) + y * y}
q)atomic'[1 2 3; 10 20 30]
101 404 909
q)atomic[1 2 3; 10 20 30]  // ' not required
101 404 909
q){[x; y] atomic[x; y]}[1 2 3; 10 20 30]
101 404 909
q)
</code></pre><p>The last example shows that such user defined atomic functions are truly atomic in the eyes of <!-- raw HTML omitted -->q<!-- raw HTML omitted -->.</p>
<p>The following code simulates the behavior of <a href="https://code.kx.com/q/ref/maps/#each-parallel"><!-- raw HTML omitted -->‘ (each-both)<!-- raw HTML omitted --></a> – on functions of two arguments – by creating a new function (that acts on vectors) from the function passed as an argument:</p>
<p>However, <a href="https://code.kx.com/q/ref/maps/#each-parallel"><!-- raw HTML omitted -->‘ (each-both)<!-- raw HTML omitted --></a> doesn’t stop at two lists, which is why it is sometimes called multivalent each. Suppose we need to generate a bunch of <a href="http://www.w3schools.com/tags/tag_a.asp">html hyperlinks</a> for a web page we are creating on-the-fly (perhaps in a <a href="http://code.kx.com/wiki/Reference/dotzdotpp">custom http <!-- raw HTML omitted -->POST <!-- raw HTML omitted -->handler</a>). Each link needs to have its own styling, so we want to add a distinct <a href="https://www.w3schools.com/html/html_classes.asp">class attribute</a> to each anchor tag.</p>
<p>The <a href="https://code.kx.com/q/ref/doth/">.h namespace</a> includes numerous functions for generating <!-- raw HTML omitted -->HTML. <!-- raw HTML omitted --> The one we need is the <a href="https://code.kx.com/q/ref/doth/">.h.htac (html tag with attributes and closing tag)</a> function:</p>
<p> </p>
<pre><code>q).h.htac[`a; `class`href ! (&quot;myclass&quot;; &quot;kdbfaq.com&quot;); &quot;kdbfaq&quot;]
&quot;&amp;lt;a class=\&quot;myclass\&quot; href=\&quot;kdbfaq.com\&quot;&amp;gt;kdbfaq&amp;lt;/a&amp;gt;&quot;
q)
</code></pre><p>Let’s wrap <a href="https://code.kx.com/q/ref/doth/">.h.htac (html tag with attributes and closing tag)</a> up in a function to create a styled link:</p>
<p> </p>
<p>We’ll store the information we need to generate the links in a table:</p>
<p> </p>
<pre><code>q)links
name        url                    class
----------------------------------------
&quot;kx&quot;        &quot;http://kx.com&quot;        &quot;c1&quot;
&quot;Wikipedia&quot; &quot;http://wikipedia.com&quot; &quot;c2&quot;
&quot;kdbfaq&quot;    &quot;http://kdbfaq.com&quot;    &quot;c3&quot;
q)
</code></pre><p>Now we can use <a href="https://code.kx.com/q/ref/maps/#each-parallel"><!-- raw HTML omitted -->‘ (multivalent each)<!-- raw HTML omitted --></a> to generate all the links easily:</p>
<pre><code>q)styled_link'[links `name; links `url; links `class]
&quot;&amp;lt;a class=\&quot;c1\&quot; href=\&quot;http://kx.com\&quot;&amp;gt;kx&amp;lt;/a&amp;gt;&quot;
&quot;&amp;lt;a class=\&quot;c2\&quot; href=\&quot;http://wikipedia.com\&quot;&amp;gt;Wikipedia&amp;lt;/a&amp;gt;&quot;
&quot;&amp;lt;a class=\&quot;c3\&quot; href=\&quot;http://kdbfaq.com\&quot;&amp;gt;kdbfaq&amp;lt;/a&amp;gt;&quot;
q)
</code></pre><p>Or, alternately, we can combine <a href="https://code.kx.com/q/ref/maps/#each-parallel"><!-- raw HTML omitted -->‘ (multivalent each)<!-- raw HTML omitted --></a> with <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a> for a shorter, more general approach to applying a function to each row in a table:</p>
<pre><code>q)styled_link .' flip value flip links
&quot;&amp;lt;a class=\&quot;c1\&quot; href=\&quot;http://kx.com\&quot;&amp;gt;kx&amp;lt;/a&amp;gt;&quot;
&quot;&amp;lt;a class=\&quot;c2\&quot; href=\&quot;http://wikipedia.com\&quot;&amp;gt;Wikipedia&amp;lt;/a&amp;gt;&quot;
&quot;&amp;lt;a class=\&quot;c3\&quot; href=\&quot;http://kdbfaq.com\&quot;&amp;gt;kdbfaq&amp;lt;/a&amp;gt;&quot;
q)
</code></pre><p>On more wrinkle: sometimes <a href="https://code.kx.com/q/ref/maps/#each-parallel"><!-- raw HTML omitted -->‘ (each)<!-- raw HTML omitted --></a> is used where <a href="https://code.kx.com/q/ref/maps/#each-left-and-each-right"><!-- raw HTML omitted -->\: (each-left)<!-- raw HTML omitted --></a> or <a href="https://code.kx.com/q/ref/maps/#each-left-and-each-right"><!-- raw HTML omitted -->/: (each-right)<!-- raw HTML omitted --></a> would be more explicit. For instance, our earlier example in which we appended the letter <!-- raw HTML omitted -->“e”<!-- raw HTML omitted --> to each element of a list of strings could have been written as follows:</p>
<pre><code>q)(&quot;car&quot;; &quot;far&quot;; &quot;mar&quot;) ,' &quot;e&quot;
&quot;care&quot;
&quot;fare&quot;
&quot;mare&quot;
q)
</code></pre><p>We find the original, more explicit form, quicker and easier to read.</p>
]]></content>
		</item>
		
		<item>
			<title>How can I capture STDOUT, STDERR and the exit status of a system command invoked from q?</title>
			<link>https://kdbfaq.com/how-can-i-capture-stdout-stderr-and-the-exit-status-of-a-system-command-invoked-from-q/</link>
			<pubDate>Mon, 23 Jan 2012 01:26:15 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-capture-stdout-stderr-and-the-exit-status-of-a-system-command-invoked-from-q/</guid>
			<description>Short answer: 2&amp;gt;&amp;amp;1(i.e., redirect STDERRto STDOUT), echo $?, and add parentheses.
Note: This applies to bash, and has not been tested in csh, ksh, etc.
 We can invoke arbitrary external programs from qusing the system command. For example:
q)system &amp;quot;echo Hello, world!&amp;quot; &amp;quot;Hello, world!&amp;quot; q) External programs often signal errors by returning a non-zero exit code, which is stored in the shell variable ?:
$ ls nonexistent_file ls: nonexistent_file: No such file or directory $ echo $?</description>
			<content type="html"><![CDATA[<p>Short answer: <!-- raw HTML omitted -->2&gt;&amp;1<!-- raw HTML omitted --> (i.e., redirect <!-- raw HTML omitted --><!-- raw HTML omitted -->STDERR<!-- raw HTML omitted --><!-- raw HTML omitted --> to <!-- raw HTML omitted --><!-- raw HTML omitted -->STDOUT<!-- raw HTML omitted --><!-- raw HTML omitted -->), <!-- raw HTML omitted -->echo $?<!-- raw HTML omitted -->, and <strong>add parentheses</strong>.</p>
<p>Note: This applies to bash, and has not been tested in csh, ksh, etc.</p>
<hr>
<p>We can invoke arbitrary external programs from <!-- raw HTML omitted -->q<!-- raw HTML omitted --> using the <a href="http://code.kx.com/wiki/Reference/system">system</a> command. For example:</p>
<pre><code>q)system &quot;echo Hello, world!&quot;
&quot;Hello, world!&quot;
q)
</code></pre><p>External programs often signal errors by returning a non-zero exit code, which is stored in the shell variable <!-- raw HTML omitted -->?<!-- raw HTML omitted -->:</p>
<pre><code>$ ls nonexistent_file
ls: nonexistent_file: No such file or directory
$ echo $?
1
$ foo
-bash: foo: command not found
$ echo $?
127
$
</code></pre><p>When an external program called from <a href="http://code.kx.com/wiki/Reference/system">system</a> in <!-- raw HTML omitted -->q<!-- raw HTML omitted --> runs into a situation like this, <!-- raw HTML omitted -->q<!-- raw HTML omitted --> detects the non-zero exit code from the child process and raises a signal, <!-- raw HTML omitted -->‘os<!-- raw HTML omitted -->:</p>
<pre><code>q)system &quot;ls nonexistent_file&quot;
ls: nonexistent_file: No such file or directory
'os
q)
</code></pre><p>When trying out ideas at the console as in the above example, the full details of the error are available on the screen. Getting those error details programmatically is a bit trickier, however. Consider the following function, in which we use <a href="https://www.kdbfaq.com/how-does-protected-execution-or-exception-handling-work-in-q.html">protected execution</a> to invoke an error handler when the <!-- raw HTML omitted -->‘os<!-- raw HTML omitted --> signal is raised:</p>
<pre><code>use_protected_execution: {[]
  : @[system;
  &quot;ls nonexistent_file&quot;;
  {[error_info] -1 &quot;error is &quot;, error_info;}];
}
</code></pre><p>The error handler in <!-- raw HTML omitted -->use_protected_execution<!-- raw HTML omitted --> knows only that an operating system error occurred. None of the error details are available within the code:</p>
<pre><code>q)use_protected_execution[]
ls: nonexistent_file: No such file or directory  // invisible
error is os
q)
</code></pre><p>We can improve the situation somewhat by appending <!-- raw HTML omitted -->“; echo $?”<!-- raw HTML omitted --> to the command:</p>
<pre><code>q)result: system &quot;ls nonexistent_file; echo $?&quot;
q)result
,&quot;1&quot;    // actually a list of strings
q)
</code></pre><p>This enables us to distinguish error codes as follows:</p>
<pre><code>distinguish_error_codes: {[]
 result: system &quot;ls nonexistent_file; echo $?&quot;;
 exit_code: &quot;I&quot; $ last result;
 $[0   = exit_code;
   ; // everything's alright
   1   = exit_code;
   ; // minor problem
   2   = exit_code;
   ; // major problem
   127 = exit_code;
   ; // command not found
   / else
   // unhandled exit code
]}
</code></pre><p>What we really want, though, is to capture the output sent by the failed command to <!-- raw HTML omitted --><!-- raw HTML omitted -->STDERR<!-- raw HTML omitted --><!-- raw HTML omitted -->. You might expect <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html">the usual shell redirection syntax</a> to do the job:</p>
<pre><code>q)result: system &quot;ls nonexistent_file 2&gt;&amp;1; echo $?&quot;
ls: nonexistent_file: No such file or directory
q)result
,&quot;1&quot;
q)
</code></pre><p>No such luck. The trick is to put parentheses around the whole thing:</p>
<pre><code>q)result: system &quot;(ls nonexistent_file 2&gt;&amp;1; echo $?)&quot;
q)result
&quot;ls: nonexistent_file: No such file or directory&quot;
,&quot;1&quot;
q)
</code></pre><p>We can wrap all this up in a handy function that, instead of raising <!-- raw HTML omitted -->os<!-- raw HTML omitted -->, raises the descriptive message output to <!-- raw HTML omitted --><!-- raw HTML omitted -->STDERR<!-- raw HTML omitted --><!-- raw HTML omitted --> by the child process:</p>
<pre><code>call_external: {[command]
  result: system &quot;(&quot;, command, &quot; 2&gt;&amp;1; echo $?)&quot;;
  exit_code: &quot;I&quot; $ last result;
  if [0 &lt; exit_code;
      ' raze -1 _ result];
  -1 _ result}
</code></pre>]]></content>
		</item>
		
		<item>
			<title>Why can’t I index some elements of a dictionary?</title>
			<link>https://kdbfaq.com/why-cant-i-index-some-elements-of-a-dictionary/</link>
			<pubDate>Sun, 23 Oct 2011 21:57:56 +0000</pubDate>
			
			<guid>https://kdbfaq.com/why-cant-i-index-some-elements-of-a-dictionary/</guid>
			<description>Short answer: Check that the keys of your dictionary are uniformly atoms or lists, not both.
 To experiment, let’s construct two dictionaries, one with atomic keys and one with list keys.
q)dict1: `keya`keyb`keyc ! 10 20 30 q)dict1 // dictionary with atomic keys keya| 10 keyb| 20 keyc| 30 q)dict2: (`keya1`keya2; `keyb1`keyb2; `keyc1`keyc2) ! 1 2 3 q)dict2 // dictionary with list keys keya1 keya2| 1 keyb1 keyb2| 2 keyc1 keyc2| 3 q)dict1[`keya] // index by atom key 10 q)dict2[`keya1`keya2] // index by list key 1 q) Note how dict1contains a keys made of exclusively of atoms, and dict2contains keys that are lists.</description>
			<content type="html"><![CDATA[<p>Short answer: Check that the keys of your dictionary are uniformly atoms or lists, not both.</p>
<hr>
<p>To experiment, let’s construct two dictionaries, one with atomic keys and one with list keys.</p>
<pre><code>q)dict1: `keya`keyb`keyc ! 10 20 30
q)dict1                // dictionary with atomic keys
keya| 10
keyb| 20
keyc| 30
q)dict2: (`keya1`keya2; `keyb1`keyb2; `keyc1`keyc2) ! 1 2 3
q)dict2                // dictionary with list keys
keya1 keya2| 1
keyb1 keyb2| 2
keyc1 keyc2| 3
q)dict1[`keya]         // index by atom key
10
q)dict2[`keya1`keya2]  // index by list key
1
q)
</code></pre><p>Note how <!-- raw HTML omitted -->dict1<!-- raw HTML omitted --> contains a keys made of exclusively of atoms, and <!-- raw HTML omitted -->dict2<!-- raw HTML omitted --> contains keys that are lists.</p>
<p>Now let’s consider a dictionary whose keys are both atoms and lists:</p>
<pre><code>q)dict3: (`keya1; `keyb1`keyb2; `keyc1`keyc2) ! 1 2 3
q)key dict3
`keya1                // The first key is an atomic symbol,
`keyb1`keyb2          // while the rest of the keys are
`keyc1`keyc2          // lists of symbols.
q)dict3[`keya1]       // The first key indexes fine,
1
q)dict3[`keyb1`keyb2] // but the remaining keys are broken;
0N 0N
q)dict3[`keyc1`keyc2] // they are treated as multiple keys.
0N 0N
q)
</code></pre><p>Even though the keys are present they cannot be found by a dictionary lookup. Reverse lookup does work:</p>
<pre><code>q)dict3
`keya1      | 1    // ok
`keyb1`keyb2| 2    // broken
`keyc1`keyc2| 3    // broken
q)dict3 ? 2
`keyb1`keyb2
q)dict3 ? 3
`keyc1`keyc2
q)
</code></pre><p>Analogous behavior can be observed when searching a list that contains both atoms and lists:</p>
<pre><code>q)list: key dict3
q)list ? `keya1
0q)list ? `keyb1`keyb2
3 3
q)
</code></pre><p>Always remember that a dictionary lookup is essentially the following:</p>
<pre><code>q)lookup: {[dict; thekey] value[dict] @ key[dict] ? thekey}
q)
</code></pre><p>Sometimes types in <!-- raw HTML omitted -->q<!-- raw HTML omitted --> behave differently depending on the data contained within. Take a look at <a href="https://www.kdbfaq.com/why-does-the-type-of-null-returned-by-a-failed-dictionary-key-lookup-vary.html">this related faq</a> to read more.</p>
]]></content>
		</item>
		
		<item>
			<title>Why does the type of null returned by a failed dictionary key lookup vary?</title>
			<link>https://kdbfaq.com/why-does-the-type-of-null-returned-by-a-failed-dictionary-key-lookup-vary/</link>
			<pubDate>Sun, 23 Oct 2011 21:57:25 +0000</pubDate>
			
			<guid>https://kdbfaq.com/why-does-the-type-of-null-returned-by-a-failed-dictionary-key-lookup-vary/</guid>
			<description>Short answer: A failed dictionary search returns the null corresponding to the first dictionary entry’s value.
 Let’s test with the following two dictionaries, sfdictand fsdict:
q)sfdict: `symbol`float ! (`abc; 123.4) // type sym is first q)fsdict: `float`symbol ! (123.4; `abc) // type float is first q)sfdict symbol| `abc float | 123.4 q)fsdict float | 123.4 symbol| `abc q) Note that while both dictionaries contain the same key-value pairs, because dictionaries are an ordered list of key value pairs, the above two dictionaries do not match.</description>
			<content type="html"><![CDATA[<p>Short answer: A failed dictionary search returns the null corresponding to the first dictionary entry’s value.</p>
<hr>
<p>Let’s test with the following two dictionaries, <!-- raw HTML omitted -->sfdict<!-- raw HTML omitted --> and <!-- raw HTML omitted -->fsdict<!-- raw HTML omitted -->:</p>
<pre><code>q)sfdict: `symbol`float ! (`abc; 123.4)  // type sym is first
q)fsdict: `float`symbol ! (123.4; `abc)  // type float is first
q)sfdict
symbol| `abc
float | 123.4
q)fsdict
float | 123.4
symbol| `abc
q)
</code></pre><p>Note that while both dictionaries contain the same key-value pairs, because dictionaries are an <strong>ordered</strong> list of key value pairs, the above two dictionaries do not match.</p>
<pre><code>q)sfdict = fsdict
symbol| 1
float | 1
q)sfdict ~ fsdict
0b
q)
</code></pre><p>A dictionary search returns a null value when the key sought is not found:</p>
<pre><code>q)null sfdict[`badkey]
1b
q)null fsdict[`badkey]
1b
q)
</code></pre><p>Getting a null back from a failed lookup is expected. On the other hand, many are surprised to find that the two nulls returned for the above two lookups differ:</p>
<pre><code>q)sfdict[`badkey] ~ fsdict[`badkey]
0b
q)sfdict[`badkey]
`                    // null symbol
q)fsdict[`badkey]
0n                   // null float
q)
</code></pre><p>The types of the returned nulls are different according to the types of the first values in <!-- raw HTML omitted -->sfdict<!-- raw HTML omitted --> and <!-- raw HTML omitted -->fsdict<!-- raw HTML omitted -->. This is the same behavior observed when indexing a mixed list with an out-of-range index:</p>
<pre><code>q)(`a; `b; 1f; 2f)[5]
`
q)(1f; 2f; `a; `b)[5]
0n
q)
</code></pre><p>There’s a similar “first element wins” behavior with the atomicity of dictionary keys. see this faq on  <a href="https://www.kdbfaq.com/why-cant-i-index-some-elements-of-a-dictionary.html">dictionary indexing</a> to learn more.</p>
]]></content>
		</item>
		
		<item>
			<title>When does : (amend) not modify its first argument?</title>
			<link>https://kdbfaq.com/when-does-amend-not-modify-its-first-argument/</link>
			<pubDate>Mon, 22 Aug 2011 02:06:57 +0000</pubDate>
			
			<guid>https://kdbfaq.com/when-does-amend-not-modify-its-first-argument/</guid>
			<description>Short answer: When 1) projected or 2) modified by an adverb, e.g., :/: :: or :’
 Normally, the : (amend) function is used to assign a value to a name:
q)foo: 47 q)foo 47 q) Like other built-in functions that take two arguments, : (amend) can be called using either infix notation (as above) or function call notation:
q):[foo; 747] q)foo 747 q) Note that : (amend) displays its special semantics (which it shares with assignments in all strict languages) of not evaluating its first argument when that argument is simply a name, regardless of whether : (amend) is invoked infix or functionally.</description>
			<content type="html"><![CDATA[<p>Short answer: When 1) projected or 2) modified by an adverb, e.g., :/: :: or :’</p>
<hr>
<p>Normally, the <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> function is used to assign a value to a name:</p>
<pre><code>q)foo: 47
q)foo
47
q)
</code></pre><p>Like other built-in functions that take two arguments, <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> can be called using either infix notation (as above) or function call notation:</p>
<pre><code>q):[foo; 747]
q)foo
747
q)
</code></pre><p>Note that <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> displays its special semantics (which it shares with assignments in all strict languages) of not evaluating its first argument when that argument is simply a name, regardless of whether <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> is invoked infix or functionally.</p>
<pre><code>q)delete bar from `.    / make sure bar is not defined
q):[bar; 42]
q)bar
42
q)
</code></pre><p>On the other hand, <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> does evaluate its first argument when that argument is an expression, but <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> still produces <a href="http://en.wikipedia.org/wiki/Value_(computer_science)">l-values</a> when it does so:</p>
<pre><code>q)list: 0 1 2 3
q)list[0]: 47
q)list
47 1 2 3
q):[list 1 2 3; 10 20 30]
q)list
47 10 20 30
q)
</code></pre><p>Based on the previous examples, you might be tempted create a projection from <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> and a left-hand side, but it turns out you can’t:</p>
<pre><code>q):[foo]
'foo
q)
</code></pre><p>It is possible to close the first argument to <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a>, but the resulting projection is no longer an assignment; it is an identity function:</p>
<pre><code>q)foo: 42
q)(:[foo])[47]
47
q)foo
42
q)
</code></pre><p>In fact, the value attached to the first argument of <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> is irrelevant:</p>
<pre><code>q)(:[`xyzzy])[47]
47
q)
</code></pre><p>Closing the second argument will cause <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> to return the same value always:</p>
<pre><code>q)f: :[; 3]     / bind the 2nd argument
q)f 18          / no matter what we pass
3
q)f &quot;hello&quot;     / f will always return 3
3
q)
</code></pre><p>The other case when <a href="https://code.kx.com/q/ref/assign/"><!-- raw HTML omitted -->: (amend)<!-- raw HTML omitted --></a> does not perform assignment is when it is modified by an adverb:</p>
<pre><code>q)list1: 0 1 2 3
q)list2: 4 5 6 7
q)(list1; list2) :\: 10 20 30 40   / we get the rhs
10 20 30 40                        / once for each list
10 20 30 40
q)list1                            / neither list
0 1 2 3
q)list2                            / has been modified
4 5 6 7
q)list2 :/: 0 1 2 3
0 1 2 3
q)list1[0 1 2 3] :' 10 20 30 40
10 20 30 40
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>What is q’s equivalent to sql’s ORDER BY?</title>
			<link>https://kdbfaq.com/what-is-qs-equivalent-to-sqls-order-by/</link>
			<pubDate>Sun, 07 Aug 2011 18:29:03 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-is-qs-equivalent-to-sqls-order-by/</guid>
			<description>xasc and xdesc. Consider the following table:
q)table: ([] x: 10 ? &amp;quot;abc&amp;quot;; y: 10 ? til 10) q)table x y --- a 7 a 7 b 1 b 9 a 1 a 0 c 8 b 8 c 3 c 1 q) To sort by column x, instead of ORDER BY, we write  `x xasc table:
q)`x xasc table // sort by column x x y --- a 7 a 7 a 1 a 0 b 1 b 9 b 8 c 8 c 3 c 1 q) The application of xdesc is similar.</description>
			<content type="html"><![CDATA[<p><a href="https://code.kx.com/q/ref/asc/#xasc"><code>xasc</code></a> and <a href="https://code.kx.com/q/ref/desc/#xdesc"><code>xdesc</code></a>. Consider the following table:</p>
<pre><code>q)table: ([] x: 10 ? &quot;abc&quot;; y: 10 ? til 10)
q)table
x y
---
a 7
a 7
b 1
b 9
a 1
a 0
c 8
b 8
c 3
c 1
q)
</code></pre><p>To sort by column <!-- raw HTML omitted -->x<!-- raw HTML omitted -->, instead of <code>ORDER BY</code>, we write  <code> `x xasc table</code>:</p>
<pre><code>q)`x xasc table // sort by column x
x y
---
a 7
a 7
a 1
a 0
b 1
b 9
b 8
c 8
c 3
c 1
q)
</code></pre><p>The application of <a href="https://code.kx.com/q/ref/desc/#xdesc"><code>xdesc</code></a> is similar.</p>
<p>In addition, to sort by multiple columns, instead of <code>ORDER BY y, x</code> or <code>ORDER BY y, x  DESC</code> , we pass the list of column names as the left argument to <a href="https://code.kx.com/q/ref/asc/#xasc"><code>xasc</code></a> or <a href="https://code.kx.com/q/ref/desc/#xdesc"><code>xdesc</code></a>, respectively. For example,</p>
<pre><code>q)`y`x xdesc select from table where y &gt; 5
x y
---
b 9
c 8
b 8
a 7
a 7
q)
</code></pre><p>Don’t confuse <a href="https://code.kx.com/q/ref/asc/#xasc"><code>xasc</code></a> and <a href="https://code.kx.com/q/ref/desc/#xdesc"><code>xdesc</code></a> with <a href="https://code.kx.com/q/ref/asc/#asc" title="code.kx.com"><code>asc</code></a> and <a href="https://code.kx.com/q/ref/desc/#desc" title="code.kx.com"><code>desc</code></a>, which operate on a vector instead of a table. Read more about sorting vectors in this <a href="https://www.kdbfaq.com/how-do-i-sort.html">related faq</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I extract hours, minutes, or seconds from a time?</title>
			<link>https://kdbfaq.com/how-do-i-extract-hours-minutes-or-seconds-from-a-time/</link>
			<pubDate>Sat, 30 Jul 2011 21:35:38 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-extract-hours-minutes-or-seconds-from-a-time/</guid>
			<description>Short answer: Times are integers (think milliseconds).
q)(`hh`mm`ss $ .z.T), `int $ .z.T mod 1000 16 49 2 233 q)  You can extract the hours, minutes, and seconds from a time by passing `hh, `mm, and `ss, respectively, as left arguments to $ (cast):
q)now: .z.T q)now 16:49:02.233 q)`hh $ now 16 q)`mm $ now 49 q)`ss $ now 2 q)`hh`mm`ss $ now 16 49 2 q) Getting the milliseconds from a time is slightly less obvious.</description>
			<content type="html"><![CDATA[<p>Short answer: Times are integers (think milliseconds).</p>
<pre><code>q)(`hh`mm`ss $ .z.T), `int $ .z.T mod 1000
16 49 2 233
q)
</code></pre><hr>
<p>You can extract the hours, minutes, and seconds from a time by passing <!-- raw HTML omitted -->`hh, `mm, and `ss<!-- raw HTML omitted -->, respectively, as left arguments to <a href="https://code.kx.com/q/ref/cast/"><!-- raw HTML omitted -->$ (cast)<!-- raw HTML omitted --></a>:</p>
<pre><code>q)now: .z.T
q)now
16:49:02.233
q)`hh $ now
16
q)`mm $ now
49
q)`ss $ now
2
q)`hh`mm`ss $ now
16 49 2
q)
</code></pre><p>Getting the milliseconds from a time is slightly less obvious. Times (type -19) are represented internally by <!-- raw HTML omitted -->q<!-- raw HTML omitted --> as 32-bit integers; typically the value counts the number of milliseconds since midnight, but it can also represent a span of time. We can cast freely back and forth between the two types and the values are preserved:</p>
<pre><code>q)`time $ 0
00:00:00.000
q)`int $ 00:00:00.000
0q)`time $ 24 * 60 * 60 * 1000
24:00:00.000
q)`int $ 24:00:00.000
86400000
q)`int $ now
60542233
q)`time $ 60542233
16:49:02.233
q)
</code></pre><p>Not only is the internal representation of time simply an integer, we can mix integers and times in integer arithmetic operations, and the result is always a time:</p>
<pre><code>q)01:00:00.000 + 00:01:00.000
01:01:00.000
q)01:00:00.000 + 60000
01:01:00.000
q)01:00:00.000 * 4
04:00:00.000
q)now - 01:30:20.123
15:18:42.110
q)
</code></pre><p>By using <a href="https://code.kx.com/q/ref/div/"><!-- raw HTML omitted -->div<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/mod"><!-- raw HTML omitted -->mod<!-- raw HTML omitted --></a>, then, we have an alternative means to calculate the components of a time:</p>
<pre><code>q)now div 3600000 // milliseconds per hour
00:00:00.016
q)now mod 1000    // just the milliseconds, please
00:00:00.233
q)
</code></pre><p>Although extracting milliseconds from a time while keeping the time type (as in the second example above) is sometimes useful, we normally want to get back these components of a time as integers, so let’s cast it:</p>
<pre><code>q)`int $ now mod 1000
233
q)
</code></pre><hr>
<p>By the way, there is a shortcut for getting hours, minutes, and seconds from global variables that hold times: dot notation.</p>
<pre><code>q)x: .z.T
q)x.hh, x.mm, x.ss
16 49 2
q)
</code></pre><p>However, we rarely use global variables to hold time values.</p>
<p> </p>
]]></content>
		</item>
		
		<item>
			<title>How do I parse a date and time?</title>
			<link>https://kdbfaq.com/how-do-i-parse-a-date-and-time/</link>
			<pubDate>Sun, 24 Jul 2011 23:46:12 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-parse-a-date-and-time/</guid>
			<description>Short answer: “D”$, “T”$, and “Z”$ In general you can parse strings to some particular type by passing the uppercase form of the corresponding type character as the left argument to $ (cast).
qcan parse dates in YYYYMMDD, YYYY-MM-DD, or YYYY.MM.DD format:
q)&amp;quot;D&amp;quot;$ (&amp;quot;20070809&amp;quot;; &amp;quot;2007-08-09&amp;quot;; &amp;quot;2007.08.09&amp;quot;) 2007.08.09 2007.08.09 2007.08.09 q) Times must have the form HH:MM:SS.mmm, but you can shorten them:
q)&amp;quot;T&amp;quot;$ (&amp;quot;07:08:09.010&amp;quot;; &amp;quot;07:08:09&amp;quot;; &amp;quot;07:08&amp;quot;; &amp;quot;07&amp;quot;) 07:08:09.010 07:08:09.000 07:08:00.000 07:00:00.000 q) In addition, “T”$will tolerate a missing zero for hours (and hours only) less than 10:</description>
			<content type="html"><![CDATA[<p>Short answer: <!-- raw HTML omitted -->“D”$<!-- raw HTML omitted -->, <!-- raw HTML omitted -->“T”$<!-- raw HTML omitted -->, and <!-- raw HTML omitted -->“Z”$<!-- raw HTML omitted --></p>
<hr>
<p>In general you can parse strings to some particular type by passing the uppercase form of the corresponding <a href="https://code.kx.com/q/basics/datatypes/">type character</a> as the left argument to <a href="https://code.kx.com/q/ref/cast/"><!-- raw HTML omitted -->$ (cast)<!-- raw HTML omitted --></a>.</p>
<p><!-- raw HTML omitted -->q<!-- raw HTML omitted --> can parse dates in <!-- raw HTML omitted -->YYYYMMDD, YYYY<!-- raw HTML omitted -->-MM-DD, or <!-- raw HTML omitted -->YYYY.MM.DD <!-- raw HTML omitted -->format:</p>
<pre><code>q)&quot;D&quot;$ (&quot;20070809&quot;; &quot;2007-08-09&quot;; &quot;2007.08.09&quot;)
2007.08.09 2007.08.09 2007.08.09
q)
</code></pre><p>Times must have the form HH:MM:SS.mmm, but you can shorten them:</p>
<pre><code>q)&quot;T&quot;$ (&quot;07:08:09.010&quot;; &quot;07:08:09&quot;; &quot;07:08&quot;; &quot;07&quot;)
07:08:09.010 07:08:09.000 07:08:00.000 07:00:00.000
q)
</code></pre><p>In addition, <!-- raw HTML omitted -->“T”$<!-- raw HTML omitted --> will tolerate a missing zero for hours (and hours only) less than 10:</p>
<pre><code>q)&quot;T&quot;$ &quot;7:08:09&quot;
07:08:09.000
q)
</code></pre><p><!-- raw HTML omitted -->“Z”$<!-- raw HTML omitted --> expects (<a href="http://www.w3.org/TR/xmlschema-2/#dateTime">as in <!-- raw HTML omitted -->XML<!-- raw HTML omitted --></a>) that dates and times are joined with a <!-- raw HTML omitted -->T<!-- raw HTML omitted -->:</p>
<pre><code>q)&quot;Z&quot;$ &quot;2007-08-09T07:08:09.101&quot;
2007.08.09T07:08:09.101
q)
</code></pre><p><!-- raw HTML omitted -->“Z”$<!-- raw HTML omitted --> usually treats the text analogously to <!-- raw HTML omitted -->“D”$<!-- raw HTML omitted --> and <!-- raw HTML omitted -->“T”$<!-- raw HTML omitted -->; that is, the date must be complete, but the time may have its finer points elided:</p>
<pre><code>q)&quot;Z&quot;$ &quot;2007&quot;
0Nz
q)&quot;Z&quot;$ &quot;20070809&quot;
2007.08.09T00:00:00.000
q)
</code></pre><p>Note, however, the <!-- raw HTML omitted -->“Z”$<!-- raw HTML omitted --> – unlike <!-- raw HTML omitted -->“T”$<!-- raw HTML omitted --> – requires that hours less than 10 be prepended with zero:</p>
<pre><code>q)&quot;Z&quot;$ &quot;20070809T7:08:09&quot;
0Nz
q)
</code></pre><p>You can also parse months with <!-- raw HTML omitted -->“M”$<!-- raw HTML omitted -->, minutes with <!-- raw HTML omitted -->“U”$<!-- raw HTML omitted -->, and seconds with <!-- raw HTML omitted -->“V”$<!-- raw HTML omitted -->:</p>
<pre><code>q)&quot;M&quot;$ (&quot;2007-08&quot;; &quot;2007.08&quot;; &quot;200708&quot;)
2007.08 2007.08 2007.08m
q)&quot;U&quot;$ &quot;07:08:09.010&quot;
07:08
q)&quot;V&quot;$ &quot;07:08:09.010&quot;
07:08:09
q)
</code></pre><p>Make sure you don’t pass any extra text to <!-- raw HTML omitted -->“M”$<!-- raw HTML omitted -->, though:</p>
<pre><code>q)&quot;M&quot;$ &quot;2007.08.01&quot;
2007.01m
q)
</code></pre><p>There are two more type characters for parsing temporal values. <!-- raw HTML omitted -->“N”$<!-- raw HTML omitted --> and <!-- raw HTML omitted -->“P”$<!-- raw HTML omitted --> are for parsing nanosecond-precise time spans and datetimes, respectively:</p>
<pre><code>q)&quot;N&quot;$ &quot;12D07:08:09.123456789&quot;
12D07:08:09.123456789
q)&quot;P&quot;$ &quot;2007-08-09T07:08:09.123456789&quot;
2007.08.09D07:08:09.123456789
q)
</code></pre><p>You may have discovered that <!-- raw HTML omitted -->“N”$<!-- raw HTML omitted --> can parse floating point numbers, as well, but beware – depending on the range of the input, you might not get what you expect:</p>
<pre><code>q)&quot;N&quot;$ &quot;0.123456789&quot;
0D00:00:00.123456789
q)&quot;N&quot;$ &quot;1.123456789&quot;
0D01:00:00.123456789
q)&quot;N&quot;$ &quot;12.123456789&quot;
0D12:00:00.123456789
q)&quot;N&quot;$ &quot;24.123456789&quot;
1D00:00:00.123456789
q)&quot;N&quot;$ &quot;48.123456789&quot;
2D00:00:00.123456789
q)&quot;N&quot;$ &quot;4800.123456789&quot;
2D00:00:00.123456789
q)
</code></pre><p>Stick with strings that represent durations in the way <!-- raw HTML omitted -->q<!-- raw HTML omitted --> does, and you’ll steer clear of surprises.</p>
<p>Lastly, if you find yourself with a text full of times expressed as seconds (and, optionally, fractions thereof) since the <a href="http://en.wikipedia.org/wiki/Unix_time">Unix epoch</a>, “P”$, and “Z”$ can parse them, too:</p>
<pre><code>q)unix_time: first system &quot;date +%s&quot;
q)unix_time
&quot;1311635286&quot;
q)&quot;Z&quot;$ unix_time
2011.07.25T23:08:06.000
q)&quot;P&quot;$ unix_time , &quot;.123456789&quot;
2011.07.25D23:08:06.123456789
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>How do I get the length of a list?</title>
			<link>https://kdbfaq.com/how-do-i-get-the-length-of-a-list/</link>
			<pubDate>Tue, 19 Jul 2011 02:02:41 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-get-the-length-of-a-list/</guid>
			<description>Short answer:
count listorcount each column_nameto get the length of a list-valued field in a query. The length of any list can be found using the count function; the only complication occurs with certain applications of count in queries. We’ll illustrate with a table of simulated trade data:
q)tradetime sym price size---------------------------09:30:17.623 glo 26.79 320009:30:26.602 ojb 28.17 160009:30:33.657 fjc 91.31 540009:30:40.884 knb 59.7 290009:31:19.</description>
			<content type="html"><![CDATA[<p>Short answer:</p>
<p><!-- raw HTML omitted -->count list<!-- raw HTML omitted --><br>
<!-- raw HTML omitted -->or<!-- raw HTML omitted --><br>
<!-- raw HTML omitted -->count each column_name<!-- raw HTML omitted --><br>
<!-- raw HTML omitted -->to get the length of a list-valued field in a query.<!-- raw HTML omitted --></p>
<hr>
<p>The length of any list can be found using the <a href="https://code.kx.com/q/ref/count/"><code>count</code></a> function; the only complication occurs with certain applications of <a href="https://code.kx.com/q/ref/count/"><!-- raw HTML omitted -->count<!-- raw HTML omitted --></a> in queries. We’ll illustrate with a table of simulated trade data:</p>
<pre><code>q)trade
time         sym price size
---------------------------
09:30:17.623 glo 26.79 3200
09:30:26.602 ojb 28.17 1600
09:30:33.657 fjc 91.31 5400
09:30:40.884 knb 59.7  2900
09:31:19.256 apl 1.26  7900
..
q)
</code></pre><p>The following query uses (<a href="https://code.kx.com/q/ref/count/"><!-- raw HTML omitted --> count <!-- raw HTML omitted --></a>) to return the number of rows that satisfy the <a href="https://code.kx.com/q/ref/where/"><!-- raw HTML omitted -->where<!-- raw HTML omitted --></a> clause:</p>
<pre><code>q)exec count i from trade where sym = `aif
6
q)
</code></pre><p>This is usually what you want.</p>
<p>However, suppose we created another table (perhaps to improve the performance of certain queries) that grouped prices for each symbol:</p>
<pre><code>q)grouped: select price by sym from trade
q)grouped
sym| price                                                   ..
---| --------------------------------------------------------..
acl| 18.1 85.5 86.31 45.65 10.91 31.25 5.49 51.66 1.02 31.82 ..
aif| 44.02 47.74 11.83 14.28 85.11 99.09                     ..
alk| 51.12 16.7 78.71 96.56 26.55 32.09 33.66 30.01 83.24 30...
amg| 59.25 56.18 92.63 46.57 57.25 14.58 69.21 88.25 94.1 28...
aog| 92.59 51.52 96.95 83.2 6.21 59.77 44.19 94.19 3.13 41.94..
..
q)
</code></pre><p>In table <!-- raw HTML omitted -->grouped<!-- raw HTML omitted -->, the <!-- raw HTML omitted -->price<!-- raw HTML omitted --> column is of type list-of-float – note the <strong>uppercase</strong> type letter <!-- raw HTML omitted -->F<!-- raw HTML omitted -->:</p>
<pre><code>q)meta grouped
c    | t f a
-----| -----
sym  | s
price| F
q)
</code></pre><p>It appears that we can retrieve the prices for a given symbol easily enough:</p>
<pre><code>q)exec price from grouped where sym = `aif
44.02 47.74 11.83 14.28 85.11 99.09
q)
</code></pre><p>Suppose, however, that we want to know how many trades occurred for a particular symbol:</p>
<pre><code>q)exec count price from grouped where sym = `aif
1
q)
</code></pre><p>What went wrong? A <a href="https://code.kx.com/q/ref/where/"><!-- raw HTML omitted -->where<!-- raw HTML omitted --></a> function yields a list of row indexes that meet the constraints, and then each projection (i.e., the column names between <!-- raw HTML omitted -->exec<!-- raw HTML omitted --> and <!-- raw HTML omitted -->from<!-- raw HTML omitted --> — in this case, <!-- raw HTML omitted -->price<!-- raw HTML omitted -->) yields a list of corresponding field values. Since the number of rows that met our sole constraint is 1, the result of the projection is an untyped list with a single element:</p>
<pre><code>q)type exec price from grouped where sym = `aif
0h
q)count exec price from grouped where sym = `aif
1
q)
</code></pre><p>Projection results are the arguments to aggregation functions in queries. In other words, the untyped list in our example is the same as the one passed to <a href="https://code.kx.com/q/ref/count/"><!-- raw HTML omitted -->count<!-- raw HTML omitted --></a>. Since the projection’s single element contains the list of prices we want to count, the way out is to combine <a href="https://code.kx.com/q/ref/count/"><!-- raw HTML omitted -->count<!-- raw HTML omitted --></a> with <a href="https://code.kx.com/q/ref/first/"><!-- raw HTML omitted -->first<!-- raw HTML omitted --></a>:</p>
<pre><code>q)exec count first price from grouped where sum = `aif
6
q)
</code></pre><p>Applying the same logic when counting the trades for every symbol, we need to use <a href="https://code.kx.com/q/ref/count/"><!-- raw HTML omitted -->count<!-- raw HTML omitted --></a> <a href="https://code.kx.com/q/ref/each/"><!-- raw HTML omitted -->each<!-- raw HTML omitted --></a>:</p>
<pre><code>q)select count price by sym from grouped
sym| price
---| -----
acl| 1
aif| 1
alk| 1
amg| 1
aog| 1
..
q)select count each price by sym from grouped
sym| price
---| -----
acl| 14
aif| 6
alk| 10
amg| 12
aog| 13
..
q)
</code></pre><p>Constraints in <a href="https://code.kx.com/q/ref/where/"><!-- raw HTML omitted -->where<!-- raw HTML omitted --></a> clauses behave the same as well. Consider the following <a href="https://code.kx.com/q/ref/select/"><!-- raw HTML omitted -->select<!-- raw HTML omitted --></a> statement:</p>
<pre><code>q)t
x y z
-------------
a 1 &quot;xyzzy&quot;
b 2 &quot;grue&quot;
c 3 &quot;frobozz&quot;
q)select from t where 5 &lt; count z
x y z
-----
q)
</code></pre><p>Newcomers to q often expect the above query to return the rows from <!-- raw HTML omitted -->t<!-- raw HTML omitted --> whose <!-- raw HTML omitted -->z<!-- raw HTML omitted --> column has more than 5 characters (i.e., <!-- raw HTML omitted -->c 3 frobozz<!-- raw HTML omitted -->). Rather than counting the contents of each <!-- raw HTML omitted -->z<!-- raw HTML omitted --> field, however, <a href="https://code.kx.com/q/ref/count/"><!-- raw HTML omitted -->count<!-- raw HTML omitted --></a> is actually counting the list <!-- raw HTML omitted -->t `z<!-- raw HTML omitted -->:</p>
<pre><code>q)count t `z
3
q)t `z
&quot;xyzzy&quot;
&quot;foobar&quot;
&quot;frobozz&quot;
q)
</code></pre><p>This insight suggests the solution:</p>
<pre><code>q)count each t `z
5 6 7
q)select from t where 5 &lt; count each z
x y z
-------------
c 3 &quot;frobozz&quot;
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>select sum size from a large table unexpectedly returns a negative number.  Why?</title>
			<link>https://kdbfaq.com/select-sum-size-from-a-large-table-unexpectedly-returns-a-negative-number-why/</link>
			<pubDate>Fri, 24 Jun 2011 03:47:45 +0000</pubDate>
			
			<guid>https://kdbfaq.com/select-sum-size-from-a-large-table-unexpectedly-returns-a-negative-number-why/</guid>
			<description>Short answer: cast the column to longbefore applying sum:
select sum `long $ size from large_table In many programming languages, including q, anytime you add integers (unless you somehow know for sure that the sum will fit in – roughly – 31 bits) you risk integer overflow. If you’re lucky, the error will be obvious (e.g., you’ll get a negative number when you expected a positive one). Casting the arguments to sum to longwill give you (almost) 63 bits of breathing room.</description>
			<content type="html"><![CDATA[<p>Short answer: cast the column to <!-- raw HTML omitted -->long<!-- raw HTML omitted --> <strong>before</strong> applying <a href="https://code.kx.com/q/ref/sum/"><!-- raw HTML omitted -->sum<!-- raw HTML omitted --></a>:</p>
<pre><code>select sum `long $ size from large_table
</code></pre><p>In many programming languages, including q, anytime you add integers (unless you somehow know for sure that the sum will fit in – roughly – 31 bits) you risk <a href="http://en.wikipedia.org/wiki/Integer_overflow" title="">integer overflow</a>. If you’re lucky, the error will be obvious (e.g., you’ll get a negative number when you expected a positive one). Casting the arguments to <a href="https://code.kx.com/q/ref/sum/"><!-- raw HTML omitted -->sum<!-- raw HTML omitted --></a> to <!-- raw HTML omitted -->long<!-- raw HTML omitted --> will give you (almost) 63 bits of breathing room.</p>
<p>If your sum won’t fit in 63 bits, you’ll need to explore other options:</p>
<ul>
<li>Switch to floats. Although overflow is still possible, it’s rare. However, you lose some precision.</li>
<li>Use a bignum library such as <a href="http://gmplib.org/">gmp</a>.</li>
<li>Use a language (e.g., <a href="http://haskell.org">haskell</a> or <a href="http://clojure.org">clojure</a>) that has built-in support for arbitrary-precision arithmetic.</li>
</ul>
<p>Lastly, keep in mind that literal values that cannot fit into an <!-- raw HTML omitted -->int<!-- raw HTML omitted --> must be suffixed with <!-- raw HTML omitted -->j<!-- raw HTML omitted --> – even if the context suggests that a <!-- raw HTML omitted -->long<!-- raw HTML omitted --> is expected:</p>
<pre><code>q)select from meta large_table where c = `id
c | t f a
--| -----
id| j
q)count select from large_table where id = 84066472837652480
'84066472837652480
q)count select from large_table where id = 84066472837652480j
1
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>Does the order of field constraints matter in the performance of a select query?</title>
			<link>https://kdbfaq.com/does-the-order-of-field-constraints-matter-in-the-performance-of-a-select-query/</link>
			<pubDate>Sat, 04 Jun 2011 06:00:06 +0000</pubDate>
			
			<guid>https://kdbfaq.com/does-the-order-of-field-constraints-matter-in-the-performance-of-a-select-query/</guid>
			<description>Short answer: Yes, put the most restrictive constraint first.
Although expressions in q are usually evaluated from right to left, there is one exception: the constraints in a whereclause are evaluated from left to right. Consider the following example:
q)t: ([] x: `a`b`c; y: 1 2 3) q)select from t where x &amp;lt; `c, y &amp;gt; 1 x y --- b 2 q) The comma separating x &amp;lt; `cfrom y &amp;gt; 1is not the join operator; instead, it delimits the constraints of the whereclause.</description>
			<content type="html"><![CDATA[<p>Short answer: Yes, put the most restrictive constraint first.</p>
<p>Although expressions in q are usually evaluated from right to left, there is one exception: the constraints in a <!-- raw HTML omitted -->where<!-- raw HTML omitted --> clause are evaluated from left to right. Consider the following example:</p>
<pre><code>q)t: ([] x: `a`b`c; y: 1 2 3)
q)select from t where x &lt; `c, y &gt; 1
x y
---
b 2
q)
</code></pre><p>The comma separating <!-- raw HTML omitted -->x &lt; `c<!-- raw HTML omitted --> from <!-- raw HTML omitted -->y &gt; 1<!-- raw HTML omitted --> is not <a href="https://code.kx.com/q/ref/join/">the join operator</a>; instead, it delimits the constraints of the <!-- raw HTML omitted -->where<!-- raw HTML omitted --> clause. If you need to use the join operator in a <!-- raw HTML omitted -->where<!-- raw HTML omitted --> clause, use parentheses:</p>
<pre><code>q)select from t where x in (`a, `b), y &gt; 1
x y
---
b 2
q)
</code></pre><p>Each constraint is evaluated in the usual order, i.e., right-to-left:</p>
<pre><code>q)select from t where x &lt; first -1 # `p`c, y &gt; 1
x y
---
b 2
q)
</code></pre><p>Because constraints are evaluated from left to right, putting the most restrictive constraint first will speed up queries on large tables. On a date partitioned database, for example, the placement of a constraint on the virtual date column will make a marked performance difference:</p>
<pre><code>select from large_table where date = 2011.02.25, name = `JOE
</code></pre><p>is significantly faster than</p>
<pre><code>select from large_table where name = `JOE, date = 2011.02.25
</code></pre><p>The latter query will attempt to load the entire contents of table for rows matching name `JOE prior to narrowing the result set down to a single date. kdb does not provide behind-the-scenes optimization in cases like these.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I set a breakpoint inside a q function?</title>
			<link>https://kdbfaq.com/how-do-i-set-a-breakpoint-inside-a-q-function/</link>
			<pubDate>Thu, 02 Jun 2011 05:47:01 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-set-a-breakpoint-inside-a-q-function/</guid>
			<description>Consider the following function, testfunc:
testfunc: {[] x: `aaa; y: `bbb; z:: `ccc; -1 &amp;quot;finished!&amp;quot;; } Let’s demonstrate the placement of a breakpoint prior to the assignment of global variable z. Although there is no explicit support for breakpoints in q, insertion of non-compliant code, such as breakhere;shown below, does the job (don’t forget the trailing semicolon):
testfunc: {[] x: `aaa; y: `bbb; breakhere; z:: `ccc; -1 “finished!” } We are tricking q into throwing a signal ‘breakhere.</description>
			<content type="html"><![CDATA[<p>Consider the following function, <!-- raw HTML omitted -->testfunc<!-- raw HTML omitted -->:</p>
<pre><code>testfunc: {[]
x: `aaa;
y: `bbb;
z:: `ccc;
-1 &quot;finished!&quot;;
}
</code></pre><p>Let’s demonstrate the placement of a breakpoint prior to the assignment of global variable <!-- raw HTML omitted -->z<!-- raw HTML omitted -->. Although there is no explicit support for breakpoints in q, insertion of non-compliant code, such as <!-- raw HTML omitted -->breakhere;<!-- raw HTML omitted --> shown below, does the job (don’t forget the trailing semicolon):</p>
<pre><code>testfunc: {[] x: `aaa;
y: `bbb;
breakhere;
z:: `ccc;
-1 “finished!”
}
</code></pre><p>We are tricking q into throwing a signal <!-- raw HTML omitted -->‘breakhere<!-- raw HTML omitted -->.</p>
<pre><code>q)testfunc[] {[] x: `aaa;
y: `bbb;
breakhere;
z:: `ccc;
-1 “finished!”
}
‘breakhere
q))
</code></pre><p>At this point, we can examine the local stack.</p>
<pre><code>q))x
`aaa
q))y
`bbb
q))z
()
q))
</code></pre><p>kdb has suspended execution, leaving the remaining two lines of function <!-- raw HTML omitted -->testfunc<!-- raw HTML omitted --> unexecuted. <a href="https://code.kx.com/q/basics/function-notation/#explicit-return"><!-- raw HTML omitted -->: (colon)<!-- raw HTML omitted --></a> resumes execution.</p>
<pre><code>q)):
finished!
-1
q)x
‘x
q)y
‘y
q)z
`ccc
q)
</code></pre><p>See:  <a href="https://code.kx.com/q/ref/overloads/#colon-colon">global amend (::)</a></p>
]]></content>
		</item>
		
		<item>
			<title>How do I expose a subset of partitions and remove the rest from view?</title>
			<link>https://kdbfaq.com/how-do-i-expose-a-subset-of-partitions-and-remove-the-rest-from-view/</link>
			<pubDate>Thu, 02 Jun 2011 01:55:55 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-expose-a-subset-of-partitions-and-remove-the-rest-from-view/</guid>
			<description>Short answer: .Q.view partition_list
By default, all partitions of a given historical kdb database are available. The .Q.view  function enables a given kdb process instance to selectively expose an arbitrary set of partitions into view.
The following example restricts all operations of the database instance to the most recent partition date (typically the previous business day):
q)yesterday: last date q).Q.view yesterday q)count date 1 q)yesterday ~ value exec from select distinct date from trade 1b q) Here is a more realistic example of a date partitioned historical database where viewable partitions are limited to those year-to-date:</description>
			<content type="html"><![CDATA[<p>Short answer: <code>.Q.view partition_list</code></p>
<p>By default, all partitions of a given historical kdb database are available. The <a href="https://code.kx.com/q/ref/dotq/#qview-subview"><!-- raw HTML omitted --> <code>.Q.view</code> <!-- raw HTML omitted --></a> function enables a given kdb process instance to selectively expose an arbitrary set of partitions into view.</p>
<p>The following example restricts all operations of the database instance to the most recent partition date (typically the previous business day):</p>
<pre><code>q)yesterday: last date
q).Q.view yesterday
q)count date
1
q)yesterday ~ value exec from select distinct date from trade
1b
q)
</code></pre><p>Here is a more realistic example of a date partitioned historical database where viewable partitions are limited to those year-to-date:</p>
<pre><code>q)start_date: &quot;D&quot; $ string[`year $ .z.D], &quot;.01.01&quot;
q)end_date: last date
q).Q.view date where date within (start_date; end_date)
q)count select from trade where not date within (start_date; end_date)
0
q)
</code></pre><p>See also: <a href="https://code.kx.com/q/ref/dotq/#qpn-partition-counts"><!-- raw HTML omitted -->.Q.pn<!-- raw HTML omitted --></a></p>
]]></content>
		</item>
		
		<item>
			<title>I have a very large file to uncompress.  zip and gzip do not work!</title>
			<link>https://kdbfaq.com/i-have-a-very-large-file-to-uncompress-zip-and-gzip-do-not-work/</link>
			<pubDate>Thu, 02 Jun 2011 01:46:54 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-have-a-very-large-file-to-uncompress-zip-and-gzip-do-not-work/</guid>
			<description>Short answer: Use 7-zip. It contains large-file support.
$ unzip verylargefile.zip /destination_dir/ I/O error: File too large $ Make sure your file system can handle LFS.
$ 7za e -o /destination_dir/ verylargefile.zip See also: 7-zip usage examples.</description>
			<content type="html"><![CDATA[<p>Short answer: Use <a href="http://www.7-zip.org/download.html">7-zip</a>. It contains large-file support.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">$ unzip verylargefile.zip /destination_dir/
 I/O error: File too large
$
</code></pre></div><p>Make sure your file system can handle <a href="http://en.wikipedia.org/wiki/Large_file_support" title="wikipedia"><!-- raw HTML omitted -->LFS<!-- raw HTML omitted --></a>.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">$ 7za e -o /destination_dir/ verylargefile.zip
</code></pre></div><p>See also: <a href="http://www.dotnetperls.com/7-zip-examples" title="">7-zip usage examples</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>What exactly does column-oriented mean?</title>
			<link>https://kdbfaq.com/what-exactly-does-column-oriented-mean/</link>
			<pubDate>Tue, 31 May 2011 06:45:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-exactly-does-column-oriented-mean/</guid>
			<description>It means that all the values in a column are stored together. This is in contrast to row-oriented, in which all the values for a row are stored together. Which organization is better depends on the access pattern of your application.
Many operations are more efficient with a column-oriented approach. In particular, operations that need to access a sequence of values from a particular column are much faster. If all the values in a column have the same size (which is true, by design, in kdb), things get even better.</description>
			<content type="html"><![CDATA[<p>It means that all the values in a column are stored together. This is in contrast to row-oriented, in which all the values for a row are stored together. Which organization is better depends on the access pattern of your application.</p>
<p>Many operations are more efficient with a column-oriented approach. In particular, operations that need to access a sequence of values from a particular column are much faster. If all the values in a column have the same size (which is true, by design, in kdb), things get even better. This type of access pattern is typical of the applications for which q and kdb are used.</p>
<p>To make this concrete, let’s examine a column of 64-bit, floating point numbers:</p>
<pre><code>q).Q.w[] `used
108464j
q)t: ([] f: 1000000 ? 1.0)
q).Q.w[] `used
8497328j
q)
</code></pre><p>As you can see, the memory needed to hold one million 8-byte values is only a little over 8MB. That’s because the data are being stored sequentially in an array. To clarify, let’s create another table:</p>
<pre><code>q)u: update g: 1000000 ? 5.0 from t
q).Q.w[] `used
16885952j
q)
</code></pre><p>Both <!-- raw HTML omitted -->t<!-- raw HTML omitted --> and <!-- raw HTML omitted -->u<!-- raw HTML omitted --> are sharing the column <!-- raw HTML omitted -->f<!-- raw HTML omitted -->. If q organized its data in rows, the memory usage would have gone up another 8MB. Another way to confirm this is to take a look at <a href="https://github.com/KxSystems/kdb/blob/master/c/c/k.h">k.h</a>.</p>
<p>Now let’s see what happens when we write the table to disk:</p>
<pre><code>q)`:t/ set t
`:t/
q)\ls -l t
&quot;total 15632&quot;
&quot;-rw-r--r--  1 kdbfaq  staff  8000016 May 29 19:57 f&quot;
q)
</code></pre><p>16 bytes of overhead. Clearly, all of the numbers are being stored sequentially on disk. Efficiency is about avoiding unnecessary work, and here we see that q does exactly what needs to be done when reading and writing a column – no more, no less.</p>
<p><!-- raw HTML omitted -->OK, <!-- raw HTML omitted -->so this approach is space efficient. How does this data layout translate into speed?</p>
<p>If we ask q to sum all 1 million numbers, having the entire list packed tightly together in memory is a tremendous advantage over a row-oriented organization, because we’ll encounter fewer misses at every stage of the memory hierarchy. Avoiding cache misses and page faults is essential to getting performance out of your machine.</p>
<p>Moreover, doing math on a long list of numbers that are all together in memory is a problem that modern <!-- raw HTML omitted -->CPU <!-- raw HTML omitted -->instruction sets have special features to handle, including instructions to prefetch array elements that will be needed in the near future. Although those features were originally created to improve PC multimedia performance, they turned out to be great for statistics as well. In addition, the same synergy of locality and <!-- raw HTML omitted -->CPU <!-- raw HTML omitted -->features enables column-oriented systems to perform linear searches (e.g., in where clauses on unindexed columns) faster than indexed searches (with their attendant branch prediction failures) up to astonishing row counts.</p>
<p>A thorough introduction to these topics is given in Ulrich Drepper’s <a href="http://lwn.net/Articles/259710/">‘What every programmer should know about memory’</a> and Scott Meyer’s 2011 talk on <a href="http://skillsmatter.com/podcast/home/cpu-caches-and-why-you-care">‘CPU caches and why you care’</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I convert a character to its ASCII code?</title>
			<link>https://kdbfaq.com/how-do-i-convert-a-character-to-its-ascii-code/</link>
			<pubDate>Sun, 22 May 2011 15:55:31 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-convert-a-character-to-its-ascii-code/</guid>
			<description>By passing the integer type symbol, `int, as the left argument to the $ (cast) operator:
q)`int $ &amp;quot;A&amp;quot; 65 q) You can convert a list of characters at once:
q)`int $ &amp;quot;Hello, world!&amp;quot; 72 101 108 108 111 44 32 119 111 114 108 100 33 q) Alternatively, the left argument to $ (cast) can also be the integer type character, “i”or type value 6h:
q)&amp;quot;i&amp;quot; $ &amp;quot;Hello, world!&amp;quot; 72 101 108 108 111 44 32 119 111 114 108 100 33 q) q)type 1 2 3 6h q)6h $ &amp;quot;Hello, world!</description>
			<content type="html"><![CDATA[<p>By passing the integer <a href="https://code.kx.com/q/basics/datatypes/">type symbol</a>, <!-- raw HTML omitted -->`int<!-- raw HTML omitted -->, as the left argument to the <a href="https://code.kx.com/q/ref/overloads/#dollar"><!-- raw HTML omitted -->$ (cast)<!-- raw HTML omitted --></a> operator:</p>
<pre><code>q)`int $ &quot;A&quot;
65
q)
</code></pre><p>You can convert a list of characters at once:</p>
<pre><code>q)`int $ &quot;Hello, world!&quot;
72 101 108 108 111 44 32 119 111 114 108 100 33
q)
</code></pre><p>Alternatively, the left argument to <a href="https://code.kx.com/q/ref/overloads/#dollar"><!-- raw HTML omitted -->$ (cast)<!-- raw HTML omitted --></a> can also be the integer <a href="https://code.kx.com/q/basics/datatypes/">type character</a>, <!-- raw HTML omitted -->“i”<!-- raw HTML omitted --> or type value 6h:</p>
<pre><code>q)&quot;i&quot; $ &quot;Hello, world!&quot;
72 101 108 108 111 44 32 119 111 114 108 100 33
q)
q)type 1 2 3
6h
q)6h $ &quot;Hello, world!&quot;
72 101 108 108 111 44 32 119 111 114 108 100 33
q)
</code></pre><p>See also: <a href="https://code.kx.com/q/kb/unicode/" title="code.kx.com">Unicode</a>, <a href="http://en.wikipedia.org/wiki/UTF-8" title="wikipedia.org"><!-- raw HTML omitted -->UTF<!-- raw HTML omitted -->-8</a></p>
]]></content>
		</item>
		
		<item>
			<title>I’m in a hurry.  Can multiple kdb processes write simultaneously to a splayed database?</title>
			<link>https://kdbfaq.com/im-in-a-hurry-can-multiple-kdb-processes-write-simultaneously-to-a-splayed-database/</link>
			<pubDate>Sat, 21 May 2011 19:42:09 +0000</pubDate>
			
			<guid>https://kdbfaq.com/im-in-a-hurry-can-multiple-kdb-processes-write-simultaneously-to-a-splayed-database/</guid>
			<description>Short answer: Yes, multiple processes can write to a database as long as the processes avoid concurrent write operations to the same table on the same partition. To see a significant speedup, you’ll need to use segments.
 With the exception of the ? operator, which can be used to provide concurrency protection for sym files, q processes do not coordinate file I/O operations in any way. Thus, kdb splayed table write operations require the same degree of care as ordinary file writes.</description>
			<content type="html"><![CDATA[<p>Short answer: Yes, multiple processes can write to a database as long as the processes avoid concurrent write operations to the same table on the same partition. To see a significant speedup, you’ll need to use <a href="http://code.kx.com/trac/wiki/Reference/pardottxt">segments</a>.</p>
<hr>
<p>With the exception of the <a href="http://code.kx.com/trac/wiki/Reference/QuestionSymbol" title="code.kx.com"><!-- raw HTML omitted -->? operator<!-- raw HTML omitted --></a>, which can be used to provide concurrency protection for sym files, q processes do not coordinate file I/O operations in any way. Thus, kdb splayed table write operations require the same degree of care as ordinary file writes.</p>
<p>The mechanism to protect sym files, however, is used throughout the functions in the <a href="http://code.kx.com/trac/wiki/DotQ">.Q namespace</a> that pertain to writing splayed tables. So, you can use those functions to build a database faster by running multiple loader processes in parallel.</p>
<p>Example 1: Concurrent writes to the <strong>same table</strong> on the <strong>same partition</strong>. This means two processes are writing to the same (table column) files simultaneously, and that is not safe! The potential for corruption is high.</p>
<pre><code>kdb_proc1: .Q.dpft[`:/vol/db; 2011.04.07; `sym; `t]
kdb_proc2: .Q.dpft[`:/vol/db; 2011.04.07; `sym; `t] 
&lt;span style=&quot;color:blue&quot;&gt;some *blue* text&lt;/span&gt;.
</code></pre><p>Example 2: Concurrent writes to two <!-- raw HTML omitted -->different tables<!-- raw HTML omitted --> on the <!-- raw HTML omitted -->same partition<!-- raw HTML omitted -->. This is will not cause corruption.</p>
<pre><code>kdb_proc1: .Q.dpft[`:/vol/db; 2011.04.07; `sym; `t] 
kdb_proc2: .Q.dpft[`:/vol/db; 2011.04.07; `sym; `q] 
</code></pre><p>Example 3: Concurrent writes to the <!-- raw HTML omitted -->same table<!-- raw HTML omitted --> on <!-- raw HTML omitted -->different partitions<!-- raw HTML omitted -->. This is also safe, with no potential corruption.</p>
<pre><code>kdb_proc1: .Q.dpft[`:/vol/db; 2011.04.07; `sym; `t]
kdb_proc2: .Q.dpft[`:/vol/db; 2011.04.08; `sym; `t]
</code></pre><p>If the two partitions are on different I/O channels using <!-- raw HTML omitted -->segments<!-- raw HTML omitted -->, this last approach can be much faster than performing the writes serially.</p>
]]></content>
		</item>
		
		<item>
			<title>How can I reorder column names of a splayed table on disk?</title>
			<link>https://kdbfaq.com/how-can-i-reorder-column-names-of-a-splayed-table-on-disk/</link>
			<pubDate>Thu, 19 May 2011 01:22:26 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-reorder-column-names-of-a-splayed-table-on-disk/</guid>
			<description>Modify the file .d in the splayed table directory. The contents are editable via operators get and set.
 $ rlwrap q sp.q KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems +`p`city!(`p$`p1`p2`p3`p4`p5`p6`p1`p2;`london`london`london.. (+(,`color)!,`blue`green`red)!+(,`qty)!,900 1000 1200 +`s`p`qty!(`s$`s1`s1`s1`s2`s3`s4;`p$`p1`p4`p6`p2`p2`p4;300 .. q)sp s p qty ——— s1 p1 300 s1 p2 200 s1 p3 400 q)`:splaydir/ set sp `:splaydir/ q)\ls -a splaydir ,”.” “..” “.d” // this is where the col names live ,”p” “qty” ,”s” q)get `:splaydir/.</description>
			<content type="html"><![CDATA[<p>Modify the file .d in the splayed table directory. The contents are editable via operators <a href="https://code.kx.com/q/ref/get/" title="code.kx.com">get</a> and <a href="https://code.kx.com/q/ref/set/" title="code.kx.com">set</a>.</p>
<pre><code>    $ rlwrap q sp.q
    KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems
    +`p`city!(`p$`p1`p2`p3`p4`p5`p6`p1`p2;`london`london`london..
    (+(,`color)!,`blue`green`red)!+(,`qty)!,900 1000 1200
    +`s`p`qty!(`s$`s1`s1`s1`s2`s3`s4;`p$`p1`p4`p6`p2`p2`p4;300 ..
    q)sp
    s p qty
    ———
    s1 p1 300
    s1 p2 200
    s1 p3 400
    q)`:splaydir/ set sp
    `:splaydir/
    q)\ls -a splaydir
    ,”.”
    “..”
    “.d” // this is where the col names live
    ,”p”
    “qty”
    ,”s”
    q)get `:splaydir/.d
    `s`p`qty
    q)`:splaydir/.d set reverse get `:splaydir/.d
    `:splaydir/.d
    q)get `:splaydir/.d
    `qty`p`s
    q)
</code></pre><p>Verify with a fresh kdb instance:</p>
<pre><code>$ rlwrap q splaydir
KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems
q)\v
,`splaydir
q)splaydir
qty p s
——-
300 0 0
200 1 0
400 2 0
q)
</code></pre><p>See also: <a href="https://www.kdbfaq.com/what-is-the-difference-between-the-functions-xcol-and-xcols.html" title="">xcol and xcols faq</a>{.}</p>
]]></content>
		</item>
		
		<item>
			<title>How do I split a list?</title>
			<link>https://kdbfaq.com/how-do-i-split-a-list/</link>
			<pubDate>Fri, 13 May 2011 01:39:17 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-split-a-list/</guid>
			<description>If you want to split the list into lists of equal size, see this related faq on the #(take) operator.
If you want to split a string on a delimiter, use the vs(vector from scalar) function:
q)” ” vs “The quick brown fox” “The” “quick” “brown” “fox” q)”, ” vs “Hello, world!” “Hello” “world!” q) When its left argument is the null symbol, `, the vs function breaks apart a symbol on dots:</description>
			<content type="html"><![CDATA[<p>If you want to split the list into lists of equal size, see this <a href="https://www.kdbfaq.com/how-can-i-slice-a-vector-into-a-series-of-vectors-of-length.html">related faq on the <!-- raw HTML omitted -->#<!-- raw HTML omitted --> (take) operator.</a></p>
<p>If you want to split a string on a delimiter, use the <a href="http://code.kx.com/trac/wiki/Reference/vs"><!-- raw HTML omitted -->vs<!-- raw HTML omitted --> (vector from scalar)</a> function:</p>
<pre><code>q)” ” vs “The quick brown fox”
“The”
“quick”
“brown”
“fox”
q)”, ” vs “Hello, world!”
“Hello”
“world!”
q)
</code></pre><p>When its left argument is the null symbol, <!-- raw HTML omitted -->`<!-- raw HTML omitted -->, the <a href="http://code.kx.com/trac/wiki/Reference/vs"><!-- raw HTML omitted -->vs<!-- raw HTML omitted --></a> function breaks apart a symbol on dots:</p>
<pre><code>q)` vs `foo.bar.baz
`foo`bar`baz
q)
</code></pre><p>Those are the most common cases. We can also split a list into lists of varying length by passing a list of indexes as the left argument to the <a href="http://code.kx.com/trac/wiki/Reference/Underscore"><!-- raw HTML omitted -->_<!-- raw HTML omitted --> (cut)</a> operator:</p>
<pre><code>q)0 1 4 9 _ til 10
,0
1 2 3
4 5 6 7 8
,9
q)
</code></pre><p>To split a list of some type other than char using a delimiter is a little more complicated. We start by finding the indexes in the list that match the delimiter:</p>
<pre><code>q)list: 1 2 0 3 4 0 5 6
q)delimiter: 0
q)indexes: where delimiter = list
q)indexes
2 5
q)
</code></pre><p>Now we can break <!-- raw HTML omitted -->list<!-- raw HTML omitted --> into pieces using the <a href=""><!-- raw HTML omitted -->_<!-- raw HTML omitted --> (cut)</a> operator as above:</p>
<pre><code>q)indexes _ list
0 3 4
0 5 6
q)
</code></pre><p>This is almost what we want. We’ll use <!-- raw HTML omitted -->_/:<!-- raw HTML omitted --> (drop-each-right) to get rid of the delimiters:</p>
<pre><code>q)1 _/: indexes _ list
3 4
5 6
q)
</code></pre><p>We can grab the first element of the result with <a href="https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/vs"><!-- raw HTML omitted -->#<!-- raw HTML omitted --> (take):</a></p>
<pre><code>q)first[indexes] # list
1 2
q)
</code></pre><p>Then we can just join (using <a href="http://code.kx.com/trac/wiki/Reference/Comma"><!-- raw HTML omitted -->,<!-- raw HTML omitted --></a>) the two together:</p>
<pre><code>q)(enlist first[indexes] # list), 1 _/: indexes _ list
1 2
3 4
5 6
q)
</code></pre><p>Note that we must call <a href="http://code.kx.com/trac/wiki/Reference/enlist"><!-- raw HTML omitted -->enlist<!-- raw HTML omitted --></a> on the front of the list or else we’ll get something a little different from what we intended:</p>
<pre><code>q)(first[indexes] # list), 1 _/: indexes _ list
1
2
3 4
5 6
q)
</code></pre><p>Lastly, we can generalize to non-atomic types by replacing <!-- raw HTML omitted -->=<!-- raw HTML omitted --> with <!-- raw HTML omitted -->~/:<!-- raw HTML omitted --> (match-each-right):</p>
<pre><code>split: {[list; delimiter]
indexes: where delimiter ~/: list;
front: first[indexes] # list;
rest: 1 _/: indexes _ list;
: (enlist front), rest;
}
</code></pre>]]></content>
		</item>
		
		<item>
			<title>How can I find the data type of a given table column?</title>
			<link>https://kdbfaq.com/how-can-i-find-the-data-type-of-a-given-table-column/</link>
			<pubDate>Wed, 04 May 2011 03:44:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-find-the-data-type-of-a-given-table-column/</guid>
			<description>Short answer: meta tablename
For example –
q)\l sp.q / found in $QHOME/sp.q q)s s | name status city --| ------------------- s1| smith 20 london s2| jones 10 paris s3| blake 30 paris s4| clark 20 london s5| adams 30 athens q)meta s c | t f a ------| ----- s | s name | s status| i city | s q) The output of meta is a kdb table, where columns cand tindicate the column name and data type, respectively.</description>
			<content type="html"><![CDATA[<p>Short answer: <code>meta tablename</code></p>
<p>For example –</p>
<pre><code>q)\l sp.q        / found in $QHOME/sp.q
q)s
s | name  status city
--| -------------------
s1| smith 20     london
s2| jones 10     paris
s3| blake 30     paris
s4| clark 20     london
s5| adams 30     athens
q)meta s
c     | t f a
------| -----
s     | s
name  | s
status| i
city  | s
q)
</code></pre><p>The output of <a href="https://code.kx.com/q/ref/meta/">meta</a> is a kdb table, where columns <!-- raw HTML omitted -->c<!-- raw HTML omitted --> and <!-- raw HTML omitted -->t<!-- raw HTML omitted --> indicate the column name and data type, respectively.</p>
<p>The <a href="https://code.kx.com/q/ref/key/">key</a> the provides an alternate method:</p>
<pre><code>q)key exec city from s
`symbol
q)
</code></pre><p>If you need the type code, use the <a href="https://code.kx.com/q/ref/#datatypes">type</a> function:</p>
<pre><code>q)type exec city from s
11h
q)
</code></pre><p>See also:  <a href="https://code.kx.com/q/ref/#datatypes">Type character definitions</a>, <a href="https://www.kdbfaq.com/is-the-output-of-meta-available-for-use-in-my-program.html">Meta output faq</a>{.}.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I set the return value of a function?</title>
			<link>https://kdbfaq.com/how-do-i-set-the-return-value-of-a-function/</link>
			<pubDate>Wed, 27 Apr 2011 05:50:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-set-the-return-value-of-a-function/</guid>
			<description>Short answer: : return_valueUnless you use : (return) or ‘ (signal) to specify otherwise, a q function returns the value of its last expression. Since functions are lists of expressions separated by semicolons, both of the following functions return 3:
q)single_expression: {3} q)single_expression[] 3 q)last_expression: {1; 2; 3} q)last_expression[] 3 q) To return a value other than that of the last expression, use : (return):
q)explicit_return: {: 3; 4} q)explicit_return[] 3 q) The last expression in explicit_return(i.</description>
			<content type="html"><![CDATA[<p>Short answer:      <!-- raw HTML omitted -->: return_value<!-- raw HTML omitted --></p>
<p>Unless you use <a href="https://code.kx.com/q/basics/function-notation/#explicit-return"><!-- raw HTML omitted -->: (return)<!-- raw HTML omitted --></a> or <a href="https://code.kx.com/q/ref/signal/"><!-- raw HTML omitted -->‘ (signal)<!-- raw HTML omitted --></a> to specify otherwise, a q function returns the value of its last expression. Since functions are lists of expressions separated by semicolons, both of the following functions return 3:</p>
<pre><code>q)single_expression: {3}
q)single_expression[] 
3
q)last_expression: {1; 2; 3}
q)last_expression[] 
3
q)
</code></pre><p>To return a value other than that of the last expression, use <a href="https://code.kx.com/q/basics/function-notation/#explicit-return"><!-- raw HTML omitted -->: (return)<!-- raw HTML omitted --></a>:</p>
<pre><code>q)explicit_return: {: 3; 4}
q)explicit_return[] 
3
q)
</code></pre><p>The last expression in <!-- raw HTML omitted -->explicit_return<!-- raw HTML omitted --> (i.e., <!-- raw HTML omitted -->4<!-- raw HTML omitted -->) is never reached.</p>
<p>Meanwhile, if a function that does not return via <a href="https://code.kx.com/q/basics/function-notation/#explicit-return"><!-- raw HTML omitted -->: (return)<!-- raw HTML omitted --></a> (or <a href="https://code.kx.com/q/ref/signal/"><!-- raw HTML omitted -->‘ (signal)<!-- raw HTML omitted --></a>) does not have a final expression (i.e, no expression after its last semicolon), that function returns a <a href="https://code.kx.com/q/ref/identity/">generic null</a>:</p>
<pre><code>q)no_return: {3; }
q)no_return[] 
q)
q)null no_return[]
1b
q)type no_return[]
101h
q)no_return[] ~ (::)
1b
q)
</code></pre><p>Lastly, functions can exit in two other ways:</p>
<ol>
<li>Calling the <a href="https://code.kx.com/q/ref/exit/"><!-- raw HTML omitted -->exit<!-- raw HTML omitted --></a> function:</li>
</ol>
<pre><code>q)die: {exit 0}
q)die[] 
$
</code></pre><p>(By the way, you can add code to run automatically at exit using <a href="https://code.kx.com/q/ref/dotz/#zexit-action-on-exit"><!-- raw HTML omitted -->.z.exit<!-- raw HTML omitted --></a>.)</p>
<ol start="2">
<li><a href="https://code.kx.com/q/ref/signal/">Signaling</a> an error:</li>
</ol>
<pre><code>q)signal: {‘ “oops”}
q)signal[] ‘oops
q)
</code></pre><p>See <a href="https://www.kdbfaq.com/how-does-protected-execution-or-exception-handling-work-in-q.html">this related faq</a> for more information on the use of <a href="https://code.kx.com/q/ref/signal/"><!-- raw HTML omitted -->‘ (signal)<!-- raw HTML omitted --></a></p>
]]></content>
		</item>
		
		<item>
			<title>How can I test for the existence of a file or directory in q?</title>
			<link>https://kdbfaq.com/how-can-i-test-for-the-existence-of-a-file-or-directory-in-q/</link>
			<pubDate>Fri, 22 Apr 2011 03:39:04 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-test-for-the-existence-of-a-file-or-directory-in-q/</guid>
			<description>Short answer: key file_handle or key dir_handle
File handle example:
 q)\touch /tmp/test.txt q)key hsym ` $ &amp;quot;/tmp/test.txt&amp;quot; `:/tmp/test.txt q) The function keyreturns an empty list when the file does not exist:
 q)hdel `:/tmp/test.txt `:/tmp/test.txt q)() ~ key `:/tmp/test.txt 1b q) keyis one of the most heavily overloaded functions in q. It accepts an argument of type dictionary, keyed table, table column, list, and integer. It&amp;rsquo;s easy to confuse it with keys, which turns out to be an entirely different function.</description>
			<content type="html"><![CDATA[<p>Short answer: <code>key file_handle</code> or <code>key dir_handle</code></p>
<p>File handle example:</p>
<pre><code>  q)\touch /tmp/test.txt
  q)key hsym ` $ &quot;/tmp/test.txt&quot;
  `:/tmp/test.txt
  q)
</code></pre><p>The function <!-- raw HTML omitted -->key<!-- raw HTML omitted --> returns an empty list when the file does not exist:</p>
<pre><code>  q)hdel `:/tmp/test.txt
  `:/tmp/test.txt
  q)() ~ key `:/tmp/test.txt
  1b
  q)
</code></pre><p><!-- raw HTML omitted --><code>key</code><!-- raw HTML omitted --> is one of the most heavily overloaded functions in q.  It accepts an argument of type dictionary, keyed table, table column, list, and integer.  It&rsquo;s easy to confuse it with <!-- raw HTML omitted -->key<!-- raw HTML omitted -->s<!-- raw HTML omitted --><!-- raw HTML omitted -->, which turns out to be an entirely different function.</p>
<p>See also: <!-- raw HTML omitted -->~ (match)<!-- raw HTML omitted -->, <!-- raw HTML omitted -->\ (system)<!-- raw HTML omitted -->, <!-- raw HTML omitted -->hdel<!-- raw HTML omitted -->, <!-- raw HTML omitted -->hsym<!-- raw HTML omitted --></p>
]]></content>
		</item>
		
		<item>
			<title>How do I remove a key from a dictionary?</title>
			<link>https://kdbfaq.com/how-do-i-remove-a-key-from-a-dictionary/</link>
			<pubDate>Wed, 20 Apr 2011 00:34:21 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-remove-a-key-from-a-dictionary/</guid>
			<description>Pass the key you want to remove as the left argument to the _ (drop) operator, and pass the dictionary as its right argument:
q)dict: `a`b`c ! 1 2 3 q)dict a| 1 b| 2 c| 3 q)`b _ dict a| 1 c| 3 q) If you reverse the order of the arguments, the removal still works:
q)dict _ `b a| 1 c| 3 q) Although we can’t think of a good reason to do this, you might come across it.</description>
			<content type="html"><![CDATA[<p>Pass the key you want to remove as the left argument to the <a href="https://code.kx.com/q/ref/drop/" title="code.kx.com">_ (drop)</a> operator, and pass the dictionary as its right argument:</p>
<pre><code>q)dict: `a`b`c ! 1 2 3
q)dict 
a| 1 
b| 2 
c| 3
q)`b _ dict
a| 1
c| 3
q)
</code></pre><p>If you reverse the order of the arguments, the removal still works:</p>
<pre><code>q)dict _ `b
a| 1
c| 3
q)
</code></pre><p>Although we can’t think of a good reason to do this, you might come across it. As our commenter Attila pointed out, however, you are more likely to see this overload in its assignment form:</p>
<pre><code>q)dict _: `b / same as dict: dict _ `b
q)dict
a| 1
c| 3
q)
</code></pre><p>Meanwhile, you can remove multiple keys at once by passing a list of keys as the left argument to <a href="https://code.kx.com/q/ref/drop/" title="code.kx.com">_ (drop)</a>:</p>
<pre><code>q)`a`c _ dict
b| 2
q)
</code></pre><p>Reversing the arguments does not work in this case:</p>
<pre><code>q)dict _ `a`c
‘type
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>I have a very big text file.  Can I read a text file in chunks?</title>
			<link>https://kdbfaq.com/i-have-a-very-big-text-file-can-i-read-a-text-file-in-chunks/</link>
			<pubDate>Thu, 14 Apr 2011 00:35:50 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-have-a-very-big-text-file-can-i-read-a-text-file-in-chunks/</guid>
			<description>By defining a function to handle one chunk
process_chunk: {[list_of_lines] // Split and parse each line in list_of_lines and // then - most likely - create some sort of output. // After all, the idea here is to avoid holding // all of the data in memory. } and passing your chunk handler along with the file handle to .Q.fs:
 bytes_read: .Q.fs[process_chunk; `:big_file_name] &amp;lt;/blockquote&amp;gt; For details on how to parse lines of text inside your chunk handler, see this related faq</description>
			<content type="html"><![CDATA[<p>By defining a function to handle one chunk</p>
<pre><code>process_chunk: {[list_of_lines]
// Split and parse each line in list_of_lines and
// then - most likely - create some sort of output.
// After all, the idea here is to avoid holding
// all of the data in memory.
}
</code></pre><p>and passing your chunk handler along with the file handle to <a href="http://code.kx.com/trac/wiki/DotQ/DotQDotfs"><!-- raw HTML omitted -->.Q.fs<!-- raw HTML omitted --></a>:</p>
<pre><code>    bytes_read: .Q.fs[process_chunk; `:big_file_name] &lt;/blockquote&gt; 
</code></pre><p>For details on how to parse lines of text inside your chunk handler, see <a href="https://www.kdbfaq.com/how-do-i-read-in-a-text-file.html">this</a> related faq</p>
]]></content>
		</item>
		
		<item>
			<title>How do I select all columns in q?</title>
			<link>https://kdbfaq.com/how-do-i-select-all-columns-in-q/</link>
			<pubDate>Tue, 12 Apr 2011 02:57:23 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-select-all-columns-in-q/</guid>
			<description>By listing nothing at all in the select clause:
q)table: ([] x: 5 10 15 20; y: 1 2 3 4) q)table x y ---- 5 1 10 2 15 3 20 4 q)select from table where x &amp;amp;gt; 10 x y ---- 15 3 20 4 q) or SQL via s):
q)s)select * from table where x &amp;gt; 10 x y —- 15 3 20 4 q) See also: $QHOME/s.</description>
			<content type="html"><![CDATA[<p>By listing nothing at all in the select clause:</p>
<pre><code>q)table: ([] x: 5 10 15 20; y: 1 2 3 4)
q)table
x  y
----
5  1
10 2
15 3
20 4
q)select from table where x &amp;gt; 10
x  y
----
15 3
20 4
q)
</code></pre><p>or <!-- raw HTML omitted -->SQL <!-- raw HTML omitted -->via <code>s)</code>:</p>
<pre><code>q)s)select * from table where x &gt; 10
x y
—-
15 3
20 4
q)
</code></pre><p>See also: $QHOME/s.k</p>
]]></content>
		</item>
		
		<item>
			<title>How do I read in a text file?</title>
			<link>https://kdbfaq.com/how-do-i-read-in-a-text-file/</link>
			<pubDate>Tue, 12 Apr 2011 01:58:45 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-read-in-a-text-file/</guid>
			<description>Short answer:
  (types; delimiter) 0: `:filename .Q.fs[chunk_handler; `:filename]   Although there are many ways to read an ASCII file in q – depending on the content, how big the file is, and what you want to do with it – most of the time you will use one of two methods. The first method is for files you want to read into memory in their entirety, while the other approach is for situations in which you want to deal with the file in chunks.</description>
			<content type="html"><![CDATA[<p>Short answer:</p>
<blockquote>
<ol>
<li><!-- raw HTML omitted -->(types; delimiter) 0: `:filename<!-- raw HTML omitted --></li>
<li><!-- raw HTML omitted -->.Q.fs[chunk_handler; `:filename]<!-- raw HTML omitted --></li>
</ol>
</blockquote>
<p>Although there are many ways to read an <!-- raw HTML omitted -->ASCII <!-- raw HTML omitted -->file in q – depending on the content, how big the file is, and what you want to do with it – most of the time you will use one of two methods. The first method is for files you want to read into memory in their entirety, while the other approach is for situations in which you want to deal with the file in chunks. The latter scenario is covered in <a href="https://www.kdbfaq.com/i-have-a-very-big-text-file-can-i-read-a-text-file-in-chunks.html">this related faq</a>.</p>
<p>If the file is small enough (compared to the available memory in your system), you can read it all in as a list of lines in one go using <a href="https://code.kx.com/q/ref/read0/"><!-- raw HTML omitted -->read0<!-- raw HTML omitted --></a>. Given the following file, <!-- raw HTML omitted -->lines.txt<!-- raw HTML omitted -->,</p>
<pre><code>foo=10
bar=20
baz=30
</code></pre><p>we can write</p>
<pre><code>q)lines: read0 `:lines.txt
q)lines
“foo=10”
“bar=20”
“baz=30”
q)
</code></pre><p>To break up the lines, we use the <a href="https://code.kx.com/q/ref/vs/"><!-- raw HTML omitted -->vs<!-- raw HTML omitted --> (vector from scalar)</a> function, applying the <a href="https://code.kx.com/q/ref/maps/#each-left-and-each-right"><!-- raw HTML omitted -->/:<!-- raw HTML omitted --> (each right)</a> adverb so that we split each line:</p>
<pre><code>q)split: “=” vs/: lines
q)split
“foo” “10”
“bar” “20”
“baz” “30”
q)
</code></pre><p>At this point, you probably want to parse each piece of text into its corresponding type to facilitate fast searching or arithmetic etc. You use the <a href="https://code.kx.com/q/ref/cast/"><!-- raw HTML omitted -->$<!-- raw HTML omitted --> (cast)</a> operator to do this, passing an uppercase  <a href="https://code.kx.com/q/basics/datatypes/">type character</a> as its left argument:</p>
<pre><code>q)”S” $ “foo”
`foo
q)”I” $ “10”
10
q)
</code></pre><p>You may remember from <a href="https://www.kdbfaq.com/how-do-i-cast-a-string-to-a-symbol.html">this related faq</a> that you can convert a list of items at once:</p>
<pre><code>q)”S” $ (“foo”; “bar”; “baz”)
`foo`bar`baz
q)”I” $ (“10”; “20”; “30”)
10 20 30
q)
</code></pre><p>But wait! There’s more! If you pass a list of type characters as the left argument to <a href="https://code.kx.com/q/ref/cast/"><!-- raw HTML omitted -->$<!-- raw HTML omitted --></a>, you can parse multiple lists:</p>
<pre><code>q)”SI” $ ((“foo”; “bar”; “baz”); (“10”; “20”; “30”))
foo bar baz
10 20 30
q)
</code></pre><p>The list of type characters can be as long as you like:</p>
<pre><code>q)&quot;SSFI*&quot; $ (&quot;foo&quot;; &quot;bar&quot;; &quot;10.5&quot;; &quot;47&quot;; &quot;left as a string&quot;)
`foo
`bar
10.5
47
&quot;left as a string&quot;
q)
</code></pre><p>Thus, we can parse our file with the following code:</p>
<pre><code>q)”SI” $ flip “=” vs/: read0 `:lines.txt
foo bar baz
10 20 30
q)
</code></pre><p>Since this sequence of operations is so common, it has been wrapped up in an overload of that workhorse of text I/O, <a href="https://code.kx.com/q/ref/file-text/"><!-- raw HTML omitted -->0:<!-- raw HTML omitted --> (load text)</a>. The trick is to pass a pair as the left argument to <a href="https://code.kx.com/q/ref/file-text/"><!-- raw HTML omitted -->0:<!-- raw HTML omitted --></a> where the first element of the pair is the string of type characters and the second element of the pair is the delimiter between each name and value in the file:</p>
<pre><code>q)(“SI”; “=”) 0: `:lines.txt
foo bar baz
10 20 30
q)
</code></pre><p>Putting it all together, we can turn our file into a table like so:</p>
<pre><code>q)flip `name`val ! (“SI”; “=”) 0: `:lines.txt
name val
——–
foo 10
bar 20
baz 30
q)
</code></pre><p>Using <a href="https://code.kx.com/q/ref/file-text/"><!-- raw HTML omitted -->0:<!-- raw HTML omitted --></a> instead of the combination of <a href="https://code.kx.com/q/ref/read0/"><!-- raw HTML omitted -->read0<!-- raw HTML omitted --></a>, <a href="https://code.kx.com/q/ref/vs/"><!-- raw HTML omitted -->vs<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/cast/"><!-- raw HTML omitted -->$<!-- raw HTML omitted --></a> is faster and less memory-intensive. The differences become significant as the file size grows:</p>
<pre><code>q)system “wc trade_small.csv”
” 1000001 1000001 29997921 trade_small.csv”
q)\ts (“TSIF”; “,”) 0: `:trade_small.csv
554 20971840j
q)\ts “TSIF” $ flip “,” vs/: read0 `:trade_small.csv
2649 232389280j
q)
</code></pre><p>As a consequence of the <a href="https://code.kx.com/q/ref/file-text/"><!-- raw HTML omitted -->0:<!-- raw HTML omitted --></a> function’s superior memory efficiency, it can handle much larger files than the other approach:</p>
<pre><code>q)system “wc trade.csv”
” 10000001 10000001 299888328 trade_big.csv”
q)\ts (“TSIF”; “,”) 0: `:trade_big.csv
5672 335544640j
q)\ts “TSIF” $ flip “,” vs/: read0 `:trade_big.csv
wsfull
q)
</code></pre><p>If you don’t actually need to parse the file contents, then <a href="https://code.kx.com/q/ref/read0/"><!-- raw HTML omitted -->read0<!-- raw HTML omitted --></a> (by itself) is fine.</p>
<p>By the way, if you only want to grab part of the file, you can pass a triple to <a href="https://code.kx.com/q/ref/read0/"><!-- raw HTML omitted -->read0<!-- raw HTML omitted --></a> in order to read a subset of the bytes. You’ll still get a list of lines broken on newlines:</p>
<pre><code>q)offset: 3
q)number_of_bytes_to_read: 6
q)read0 (`:lines.txt; offset; number_of_bytes_to_read)
“=10”
“ba”
q)
</code></pre><p>Unless your file has fixed-length records, however, you may find it easier – assuming you have the <a href="http://linux.die.net/man/1/head"><!-- raw HTML omitted -->head<!-- raw HTML omitted --></a> and <a href="http://linux.die.net/man/1/tail"><!-- raw HTML omitted -->tail<!-- raw HTML omitted --></a> utilities (or similar) available, to use the<!-- raw HTML omitted -->system<!-- raw HTML omitted --><!-- raw HTML omitted --> function to get exactly the lines you want. For example,<!-- raw HTML omitted --></p>
<pre><code>q)first_line: first system “head -1 lines.txt”
q)
</code></pre><p>(Note the call to <!-- raw HTML omitted -->first<!-- raw HTML omitted --><!-- raw HTML omitted -->; <!-- raw HTML omitted -->system<!-- raw HTML omitted --><!-- raw HTML omitted --> always returns a list of strings, even when there is only one.) This particular example is handy when you need to examine the start of a file to figure out how to read it properly.<!-- raw HTML omitted --></p>
]]></content>
		</item>
		
		<item>
			<title>How do I convert from symbol to integer?</title>
			<link>https://kdbfaq.com/how-do-i-convert-from-symbol-to-integer/</link>
			<pubDate>Thu, 07 Apr 2011 02:25:42 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-convert-from-symbol-to-integer/</guid>
			<description>Convert to string, then to int by applying the $(cast) operator while passing an uppercase type character as its left argument:
q)”I” $ string `123 123 q) Type number also works:
q)type 123 -6h q)-6h $ string `123 123 q) See also: string to symbol conversion faq{.}, Datatypes and $</description>
			<content type="html"><![CDATA[<p>Convert to string, then to int by applying the <a href="http://code.kx.com/trac/wiki/Reference/DollarSign"><!-- raw HTML omitted -->$<!-- raw HTML omitted --> (cast)</a> operator while passing an <a href="http://code.kx.com/trac/wiki/Reference/Datatypes#PrimitiveTypes">uppercase type character</a> as its left argument:</p>
<pre><code>q)”I” $ string `123
123
q)
</code></pre><p>Type number also works:</p>
<pre><code>q)type 123
-6h
q)-6h $ string `123
123
q)
</code></pre><p>See also: <a href="https://www.kdbfaq.com/how-do-i-cast-a-string-to-a-symbol.html">string to symbol conversion faq</a>{.}, <a href="http://www.kx.com/q/d/a/kdb+.htm#Datatypes"><!-- raw HTML omitted -->Datatypes<!-- raw HTML omitted --></a> and <a href="http://code.kx.com/trac/wiki/Reference/DollarSign"><!-- raw HTML omitted -->$<!-- raw HTML omitted --></a></p>
]]></content>
		</item>
		
		<item>
			<title>How do I cast a string to a symbol?</title>
			<link>https://kdbfaq.com/how-do-i-cast-a-string-to-a-symbol/</link>
			<pubDate>Sun, 03 Apr 2011 17:07:49 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-cast-a-string-to-a-symbol/</guid>
			<description>By applying the $(cast) operator while passing `(the null symbol) as its left argument:
q)` $ “foo” `foo q) The cast operator also accepts an uppercase type character as its left argument:
q)”S” $ “foo” `foo q) Moreover, you can convert a list of strings at once:
q)”S” $ (“foo”; “bar”; “baz”) `foo`bar`baz q) To go the other way, use the string function:
q)string `foo “foo” q) Since the string function is implemented as the monadic form (i.</description>
			<content type="html"><![CDATA[<p>By applying the <a href="https://code.kx.com/q/ref/cast/"><!-- raw HTML omitted -->$<!-- raw HTML omitted --> (cast)</a> operator while passing <!-- raw HTML omitted -->`<!-- raw HTML omitted --> (the null symbol) as its left argument:</p>
<pre><code>q)` $ “foo”
`foo
q)
</code></pre><p>The cast operator also accepts an <a href="https://code.kx.com/q/basics/datatypes/">uppercase type character</a> as its left argument:</p>
<pre><code>q)”S” $ “foo”
`foo
q)
</code></pre><p>Moreover, you can convert a list of strings at once:</p>
<pre><code>q)”S” $ (“foo”; “bar”; “baz”)
`foo`bar`baz
q)
</code></pre><p>To go the other way, use the <a href="https://code.kx.com/q/ref/string/"><!-- raw HTML omitted -->string<!-- raw HTML omitted --></a> function:</p>
<pre><code>q)string `foo
“foo”
q)
</code></pre><p>Since the <a href="https://code.kx.com/q/ref/string/"><!-- raw HTML omitted -->string<!-- raw HTML omitted --></a> function is implemented as the monadic form (i.e., single argument overload) of the k function <!-- raw HTML omitted -->$<!-- raw HTML omitted --> —</p>
<pre><code>q)string
$:
q)
</code></pre><p>— it is also possible to write the above cast as follows:</p>
<pre><code>q)($)`foo
“foo”
q)
</code></pre><p>Although we don’t recommend it, we thought you should know in case you see it in the wild.</p>
<p>See also: <a href="https://code.kx.com/q/ref/type/"><!-- raw HTML omitted -->type<!-- raw HTML omitted --></a></p>
]]></content>
		</item>
		
		<item>
			<title>How do I parse a ctrl-A delimited string?</title>
			<link>https://kdbfaq.com/how-do-i-parse-a-ctrl-a-delimited-string/</link>
			<pubDate>Sat, 02 Apr 2011 16:51:25 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-parse-a-ctrl-a-delimited-string/</guid>
			<description>Short answer: “\001” vs data
Use the vs(vector from scalar) function:
q)fstring “f1=va\001f2=vb\001f3=vc” q)”\001″ vs fstring “f1=va” “f2=vb” “f3=vc” q) We can combine vs with /:(each right) to break up each component:
q)”=” vs/: “\001” vs fstring “f1” “va” “f2” “vb” “f3” “vc” q) Note that you cannot put any space between vs and /:. If you did, that would be a comment.
We might next turn fstring’scontents into a table using a combination of flip and !</description>
			<content type="html"><![CDATA[<p>Short answer: <code>“\001” vs data</code></p>
<p>Use the <a href="https://code.kx.com/q/ref/vs/"><!-- raw HTML omitted -->vs<!-- raw HTML omitted --> (vector from scalar)</a> function:</p>
<pre><code>q)fstring
“f1=va\001f2=vb\001f3=vc”
q)”\001″ vs fstring
“f1=va”
“f2=vb”
“f3=vc”
q)
</code></pre><p>We can combine <a href="https://code.kx.com/q/ref/vs/"><!-- raw HTML omitted -->vs<!-- raw HTML omitted --></a> with <a href="https://code.kx.com/q/ref/maps/#each-left-and-each-right"><!-- raw HTML omitted -->/:<!-- raw HTML omitted --> (each right)</a> to break up each component:</p>
<pre><code>q)”=” vs/: “\001” vs fstring
“f1” “va”
“f2” “vb”
“f3” “vc”
q)
</code></pre><p>Note that you cannot put any space between <a href="https://code.kx.com/q/ref/vs/"><!-- raw HTML omitted -->vs<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/maps/#each-left-and-each-right"><!-- raw HTML omitted -->/:<!-- raw HTML omitted --></a>. If you did, that would be a <a href="https://www.kdbfaq.com/how-do-i-comment-q-code.html">comment</a>.</p>
<p>We might next turn <!-- raw HTML omitted -->fstring’s<!-- raw HTML omitted --> contents into a table using a combination of <a href="https://code.kx.com/q/ref/flip/"><!-- raw HTML omitted -->flip<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/dict/"><!-- raw HTML omitted -->!<!-- raw HTML omitted --> (dict)</a>:</p>
<pre><code>q)flip &quot;=&quot; vs/: &quot;\001&quot; vs fstring
&quot;f1&quot; &quot;f2&quot; &quot;f3&quot;
&quot;va&quot; &quot;vb&quot; &quot;vc&quot;
q)`field`value ! flip &quot;=&quot; vs/: &quot;\001&quot; vs fstring
field| &quot;f1&quot; &quot;f2&quot; &quot;f3&quot;
value| &quot;va&quot; &quot;vb&quot; &quot;vc&quot;
q)flip `field`value ! flip &quot;=&quot; vs/: &quot;\001&quot; vs fstring
field value
-----------
&quot;f1&quot;  &quot;va&quot;
&quot;f2&quot;  &quot;vb&quot;
&quot;f3&quot;  &quot;vc&quot;
q)
</code></pre><p>This is almost what we want. Usually, though, you want the field names to be symbols rather than strings. We can do that by <a href="https://code.kx.com/q/ref/apply/"><em>applying</em> <!-- raw HTML omitted -->(@)<!-- raw HTML omitted --></a> the <a href="https://code.kx.com/q/ref/cast/"><!-- raw HTML omitted -->$<!-- raw HTML omitted --> (cast)</a> operator to (only) the values of the field column:</p>
<pre><code>q)columns: @[flip &quot;=&quot; vs/: &quot;\001&quot; vs fstring; 0; `$]
q)columns
f1   f2   f3
&quot;va&quot; &quot;vb&quot; &quot;vc&quot;
q)flip `field`value ! columns
field value
-----------
f1    &quot;va&quot;
f2    &quot;vb&quot;
f3    &quot;vc&quot;
q)
</code></pre><p>However, there is a shortcut we can take to deconstruct the string into a table using one of the many variants of <a href="https://code.kx.com/q/ref/file-text/"><!-- raw HTML omitted -->0:<!-- raw HTML omitted --></a>:</p>
<pre><code>q)flip `field`value ! “S=\001” 0: fstring
field value
———–
f1 “va”
f2 “vb”
f3 “vc”
q)
</code></pre><p>Not only is this last example more succinct, it’s much faster:</p>
<pre><code>q)\t do[100000;
flip `field`value !
@[flip &quot;=&quot; vs/: &quot;\001&quot; vs fstring; 0; `$]]
485
q)\t do[100000; flip `field`value ! &quot;S=\001&quot; 0: fstring]
110
q)
</code></pre><p>See also <a href="https://www.kdbfaq.com/how-do-i-build-a-ctrl-a-delimited-string.html">How do I build a ctrl-A delimited string?</a></p>
]]></content>
		</item>
		
		<item>
			<title>How do I build a ctrl-A delimited string?</title>
			<link>https://kdbfaq.com/how-do-i-build-a-ctrl-a-delimited-string/</link>
			<pubDate>Sat, 02 Apr 2011 00:03:05 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-build-a-ctrl-a-delimited-string/</guid>
			<description>Short answer: “\001” sv (“one”; “two”; “three”)
To build delimited strings in general, use the sv(scalar from vector) function:
q)”, ” sv (“Hello”; “world!”) “Hello, world!” q) As in many programming languages, the syntax for non-printable ASCII characters is borrowed from C, although only a subset of C’s sequences is supported:
\n newline \r carriage return \t tab (q also supports a few printable escape sequences: \, &amp;amp;#8221;and &amp;amp;#8217;). However, as in C, you can express any ASCII code in q by following a backslash with the code’s 3 digit octal representation:</description>
			<content type="html"><![CDATA[<p>Short answer: <code>“\001” sv (“one”; “two”; “three”)</code></p>
<p>To build delimited strings in general, use the <a href="https://code.kx.com/q/ref/sv/"><!-- raw HTML omitted -->sv<!-- raw HTML omitted --> (scalar from vector)</a> function:</p>
<pre><code>q)”, ” sv (“Hello”; “world!”)
“Hello, world!”
q)
</code></pre><p>As in many programming languages, the syntax for <a href="http://en.wikipedia.org/wiki/ASCII#ASCII_control_characters">non-printable <!-- raw HTML omitted -->ASCII <!-- raw HTML omitted -->characters</a> is borrowed from C, although only a subset of C’s sequences is supported:</p>
<pre><code>\n      newline
\r      carriage return
\t      tab
</code></pre><p>(q also supports a few printable escape sequences: <!-- raw HTML omitted -->\<!-- raw HTML omitted -->, <!-- raw HTML omitted -->&amp;#8221;<!-- raw HTML omitted --> and <!-- raw HTML omitted -->&amp;#8217;<!-- raw HTML omitted -->). However, as in C, you can express any <!-- raw HTML omitted -->ASCII <!-- raw HTML omitted -->code in q by following a backslash with the code’s 3 digit octal representation:</p>
<pre><code>q)”\054\040″ sv (“Hello”; “world!”)
“Hello, world!”
q)
</code></pre><p>Since ctrl-A is <!-- raw HTML omitted -->ASCII<!-- raw HTML omitted --> 1, we need to use <!-- raw HTML omitted -->\001<!-- raw HTML omitted -->:</p>
<pre><code>q)fstring: “\001” sv (“f1=va”; “f2=vb”; “f3=vc”)
q)fstring
“f1=va\001f2=vb\001f3=vc”
q)
</code></pre><p>We can use <a href="https://www.kdbfaq.com/how-do-i-save-a-table-to-delimited-text.html"><!-- raw HTML omitted -->0:<!-- raw HTML omitted --></a> to write <!-- raw HTML omitted -->fstring<!-- raw HTML omitted --> to a file, and use an external program to confirm the result:</p>
<pre><code>q)`:test 0: enlist fstring
`:test
q)\\
$ hexdump test
0000000 66 31 3d 76 61 01 66 32 3d 76 62 01 66 33 3d 76
0000010 63 0a
0000012
q)
</code></pre><p>To break <!-- raw HTML omitted -->fstring<!-- raw HTML omitted --> up into its parts, see <a href="https://www.kdbfaq.com/how-do-i-parse-a-ctrl-a-delimited-string.html">How do I parse a ctrl-A delimited string?</a></p>
]]></content>
		</item>
		
		<item>
			<title>How can I measure the performance of my q code?</title>
			<link>https://kdbfaq.com/how-can-i-measure-the-performance-of-my-q-code/</link>
			<pubDate>Sun, 27 Mar 2011 16:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-measure-the-performance-of-my-q-code/</guid>
			<description>The simplest way to time something in q is to use the \t command:
q)f: {[] do[100000; 2 + 2]} q)\t f[] 10 q) \t executes its argument and returns the number of milliseconds that elapsed – i.e., wall clock time (except when you are using \t in its other sense, i.e., setting or getting the time between timer events).
When using kdb as a database server, you will want to use one or more of Simon’s logging scripts as a starting point.</description>
			<content type="html"><![CDATA[<p>The simplest way to time something in q is to use the <a href="https://code.kx.com/q/basics/syscmds/#t-timer"><!-- raw HTML omitted -->\t<!-- raw HTML omitted --></a> command:</p>
<pre><code>q)f: {[] do[100000; 2 + 2]}
q)\t f[]
10
q)
</code></pre><p><a href="https://code.kx.com/q/basics/syscmds/#t-timer"><!-- raw HTML omitted -->\t<!-- raw HTML omitted --></a> executes its argument and returns the number of milliseconds that elapsed – i.e., wall clock time (except when you are using <a href="https://code.kx.com/q/basics/syscmds/#t-timer"><!-- raw HTML omitted -->\t<!-- raw HTML omitted --></a> in its other sense, i.e., <a href="https://www.kdbfaq.com/how-do-i-use-the-timer.html">setting or getting the time between timer events</a>).</p>
<p>When using kdb as a database server, you will want to use one or more of <a href="https://code.kx.com/q/ref/#z">Simon’s logging scripts</a> as a starting point. These tremendously useful scripts enable you to record every incoming query as well as measure the time taken by every incoming query. That way you can calculate summary statistics on actual database performance in order to find and fix intermittent problems.</p>

<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
  <iframe src="https://www.youtube.com/embed/1fqh5rWFJPQ" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" allowfullscreen title="YouTube Video"></iframe>
</div>

]]></content>
		</item>
		
		<item>
			<title>How do I declare a table column of type string (not symbol!)?</title>
			<link>https://kdbfaq.com/how-do-i-declare-a-table-column-of-type-string-not-symbol/</link>
			<pubDate>Sun, 27 Mar 2011 15:19:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-declare-a-table-column-of-type-string-not-symbol/</guid>
			<description>Declare it without a type as follows:
q)t: ([] str: ()) q)meta t c | t f a ---| ----- str| q) A the type of a column defined as ()is determined when the first row is inserted:
q)`t insert enlist enlist &amp;quot;foo&amp;quot; ,0 q)select from t str ----- &amp;quot;foo&amp;quot; q) </description>
			<content type="html"><![CDATA[<p>Declare it without a type as follows:</p>
<pre><code>q)t: ([] str: ())
q)meta t
c  | t f a
---| -----
str|
q)
</code></pre><p>A the type of a column defined as <!-- raw HTML omitted -->()<!-- raw HTML omitted --> is determined when the first row is inserted:</p>
<pre><code>q)`t insert enlist enlist &quot;foo&quot;
,0
q)select from t
str  
-----
&quot;foo&quot;
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>Can a table be partitioned but not be splayed?</title>
			<link>https://kdbfaq.com/can-a-table-be-partitioned-but-not-be-splayed/</link>
			<pubDate>Sun, 27 Mar 2011 13:35:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/can-a-table-be-partitioned-but-not-be-splayed/</guid>
			<description>No. A partitioned table is a splayed table.
See also: Splayed Tables</description>
			<content type="html"><![CDATA[<p>No. A partitioned table is a splayed table.</p>
<p>See also: <a href="https://code.kx.com/q/kb/splayed-tables/" title="code.kx.com">Splayed Tables</a></p>
]]></content>
		</item>
		
		<item>
			<title>What are some of the freely available software packages related to kdb?</title>
			<link>https://kdbfaq.com/what-are-some-of-the-freely-available-software-packages-related-to-kdb/</link>
			<pubDate>Sat, 26 Mar 2011 22:43:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-are-some-of-the-freely-available-software-packages-related-to-kdb/</guid>
			<description>Testing  k4unit qspec  IDEs  qkdt QInsightPad – Public Beta studio for kdb+  Libraries  Perl-Compatible Regular Expressions for q q Math Library  Tools  Doxygen filters Linq2Kdb kp.net perl kx.pm Sybase kdb+ driver  See also: Useful companion tools</description>
			<content type="html"><![CDATA[<h3 id="testing">Testing</h3>
<ul>
<li><a href="https://github.com/simongarland/k4unit">k4unit</a></li>
<li><a href="https://github.com/nugend/qspec">qspec</a></li>
</ul>
<h3 id="span-classcapsidespans"><!-- raw HTML omitted -->IDE<!-- raw HTML omitted -->s</h3>
<ul>
<li><a href="http://www.qkdt.org/">qkdt</a></li>
<li><a href="http://www.qinsightpad.com/">QInsightPad – Public Beta</a></li>
<li><a href="https://anonymous:anonymous@code.kx.com/trac/wiki/studioforkdb%2B">studio for kdb+</a></li>
</ul>
<h3 id="libraries">Libraries</h3>
<ul>
<li><a href="http://q.o.potam.us/?p=pcre">Perl-Compatible Regular Expressions for q</a></li>
<li><a href="http://althenia.net/qml">q Math Library</a></li>
</ul>
<h3 id="tools">Tools</h3>
<ul>
<li><a href="http://sourceforge.net/projects/doxyf/">Doxygen filters</a></li>
<li><a href="http://weblogs.asp.net/sweinstein/archive/2009/03/03/linq2kdb-provider-source-code-update.aspx">Linq2Kdb</a></li>
<li><a href="http://kpnet.codeplex.com/">kp.net</a></li>
<li><a href="http://search.cpan.org/~markpf/Kx-0.039/lib/Kx.pm">perl kx.pm</a></li>
<li><a href="http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc01028.0400/doc/html/cgo1276007338307.html">Sybase kdb+ driver</a></li>
</ul>
<p>See also: <a href="https://www.kdbfaq.com/what-companion-tools-to-kdb-are-useful.html">Useful companion tools</a></p>
]]></content>
		</item>
		
		<item>
			<title>q truncates the results in stdout.  How can I fix it?</title>
			<link>https://kdbfaq.com/q-truncates-the-results-in-stdout-how-can-i-fix-it/</link>
			<pubDate>Sat, 26 Mar 2011 22:17:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/q-truncates-the-results-in-stdout-how-can-i-fix-it/</guid>
			<description>To set q’s console output to 80 columns wide and 24 rows high (console size), use \c:
 q)\c 80 24 You can also use the $LINES and $COLUMNS environment variables to have q start up automatically with your preferred settings:
$ export LINES=40 $ export COLUMNS=120 $ q KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems q)\c 40 120 q) To adjust the amount of output when access a q server via a web browser, see http page size (\C)</description>
			<content type="html"><![CDATA[<p>To set q’s console output to 80 columns wide and 24 rows high (<a href="https://code.kx.com/q/basics/syscmds/#c-console-size">console size</a>), use \c:</p>
<pre><code>    q)\c 80 24
</code></pre><p>You can also use the $LINES and $COLUMNS environment variables to have q start up automatically with your preferred settings:</p>
<pre><code>$ export LINES=40
$ export COLUMNS=120
$ q
KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems
q)\c
40 120
q)
</code></pre><p>To adjust the amount of output when access a q server via a web browser, see <a href="http://code.kx.com/trac/wiki/Reference/SystemCommands#Chw-httpheightwidth" title="code.kx.com"><!-- raw HTML omitted -->http page size (\C)<!-- raw HTML omitted --></a></p>
<p>Lastly, you may be interested in <a href="https://code.kx.com/q/ref/dotq/#qs-plain-text" title="code.kx.com">.Q.s</a> and <a href="https://code.kx.com/q/ref/dotq/#qs1-string-representation" title="code.kx.com">.Q.s1</a></p>
]]></content>
		</item>
		
		<item>
			<title>How do I use the timer?</title>
			<link>https://kdbfaq.com/how-do-i-use-the-timer/</link>
			<pubDate>Sat, 26 Mar 2011 16:19:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-use-the-timer/</guid>
			<description>If you defined a function called .z.ts, and enable q’s timer with \t n then q will call .z.ts every nmilliseconds:
q).z.ts: {[] show .z.T} q)\t 500 q)07:41:15.147 07:41:15.647 07:41:16.147 07:41:16.647 07:41:17.147 \t 0 q) As shown above, \t 0 stops the timer.
To set the timer interval, you must give \t a literal integer. What that means is that, if you want to change the timer frequency at runtime (e.</description>
			<content type="html"><![CDATA[<p>If you defined a function called <a href="https://code.kx.com/q/ref/dotz/#zts-timer"><!-- raw HTML omitted -->.z.ts<!-- raw HTML omitted --></a>, and enable q’s timer with <a href="https://code.kx.com/q/basics/syscmds/#t-timer"><!-- raw HTML omitted -->\t n<!-- raw HTML omitted --></a> then q will call <a href="https://code.kx.com/q/ref/dotz/#zts-timer"><!-- raw HTML omitted -->.z.ts<!-- raw HTML omitted --></a> every <!-- raw HTML omitted -->n<!-- raw HTML omitted --> milliseconds:</p>
<pre><code>q).z.ts: {[] show .z.T}
q)\t 500
q)07:41:15.147
07:41:15.647
07:41:16.147
07:41:16.647
07:41:17.147
\t 0
q)
</code></pre><p>As shown above, <a href="https://code.kx.com/q/basics/syscmds/#t-timer"><!-- raw HTML omitted -->\t 0<!-- raw HTML omitted --></a> stops the timer.</p>
<p>To set the timer interval, you must give <a href="https://code.kx.com/q/basics/syscmds/#t-timer"><!-- raw HTML omitted -->\t<!-- raw HTML omitted --></a> a <em>literal</em> integer. What that means is that, if you want to change the timer frequency at runtime (e.g., when building a simple scheduler), the following will not work:</p>
<pre><code>q)i: 500
q).z.ts: {[] show .z.T; system “t i”; i *: 2}
q)\t 500
q)07:46:47.106
07:46:47.606
07:46:48.106
07:46:48.606
\t 0
q)
</code></pre><p>Notice what happens when we enter <a href="https://code.kx.com/q/basics/syscmds/#t-timer"><!-- raw HTML omitted -->\t i<!-- raw HTML omitted --></a> at the repl:</p>
<pre><code>q)\t i
0
q)
</code></pre><p>What we’ve done is use <a href="https://code.kx.com/q/basics/syscmds/#t-timer"><!-- raw HTML omitted -->\t<!-- raw HTML omitted --></a> tomeasure the execution time<!-- raw HTML omitted --> of the expression <!-- raw HTML omitted -->i<!-- raw HTML omitted -->. To get the effect we want is, fortunately, easy once you see what is going on:<!-- raw HTML omitted --></p>
<pre><code>q)i: 500
q).z.ts: {[] show .z.T; system “t “, string i; i *: 2}
q)\t 500
q)07:59:59.694
08:00:00.195
08:00:01.195
08:00:03.196
\t 0
q)
</code></pre><p>By passing <!-- raw HTML omitted -->“t “, string i<!-- raw HTML omitted --> instead of <!-- raw HTML omitted -->“t i”<!-- raw HTML omitted --> to <a href="https://code.kx.com/q/ref/system/"><!-- raw HTML omitted -->system<!-- raw HTML omitted --></a>, the q interpreter sees a literal integer.</p>
<p>One last detail: if you decide you need to delete the definition of <a href="https://code.kx.com/q/ref/dotz/#zts-timer"><!-- raw HTML omitted -->.z.ts<!-- raw HTML omitted --></a>, you’ll need to use <a href="https://www.kdbfaq.com/how-do-i-delete-a-function-in-namespace-z.html">\x</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>What environment variables do I need to know about when kdb starts up?</title>
			<link>https://kdbfaq.com/what-environment-variables-do-i-need-to-know-about-when-kdb-starts-up/</link>
			<pubDate>Sat, 26 Mar 2011 01:40:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-environment-variables-do-i-need-to-know-about-when-kdb-starts-up/</guid>
			<description>Here are several environment variables used by q during initialization:
 $QLIC $QHOME %WinDir% (only on w32 and w64 OS) $QINIT $LINES $COLUMNS $LD_LIBRARY_PATH for dynamic load 2:  You can read the value of any environment variable with the getenv function:
q)getenv `PATH&amp;lt;br /&amp;gt; &amp;amp;#8220;/sw/bin:/sw/sbin:/usr/bin:/bin:/usr/sbin:/sbin:..&amp;lt;br /&amp;gt; q) </description>
			<content type="html"><![CDATA[<p>Here are several environment variables used by q during initialization:</p>
<ul>
<li>$QLIC</li>
<li>$QHOME</li>
<li>%WinDir% (only on w32 and w64 OS)</li>
<li><a href="https://www.kdbfaq.com/when-i-launch-kdb-with-a-directory-what-exactly-happens-on-s.html">$QINIT</a></li>
<li><a href="https://www.kdbfaq.com/q-truncates-the-results-in-stdout-how-can-i-fix-it.html">$LINES</a></li>
<li><a href="https://www.kdbfaq.com/q-truncates-the-results-in-stdout-how-can-i-fix-it.html">$COLUMNS</a></li>
<li>$LD_LIBRARY_PATH for dynamic load <a href="http://code.kx.com/trac/wiki/Reference/TwoColon"><!-- raw HTML omitted -->2:<!-- raw HTML omitted --></a></li>
</ul>
<p>You can read the value of any environment variable with the <a href="http://code.kx.com/trac/wiki/Reference/getenv"><!-- raw HTML omitted -->getenv<!-- raw HTML omitted --></a> function:</p>
<pre><code>q)getenv `PATH&lt;br /&gt; &amp;#8220;/sw/bin:/sw/sbin:/usr/bin:/bin:/usr/sbin:/sbin:..&lt;br /&gt; q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>I know k sits under q.  By porting q code to k, will it run faster?</title>
			<link>https://kdbfaq.com/i-know-k-sits-under-q-by-porting-q-code-to-k-will-it-run-faster/</link>
			<pubDate>Sat, 26 Mar 2011 00:42:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-know-k-sits-under-q-by-porting-q-code-to-k-will-it-run-faster/</guid>
			<description>No. The interpreter boils it down to the same bytecode.
Consider Problem 1 from Project Euler: sum the multiples of 3 and 5 which are less than 1000. You may want to try this before reading further. The problems from Project Euler are great exercises for learning q!
The code below shows one solution written in both languages; f is written in q, while g is written in k.
q)f: {(+/) distinct where (0 = x mod 3) | 0 = x mod 5} q)\ g: {+/?</description>
			<content type="html"><![CDATA[<p>No. The interpreter boils it down to the same <a href="http://en.wikipedia.org/wiki/Bytecode">bytecode</a>.</p>
<p>Consider <a href="http://projecteuler.net/index.php?section=problems&amp;id=1">Problem 1</a> from <a href="http://projecteuler.net">Project Euler</a>: sum the multiples of 3 and 5 which are less than 1000. You may want to try this before reading further. The problems from <a href="http://projecteuler.net">Project Euler</a> are great exercises for learning q!</p>
<p>The code below shows one solution written in both languages; <code>f</code> is written in q, while <code>g</code> is written in k.</p>
<pre><code>q)f: {(+/) distinct where (0 = x mod 3) | 0 = x mod 5}
q)\
g: {+/?&amp;(0={x-y*x div y}[x;3])|0={x-y*x div y}[x;5]}
\
q)
</code></pre><p>You can see the bytecode for a function (as well as some generally more useful information, like the function’s arguments) by calling <a href="https://code.kx.com/q/ref/value/">value</a> on it:</p>
<pre><code>q)value f
0xa278a10a020c48a078a10a020c48462531a31b520004
,`x
`symbol$()
,`
3
k){x-y*x div y}
5
+
“{(+/) distinct where (0 = x mod 3) | 0 = x mod 5}”
q)
</code></pre><p>As you can see, when passed a function, <a href="https://code.kx.com/q/ref/value/">value</a> returns a list. The first element of that list is the function’s bytecode. Now it is easy to show that <code>f</code> and <code>g</code> have the same bytecode:</p>
<pre><code>q)first value f
0xa278a10a020c48a078a10a020c48462531a31b520004
q)first value g
0xa278a10a020c48a078a10a020c48462531a31b520004
q)all (first value f) = first value g
1b
q)
</code></pre><p>In q, however, you probably would have written the solution a tiny bit differently:</p>
<pre><code>q)f: {sum distinct where (0 = x mod 3) | 0 = x mod 5}
q)
</code></pre><p>This results in a q version that is actually two bytes smaller and (maybe) a hair faster:</p>
<pre><code>q)first value f
0xa278a10a020c48a078a10a020c48462531390004
q)first value g
0xa278a10a020c48a078a10a020c48462531a31b520004
q)\t do[100000; f til 1000] 3240
q)\t do[100000; g til 1000] 3253
q)
</code></pre><p><em>Thanks to Charlie Skelton from</em> <a href="http://kx.com"><em>kx</em></a> <em>for pointing out errors in the original version of this article.</em></p>
]]></content>
		</item>
		
		<item>
			<title>I defined an untyped list, but I get a type error when I add more than one element to it?  How do I store mixed data in a list?</title>
			<link>https://kdbfaq.com/i-defined-an-untyped-list-but-i-get-a-type-error-when-i-add-more-than-one-element-to-it-how-do-i-store-mixed-data-in-a-list/</link>
			<pubDate>Fri, 25 Mar 2011 22:54:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-defined-an-untyped-list-but-i-get-a-type-error-when-i-add-more-than-one-element-to-it-how-do-i-store-mixed-data-in-a-list/</guid>
			<description>If you are defining the list’s contents at the same time you declare it, this is easy:
q)list: (`sector; 47) q)type list 0h q)list ,: 2.7 q)list `sector 47 2.7 q) However, you often don’t know what items are going in the list in advance. Let’s try defining an empty list without specifying an element type:
q)list: () q) At first, that seems to be just what we wanted:
q)type list 0h q) The trouble begins when we actually add elements to the list:</description>
			<content type="html"><![CDATA[<p>If you are defining the list’s contents at the same time you declare it, this is easy:</p>
<pre><code>q)list: (`sector; 47)
q)type list
0h
q)list ,: 2.7
q)list
`sector
47
2.7
q)
</code></pre><p>However, you often don’t know what items are going in the list in advance. Let’s try defining an empty list without specifying an element type:</p>
<pre><code>q)list: ()
q)
</code></pre><p>At first, that seems to be just what we wanted:</p>
<pre><code>q)type list
0h
q)
</code></pre><p>The trouble begins when we actually add elements to the list:</p>
<pre><code>q)list ,: `sector
q)list ,: 47
‘type
q)
</code></pre><p>What happened? Let’s re-examine <!-- raw HTML omitted -->list<!-- raw HTML omitted -->‘s type:</p>
<pre><code>q)type list
11h
q)
</code></pre><p>Now <!-- raw HTML omitted -->list<!-- raw HTML omitted -->‘s type is no longer <code>0h</code>; it has been transmuted into <code>11h</code>; i.e., list of symbol. The <!-- raw HTML omitted -->‘type<!-- raw HTML omitted --> error is telling us that we can’t add an <!-- raw HTML omitted -->int<!-- raw HTML omitted --> to a list of <!-- raw HTML omitted -->symbol<!-- raw HTML omitted -->.</p>
<p>In some situations, determining the type of an empty list dynamically (i.e., when the first item is added) may be what you want. A list of <!-- raw HTML omitted -->symbol<!-- raw HTML omitted --> (or <!-- raw HTML omitted -->int<!-- raw HTML omitted -->) uses less memory that an untyped list with the same number of elements. Most operations on a typed list will be faster as well.</p>
<p>In this case, however, we need a way to prevent q from promoting the untyped list to a typed list. The only way to do that is to stuff the list – when you create it – with some data that can’t fit into a typed list. While you could use two values of different types (as in our first example), you only need to use one value if that value is itself a list. Our practice to use a list of characters, i.e., a string:</p>
<pre><code>q)list: enlist “sentinel”
q)type list
0h
q)list ,: `sector
q)list ,: 47
q)count list
3
q)
</code></pre><p>Note that the use of <a href="https://code.kx.com/q/ref/enlist/"><!-- raw HTML omitted -->enlist<!-- raw HTML omitted --></a> is essential; without it, <!-- raw HTML omitted -->list<!-- raw HTML omitted --> is simply the string:</p>
<pre><code>q)list: (“sentinel”)
q)type list
10h
q)count list
8
q)
</code></pre><p>We use the string <!-- raw HTML omitted -->“sentinel”<!-- raw HTML omitted --> because the term sentinel has been used for decades in computer science to denote a value in a data structure that isn’t actually part of the data, but rather signals some special condition to the program. It also happens to be a term that doesn’t come up often in other domains.</p>
<p>Of course, any code that reads or writes to <!-- raw HTML omitted -->list<!-- raw HTML omitted --> needs to understand that the first element is to be ignored. (In our experience, the less code that is aware of that, the less time we spend debugging.) In particular, you must never remove all the data from <!-- raw HTML omitted -->list<!-- raw HTML omitted -->; the sentinel must always remain. Otherwise, when you start adding elements again, <!-- raw HTML omitted -->list<!-- raw HTML omitted -->‘s type will become list-of-type-of-the-first-element-added:</p>
<pre><code>q)list: list _/ reverse til count list
q)count list
0
q)type list
0h
q)list ,: `sector
q)type list
11h
q)
</code></pre><p>This can happen unexpectedly when a mixed-type list is actually a column in a table. See this <a href="https://www.kdbfaq.com/how-do-i-store-mixed-data-types-in-a-single-column-of-a-tabl.html?SSScrollPosition=0">related faq</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>Does q have closures?</title>
			<link>https://kdbfaq.com/does-q-have-closures/</link>
			<pubDate>Fri, 25 Mar 2011 00:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/does-q-have-closures/</guid>
			<description>Not quite. q supports what it calls projections, which are functions whose arguments are partially specified. Projections can serve the same purpose as closures, albeit (and ironically, we might add) with some additional typing:
f: {[list; n] {[nn; item] / n cannot be referenced here, / so we pass it as nn nn + item}[n; ] each list } See: Closure</description>
			<content type="html"><![CDATA[<p>Not quite. q supports what it calls projections, which are functions whose arguments are partially specified. Projections can serve the same purpose as closures, albeit (and ironically, we might add) with some additional typing:</p>
<pre><code>f: {[list; n] {[nn; item]
/ n cannot be referenced here,
/ so we pass it as nn
nn + item}[n; ] each list
}
</code></pre><p>See: <a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)" title="wiki">Closure</a></p>
]]></content>
		</item>
		
		<item>
			<title>Why doesn’t ‘select from tablename where name = `ABC/A’ work?</title>
			<link>https://kdbfaq.com/why-doesnt-select-from-tablename-where-name-abc-a-work/</link>
			<pubDate>Thu, 24 Mar 2011 23:13:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/why-doesnt-select-from-tablename-where-name-abc-a-work/</guid>
			<description>When using symbols that have special characters embedded in them, you need to use a string and cast it to a symbol.
In the example in the question, the / is interpreted as the q adverb over:
q)`ABC/A / interpreted as `ABC over A. ‘/ q) The ‘/error means we have misapplied /. Here’s how to create the symbol we want:
q)`$ “ABC/A” `ABC/A q)select from tablename where name = `$ “ABC/A” Finally, symbols with embedded spaces are allowed, as long they are not leading or trailing:</description>
			<content type="html"><![CDATA[<p>When using symbols that have special characters embedded in them, you need to use a string and <a href="https://code.kx.com/q/ref/cast/" title="code.kx.com">cast</a> it to a symbol.</p>
<p>In the example in the question, the <a href="https://code.kx.com/q/ref/accumulators/#over" title="code.kx.com"><!-- raw HTML omitted -->/<!-- raw HTML omitted --></a> is interpreted as the q adverb <a href="https://code.kx.com/q/ref/accumulators/#over" title="code.kx.com"><!-- raw HTML omitted -->over<!-- raw HTML omitted --></a>:</p>
<pre><code>q)`ABC/A        / interpreted as `ABC over A.
‘/
q)
</code></pre><p>The <!-- raw HTML omitted -->‘/<!-- raw HTML omitted --> error means we have misapplied <a href="https://code.kx.com/q/ref/accumulators/#over" title="code.kx.com"><!-- raw HTML omitted -->/<!-- raw HTML omitted --></a>. Here’s how to create the symbol we want:</p>
<pre><code>q)`$ “ABC/A”
`ABC/A
q)select from tablename where name = `$ “ABC/A”
</code></pre><p>Finally, symbols with embedded spaces are allowed, as long they are not leading or trailing:</p>
<pre><code>q)`$” ABC E “
`ABC E
q)string `$” ABC E “
“ABC E”
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>What does ‘NUC mean?</title>
			<link>https://kdbfaq.com/what-does-nuc-mean/</link>
			<pubDate>Thu, 24 Mar 2011 19:18:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-does-nuc-mean/</guid>
			<description>NUCmeans, “Non-Upward-Compatible.”</description>
			<content type="html"><![CDATA[<p><!-- raw HTML omitted --><!-- raw HTML omitted -->NUC<!-- raw HTML omitted --><!-- raw HTML omitted --> means, “Non-Upward-Compatible.”</p>
]]></content>
		</item>
		
		<item>
			<title>How do I save a table to delimited text?</title>
			<link>https://kdbfaq.com/how-do-i-save-a-table-to-delimited-text/</link>
			<pubDate>Thu, 24 Mar 2011 02:49:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-save-a-table-to-delimited-text/</guid>
			<description>One way, if the format you want is csv, is automatically invoked when using the save function if the name of the destination file ends in .csv:
q)t: ([] x: `a`b; y: 1 2) q)save `:t.csv q)\cat t.csv “x,y” “a,1” “b,2” q) For other delimiters, you must first format the text using the overload of the 0: function whose first parameter is a character:
q)t: ([] x: `a`b; y: 1 2) q)”|” 0: t “x|y” “a|1” “b|2” q) Notice that, by default, q saves the table column names as a header in the first line of the file.</description>
			<content type="html"><![CDATA[<p>One way, if the format you want is csv, is automatically invoked when using the <a href="https://code.kx.com/q/ref/save/"><!-- raw HTML omitted -->save<!-- raw HTML omitted --></a> function if the name of the destination file ends in .csv:</p>
<pre><code>q)t: ([] x: `a`b; y: 1 2)
q)save `:t.csv
q)\cat t.csv
“x,y”
“a,1”
“b,2”
q)
</code></pre><p>For other delimiters, you must first format the text using the overload of the <a href="https://code.kx.com/q/ref/file-text/"><!-- raw HTML omitted -->0:<!-- raw HTML omitted --></a> function whose first parameter is a character:</p>
<pre><code>q)t: ([] x: `a`b; y: 1 2)
q)”|” 0: t
“x|y”
“a|1”
“b|2”
q)
</code></pre><p>Notice that, by default, q saves the table column names as a header in the first line of the file. If you want to get rid of the header line, use <a href="https://code.kx.com/q/ref/drop/"><!-- raw HTML omitted -->_<!-- raw HTML omitted --> (drop)</a>:</p>
<pre><code>q)t: ([] x: `a`b; y: 1 2)
q)1 _ “\t” 0: t
“a\t1”
“b\t2”
q)
</code></pre><p>Once you have your data as a list of strings complete with delimiters, you use another overload of the <a href="https://code.kx.com/q/ref/file-text/"><!-- raw HTML omitted -->0:<!-- raw HTML omitted --></a> function to save the data to disk; this time, the first parameter is the file handle (name) of the destination file:</p>
<pre><code>q)t: ([] x: `a`b; y: 1 2)
q)`:filename.psv 0: 1 _ “|” 0: t
`:filename.psv
q)\cat filename.psv
“a|1”
“b|2”
q)
</code></pre><p>Since we can’t seem to keep all of the overloads for <a href="https://code.kx.com/q/ref/file-text/"><!-- raw HTML omitted -->0:<!-- raw HTML omitted --></a> straight (there are more we didn’t cover here), we like to wrap the above idiom in a function with a descriptive name. For example,</p>
<pre><code>SaveTableDataAsText: {[path; table; delimiter] hsym[path] 0: 1 _ delimiter 0: table}
</code></pre><p>See also: <a href="https://code.kx.com/q/ref/doth/" title="code.kx.com">.h.cd</a></p>
]]></content>
		</item>
		
		<item>
			<title>When I launch kdb with a directory, what exactly happens on start up and in what order?</title>
			<link>https://kdbfaq.com/when-i-launch-kdb-with-a-directory-what-exactly-happens-on-start-up-and-in-what-order/</link>
			<pubDate>Thu, 24 Mar 2011 01:37:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/when-i-launch-kdb-with-a-directory-what-exactly-happens-on-start-up-and-in-what-order/</guid>
			<description>The short answer is, q initializes itself, loads data, then code.
The exact sequence is as follows:
 load $QHOME/q.k load $QINIT/q.q or $QHOME/q.q load tables contained in /directorypath load scripts /directorypath/*.q (and *.k or .s) in alphabetical order  </description>
			<content type="html"><![CDATA[<p>The short answer is, q initializes itself, loads data, then code.</p>
<p>The exact sequence is as follows:</p>
<ol>
<li>load $QHOME/q.k</li>
<li>load $QINIT/q.q or $QHOME/q.q</li>
<li>load tables contained in /directorypath</li>
<li>load scripts /directorypath/*.q (and *.k or .s) in alphabetical order</li>
</ol>
]]></content>
		</item>
		
		<item>
			<title>I wish to keep sym file small.  How can I find out if I will be introducing a new symbol before splaying the data out to disk?</title>
			<link>https://kdbfaq.com/i-wish-to-keep-sym-file-small-how-can-i-find-out-if-i-will-be-introducing-a-new-symbol-before-splaying-the-data-out-to-disk/</link>
			<pubDate>Thu, 24 Mar 2011 00:39:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-wish-to-keep-sym-file-small-how-can-i-find-out-if-i-will-be-introducing-a-new-symbol-before-splaying-the-data-out-to-disk/</guid>
			<description>You can detect if the use of a symbol will increased the total number of interned symbols in the pool using .Q.w:
$ rlwrap q KDB+ 2.7 2011.02.16 Copyright (C) 1993-2011 Kx Systems q).Q.w[] used| 108432 heap| 67108864 peak| 67108864 wmax| 0 mmap| 0 syms| 537 symw| 15616 q)`1 // force kdb to internalize a new symbol `1 q).Q.w[] used| 108432 heap| 67108864 peak| 67108864 wmax| 0 mmap| 0 syms| 538 // increased by 1 symw| 15634 // increase of +18 bytes q)`12 // force kdb to internalize another `12 q).</description>
			<content type="html"><![CDATA[<p>You can detect if the use of a symbol will increased the total number of interned symbols in the pool using <a href="https://www.kdbfaq.com/how-do-i-interpret-the-output-of-function-qw.html">.Q.w</a>:</p>
<pre><code>$ rlwrap q
KDB+ 2.7 2011.02.16 Copyright (C) 1993-2011 Kx Systems
q).Q.w[]
used| 108432
heap| 67108864
peak| 67108864
wmax| 0
mmap| 0
syms| 537
symw| 15616
q)`1              // force kdb to internalize a new symbol
`1
q).Q.w[]
used| 108432
heap| 67108864
peak| 67108864
wmax| 0
mmap| 0
syms| 538         // increased by 1
symw| 15634       // increase of +18 bytes
q)`12             // force kdb to internalize another
`12
q).Q.w[]
used| 108432
heap| 67108864
peak| 67108864
wmax| 0
mmap| 0
syms| 539         // increase by 1
symw| 15653       // increase of 19 bytes
q)`123
`123
q).Q.w[]
used| 108432
heap| 67108864
peak| 67108864
wmax| 0
mmap| 0
syms| 540         // increase by 1
symw| 15673       // increase of 20 bytes
q)
</code></pre><p>See this solution to <a href="https://code.kx.com/q/kb/compacting-hdb-sym/">compacting a bloated sym file</a></p>
]]></content>
		</item>
		
		<item>
			<title>How can I define my own infix functions?</title>
			<link>https://kdbfaq.com/how-can-i-define-my-own-infix-functions/</link>
			<pubDate>Wed, 23 Mar 2011 02:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-define-my-own-infix-functions/</guid>
			<description>Put them in the .q workspace, e.g.,
q).q.f: {x + y} q)5 f 6 11 q) This is generally considered bad style.</description>
			<content type="html"><![CDATA[<p>Put them in the <code>.q</code> workspace, e.g.,</p>
<pre><code>q).q.f: {x + y}
q)5 f 6
11
q)
</code></pre><p>This is generally considered bad style.</p>
]]></content>
		</item>
		
		<item>
			<title>Why doesn’t my query ‘select from reallybigtable’ ever return?</title>
			<link>https://kdbfaq.com/why-doesnt-my-query-select-from-reallybigtable-ever-return/</link>
			<pubDate>Wed, 23 Mar 2011 01:37:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/why-doesnt-my-query-select-from-reallybigtable-ever-return/</guid>
			<description>It’s a valid query, but q will run out of memory before returning. You’ll have to add some constraints to the query to reduce the size of the result set. Something like
select from reallybigtable where date = YYYY.MM.DD would be a good start.</description>
			<content type="html"><![CDATA[<p>It’s a valid query, but q will run out of memory before returning. You’ll have to add some constraints to the query to reduce the size of the result set. Something like</p>
<pre><code>select from reallybigtable where date = YYYY.MM.DD
</code></pre><p>would be a good start.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I store mixed data types in a single column of a table?</title>
			<link>https://kdbfaq.com/how-do-i-store-mixed-data-types-in-a-single-column-of-a-table/</link>
			<pubDate>Tue, 22 Mar 2011 23:29:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-store-mixed-data-types-in-a-single-column-of-a-table/</guid>
			<description>The first time we needed a column that can hold values of multiple types, we tried something similar to the following:
q)t: ([] thing: ()) q)meta t c | t f a -----| ----- thing| q) True, when you define a table column as an untyped list, it can contain anything. However, the first time you put something in it, the column’s type is set to the type of that first inserted item:</description>
			<content type="html"><![CDATA[<p>The first time we needed a column that can hold values of multiple types, we tried something similar to the following:</p>
<pre><code>q)t: ([] thing: ())
q)meta t
c    | t f a
-----| -----
thing|      
q)
</code></pre><p>True, when you define a table column as an untyped list, it can contain anything. However, the first time you put something in it, the column’s type is set to the type of that first inserted item:</p>
<pre><code>q)`t insert `aunt
,0
q)`t insert 33.33
'type
  [0]  `t insert 33.33
          ^
q)meta t
c    | t f a
-----| -----
thing| s    
q)
</code></pre><p>In our example, the type of the <code>thing</code> column has been promoted to <code>symbol</code>; we can&rsquo;t insert numbers into it.</p>
<p>When you want to store elements of different types in the same column, you have to prevent q from performing this type promotion by stuffing a sentinel row (i.e., a row of dummy values), <em>whose value for the column in question is itself a list</em>, into the table:</p>
<pre><code>q)t:([] thing: enlist &quot;sentinel&quot;)
q)meta t
c    | t f a
-----| -----
thing| C    
q)
</code></pre><p>Don&rsquo;t believe the hype. The <code>meta</code> function is trying to help out by actually inspecting the first value in the column when reporting the <code>thing</code> column&rsquo;s type. However, the true type of the column is untyped, i.e., zero:</p>
<pre><code>q)type t `thing
0h
q)
</code></pre><p>You can, therefore, put whatever you like into <!-- raw HTML omitted -->t’s thing<!-- raw HTML omitted --> column:</p>
<pre><code>q)t: ([] thing: enlist &quot;sentinel&quot;)
q)meta t
c    | t f a
-----| -----
thing| C    
q)q)`t insert/: (`gave; 42)
1
2
q)t
thing     
----------
&quot;sentinel&quot;
`gave     
42        
q)meta t
c    | t f a
-----| -----
thing| C    
q)
</code></pre><p>Beware cleaning out such a table too thoroughly (in, say, an end-of-day function):</p>
<pre><code>q)delete from `t
`t
q)meta t
c    | t f a
-----| -----
thing|      
q)
</code></pre><p>See this <a href="https://www.kdbfaq.com/i-defined-an-untyped-list-but-i-get-a-type-error-when-i-add.html">related faq</a> on untyped lists.</p>
]]></content>
		</item>
		
		<item>
			<title>How does kdb compare to cloud computing?</title>
			<link>https://kdbfaq.com/how-does-kdb-compare-to-cloud-computing/</link>
			<pubDate>Tue, 22 Mar 2011 01:37:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-does-kdb-compare-to-cloud-computing/</guid>
			<description>Cloud-based solutions (such as Hadoop) are great if
 you have developers who know how to program them you don’t mind putting your data on a cloud the data you need for even a single query can’t fit in memory you can afford to wait minutes for your query results  For some applications, then, clouds are an excellent approach. kdb+, however, is typically used in scenarios where
 you can’t (e.</description>
			<content type="html"><![CDATA[<p>Cloud-based solutions (such as Hadoop) are great if</p>
<ul>
<li>you have developers who know how to program them</li>
<li>you don’t mind putting your data on a cloud</li>
<li>the data you need for even a single query can’t fit in memory</li>
<li>you can afford to wait minutes for your query results</li>
</ul>
<p>For some applications, then, clouds are an excellent approach. kdb+, however, is typically used in scenarios where</p>
<ul>
<li>you can’t (e.g., due to licensing) or don’t want your data outside your firm</li>
<li>you don’t have an in-house cloud infrastructure</li>
<li>you don’t want each query to be an IT project in and of itself</li>
<li>you want the answer to your query in milliseconds (or seconds at worst)</li>
<li>you can fit your data in memory (not necessarily all at once)</li>
</ul>
]]></content>
		</item>
		
		<item>
			<title>How do I extract the milliseconds from a time?</title>
			<link>https://kdbfaq.com/how-do-i-extract-the-milliseconds-from-a-time/</link>
			<pubDate>Tue, 22 Mar 2011 01:30:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-extract-the-milliseconds-from-a-time/</guid>
			<description>mod 1000:
q)now: .z.T q)now 00:15:00.812 q)now mod 1000 00:00:00.812 q) If you want the milliseconds as an integer, you can simply follow the mod with a conversion to int:
q)`int$ now mod 1000 812 q) You don’t want to pass a datetimeto mod; the result you’ll get is not what you had in mind. You must convert it to a timefirst:
q)now: .z.Z q)now 2011.03.26T09:51:26.624 q)now mod 1000 102.4107 q)`int$ (`time$ now) mod 1000 624 q) </description>
			<content type="html"><![CDATA[<p><a href="https://code.kx.com/q/ref/mod/">mod</a> 1000:</p>
<pre><code>q)now: .z.T
q)now
00:15:00.812
q)now mod 1000
00:00:00.812
q)
</code></pre><p>If you want the milliseconds as an integer, you can simply follow the <a href="https://code.kx.com/q/ref/mod/">mod</a> with a conversion to <!-- raw HTML omitted -->int<!-- raw HTML omitted -->:</p>
<pre><code>q)`int$ now mod 1000
812
q)
</code></pre><p>You don’t want to pass a <!-- raw HTML omitted -->datetime<!-- raw HTML omitted --> to <a href="https://code.kx.com/q/ref/mod/">mod</a>; the result you’ll get is not what you had in mind. You must convert it to a <!-- raw HTML omitted -->time<!-- raw HTML omitted --> first:</p>
<pre><code>q)now: .z.Z
q)now
2011.03.26T09:51:26.624
q)now mod 1000
102.4107
q)`int$ (`time$ now) mod 1000
624
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>Can I simply invoke garbage collect and clear the root namespace instead of restarting the process to reinitialize my database?</title>
			<link>https://kdbfaq.com/can-i-simply-invoke-garbage-collect-and-clear-the-root-namespace-instead-of-restarting-the-process-to-reinitialize-my-database/</link>
			<pubDate>Mon, 21 Mar 2011 22:21:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/can-i-simply-invoke-garbage-collect-and-clear-the-root-namespace-instead-of-restarting-the-process-to-reinitialize-my-database/</guid>
			<description>Almost. The symbol pool, however, will remain uncleared:
$ rlwrap q KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems q).Q.gc[] 0j / as expected, gc is a no-op q).Q.w[] used| 108432 heap| 67108864 peak| 67108864 wmax| 0 mmap| 0 syms| 538 symw| 15638 q)-1000000?`6 / 1 million symbols of length 6 `milgli`igfbag`kaodhb`bafclb`kfhogj`jecpae`kfmohp`lk.. q).Q.w[] used used| 108592 heap| 67108864 peak| 67108864 wmax| 0 mmap| 0 syms| 1000539 / bumped by a million symw| 31400168 q).</description>
			<content type="html"><![CDATA[<p>Almost. The symbol pool, however, will remain uncleared:</p>
<pre><code>$ rlwrap q
KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems
q).Q.gc[]
0j                            / as expected, gc is a no-op
q).Q.w[] 
used| 108432
heap| 67108864
peak| 67108864
wmax| 0
mmap| 0
syms| 538
symw| 15638
q)-1000000?`6                 / 1 million symbols of length 6
`milgli`igfbag`kaodhb`bafclb`kfhogj`jecpae`kfmohp`lk..
q).Q.w[] used
used| 108592
heap| 67108864
peak| 67108864
wmax| 0
mmap| 0
syms| 1000539                 / bumped by a million
symw| 31400168
q).Q.gc[]
0j                            / no-op again!
q).Q.w[]
used| 108592
heap| 67108864
peak| 67108864
wmax| 0
mmap| 0
syms| 1000539                 / remains unchanged
symw| 31400168
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>How portable is q code across operating systems?</title>
			<link>https://kdbfaq.com/how-portable-is-q-code-across-operating-systems/</link>
			<pubDate>Mon, 21 Mar 2011 01:36:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-portable-is-q-code-across-operating-systems/</guid>
			<description>kdb is available on Windows, Linux, Solaris and Mac OS X. Like most functional languages, q is a very high level language. As long as you stick with forward slashes in your file paths, you will be rarely notice the difference between operating systems. The only significant issue we’ve come across is that multi-threading is not supported on Macs.
If you do need to distinguish different operating systems, use the variable .</description>
			<content type="html"><![CDATA[<p>kdb is available on Windows, Linux, Solaris and Mac OS X. Like most functional languages, q is a very high level language. As long as you stick with forward slashes in your file paths, you will be rarely notice the difference between operating systems. The only significant issue we’ve come across is that multi-threading is not supported on Macs.</p>
<p>If you do need to distinguish different operating systems, use the variable <a href="https://code.kx.com/q/ref/dotz/#zo-os-version">.z.o</a> to detect the operating system in which your code is running.</p>
]]></content>
		</item>
		
		<item>
			<title>Given a value, how do I get the null of that value’s type?</title>
			<link>https://kdbfaq.com/given-a-value-how-do-i-get-the-null-of-that-values-type/</link>
			<pubDate>Mon, 21 Mar 2011 01:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/given-a-value-how-do-i-get-the-null-of-that-values-type/</guid>
			<description>We take advantage of a property of q’s indexing: If you request an item from a list (or a dictionary, for that matter) using an index that is out of range, q returns the null item for the list’s type.
q)x: 1 2 3 q)x 3 0N q) Thus, we can take the item whose corresponding null we want, make a list from it, and then access that list with an out-of-range index:</description>
			<content type="html"><![CDATA[<p>We take advantage of a property of q’s indexing: If you request an item from a list (or a dictionary, for that matter) using an index that is out of range, q returns the null item for the list’s type.</p>
<pre><code>q)x: 1 2 3
q)x 3
0N
q)
</code></pre><p>Thus, we can take the item whose corresponding null we want, make a list from it, and then access that list with an out-of-range index:</p>
<pre><code>q)NullOf: {[item] enlist[item] 1}
q)NullOf 1
0N
q)(::) ~ NullOf {x*x}
1b
q)null NullOf (.z.D; 1e; ” “; type “foo”)
1111b
q)
</code></pre><p>Remember, there is no null list. If you pass a list to NullOf, you get the empty list of the corresponding type:</p>
<pre><code>q)NullOf 1 2 3
`int$()
q)
</code></pre><p>See also: <a href="https://code.kx.com/q/ref/dotq/#qty-type" title="code.kx.com">.Q.ty</a></p>
]]></content>
		</item>
		
		<item>
			<title>What are 0!, 1! and 2!?</title>
			<link>https://kdbfaq.com/what-are-0-1-and-2/</link>
			<pubDate>Sun, 20 Mar 2011 20:19:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-are-0-1-and-2/</guid>
			<description>When !’s left argument is a positive integer, it sets the key fields of a table:
q)flip `a`b`c ! (1 2 3; 1 2 3; 1 2 3) a b c ----- 1 1 1 2 2 2 3 3 3 q)1! flip `a`b`c ! (1 2 3; 1 2 3; 1 2 3) a| b c -| --- 1| 1 1 2| 2 2 3| 3 3 q)2! flip `a`b`c !</description>
			<content type="html"><![CDATA[<p>When <a href="https://code.kx.com/q/ref/overloads/#bang">!’s</a> left argument is a positive integer, it sets the key fields of a table:</p>
<pre><code>q)flip `a`b`c ! (1 2 3; 1 2 3; 1 2 3)
a b c
-----
1 1 1
2 2 2
3 3 3
q)1! flip `a`b`c ! (1 2 3; 1 2 3; 1 2 3)
a| b c
-| ---
1| 1 1
2| 2 2
3| 3 3
q)2! flip `a`b`c ! (1 2 3; 1 2 3; 1 2 3)
a b| c
---| -
1 1| 1
2 2| 2
3 3| 3
q)
</code></pre><p>When <a href="https://code.kx.com/q/ref/overloads/#bang">!’s</a> left argument is zero, it returns an unkeyed table from a keyed table:</p>
<pre><code>q)0! flip `a`b`c ! (1 2 3; 1 2 3; 1 2 3)
a b c
-----
1 1 1
2 2 2
3 3 3
q)
</code></pre><p>An arguably more readable equivalent is the <a href="https://code.kx.com/q/ref/keys/#xkey"><!-- raw HTML omitted -->xkey<!-- raw HTML omitted --></a> function:</p>
<pre><code>q)`a xkey flip `a`b`c ! (1 2 3; 1 2 3; 1 2 3)
a| b c
-| ---
1| 1 1
2| 2 2
3| 3 3
q)`a`b xkey flip `a`b`c ! (1 2 3; 1 2 3; 1 2 3)
a b| c
---| -
1 1| 1
2 2| 2
3 3| 3
q)() xkey flip `a`b`c ! (1 2 3; 1 2 3; 1 2 3)
a b c
-----
1 1 1
2 2 2
3 3 3
q)
</code></pre><p>It’s easy to confuse function <a href="https://code.kx.com/q/ref/keys/#xkey"><!-- raw HTML omitted -->xkey<!-- raw HTML omitted --></a> with <a href="https://code.kx.com/q/ref/key/"><!-- raw HTML omitted -->key<!-- raw HTML omitted --></a>, <a href="https://code.kx.com/q/ref/keys/#xkey"><!-- raw HTML omitted -->keys<!-- raw HTML omitted --></a>, <a href="https://www.kdbfaq.com/what-is-the-difference-between-the-functions-xcol-and-xcols.html"><!-- raw HTML omitted -->xcol<!-- raw HTML omitted --> and <!-- raw HTML omitted -->xcols<!-- raw HTML omitted --></a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How can I experiment on a production kdb while keeping the data free from accidental damage?</title>
			<link>https://kdbfaq.com/how-can-i-experiment-on-a-production-kdb-while-keeping-the-data-free-from-accidental-damage/</link>
			<pubDate>Sun, 20 Mar 2011 01:33:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-experiment-on-a-production-kdb-while-keeping-the-data-free-from-accidental-damage/</guid>
			<description>Use the -b command line argument to start kdb in read only mode, or start up with a negative port number.
one can verify the read-only mode by examining the return value of function _
$ q -b KDB+ 2.7 2011.02.16 Copyright (C) 1993-2011 Kx Systems ... q)\_ 1 q) </description>
			<content type="html"><![CDATA[<p>Use the <a href="https://code.kx.com/q/basics/cmdline/">-b command line argument</a> to start kdb in read only mode, or start up with a <a href="https://code.kx.com/q/basics/listening-port/">negative port number</a>.</p>
<p>one can verify the read-only mode by examining the return value of function _</p>
<pre><code>$ q -b
KDB+ 2.7 2011.02.16 Copyright (C) 1993-2011 Kx Systems
...
q)\_
1
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>What is a virtual column?</title>
			<link>https://kdbfaq.com/what-is-a-virtual-column/</link>
			<pubDate>Sat, 19 Mar 2011 17:16:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-is-a-virtual-column/</guid>
			<description>A virtual column is not stored. There are two kinds of virtual columns in kdb:
 The index column, i, which is present in all tables, and the partition column on a partitioned table. For example, the most common partitioning scheme is by date. Rather than storing the date column along with the other columns in the table, the date is inferred from the partition directory; splayed table directories will not contain files for the date column.</description>
			<content type="html"><![CDATA[<p>A virtual column is not stored. There are two kinds of virtual columns in kdb:</p>
<ol>
<li>The index column, <!-- raw HTML omitted -->i<!-- raw HTML omitted -->, which is present in all tables, and</li>
<li>the partition column on a partitioned table. For example, the most common partitioning scheme is by date. Rather than storing the date column along with the other columns in the table, the date is inferred from the partition directory; splayed table directories will <strong>not</strong> contain files for the date column.</li>
</ol>
<p>See also: <a href="https://code.kx.com/q/ref/dotq/#qpf-partition-field" title="code.kx.com">.Q.pf</a> and <a href="https://code.kx.com/q/ref/dotq/#qpt-partitioned-tables" title="code.kx.com">.Q.pt</a></p>
]]></content>
		</item>
		
		<item>
			<title>What is the difference between the functions xcol and xcols?</title>
			<link>https://kdbfaq.com/what-is-the-difference-between-the-functions-xcol-and-xcols/</link>
			<pubDate>Sat, 19 Mar 2011 14:57:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-is-the-difference-between-the-functions-xcol-and-xcols/</guid>
			<description>Use xcol to rename columns. Note that it doesn’t require a complete list of columns.
$ rlwrap q sp.q KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems +`p`city!(`p$`p1`p2`p3`p4`p5`p6`p1`p2;`london`london`london`l.. (+(,`color)!,`blue`green`red)!+(,`qty)!,900 1000 1200 +`s`p`qty!(`s$`s1`s1`s1`s2`s3`s4;`p$`p1`p4`p6`p2`p2`p4;300 200 100 400 200 300) q)sp s p qty ——— s1 p1 300 s1 p2 200 s1 p3 400 s1 p4 200 q)`p`s xcol sp // rename the first two cols p s qty ——— s1 p1 300 s1 p2 200 s1 p3 400 s1 p4 200 q) Use xcols to reorder columns:</description>
			<content type="html"><![CDATA[<p>Use <a href="http://code.kx.com/trac/wiki/Reference/xcol"><!-- raw HTML omitted -->xcol<!-- raw HTML omitted --></a> to <strong>rename</strong> columns. Note that it doesn’t require a complete list of columns.</p>
<pre><code>$ rlwrap q sp.q
KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems
+`p`city!(`p$`p1`p2`p3`p4`p5`p6`p1`p2;`london`london`london`l..
(+(,`color)!,`blue`green`red)!+(,`qty)!,900 1000 1200
+`s`p`qty!(`s$`s1`s1`s1`s2`s3`s4;`p$`p1`p4`p6`p2`p2`p4;300 200 100 400 200 300)
q)sp
s p qty
———
s1 p1 300
s1 p2 200
s1 p3 400
s1 p4 200
q)`p`s xcol sp // rename the first two cols
p s qty
———
s1 p1 300
s1 p2 200
s1 p3 400
s1 p4 200
q)
</code></pre><p>Use <a href="http://code.kx.com/trac/wiki/Reference/xcol"><!-- raw HTML omitted -->xcols<!-- raw HTML omitted --></a> to <strong>reorder</strong> columns:</p>
<pre><code>q)(reverse cols sp) xcols sp
qty p s
———
300 p1 s1
200 p2 s1
400 p3 s1
200 p4 s1
q)
</code></pre><p>One way to remember which is which is that, just as <em>rename</em> precedes <em>reorder</em> (in alphabetical order), so does <!-- raw HTML omitted -->xcol<!-- raw HTML omitted --> precede <!-- raw HTML omitted -->xcols<!-- raw HTML omitted -->.</p>
]]></content>
		</item>
		
		<item>
			<title>What should I know about the sym file, and why back it up?</title>
			<link>https://kdbfaq.com/what-should-i-know-about-the-sym-file-and-why-back-it-up/</link>
			<pubDate>Sat, 19 Mar 2011 01:29:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-should-i-know-about-the-sym-file-and-why-back-it-up/</guid>
			<description>In a partitioned database, the sym file is a string intern pool which grows every time a new distinct symbol is introduced and persisted to that database. The sym file cannot be regenerated (unless you know the exact order in which your data was loaded from the inception of your database) and does not automatically shrink when symbols are removed from the database.
See this solution to compacting a bloated sym file.</description>
			<content type="html"><![CDATA[<p>In a partitioned database, the sym file is a string intern pool which grows every time a new distinct symbol is introduced and persisted to that database. The sym file cannot be regenerated (unless you know the exact order in which your data was loaded from the inception of your database) and does not automatically shrink when symbols are removed from the database.</p>
<p>See this solution to <a href="https://code.kx.com/q/kb/compacting-hdb-sym/">compacting a bloated sym file</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I get the day of the week?</title>
			<link>https://kdbfaq.com/how-do-i-get-the-day-of-the-week/</link>
			<pubDate>Fri, 18 Mar 2011 23:26:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-get-the-day-of-the-week/</guid>
			<description>q)`Sat`Sun`Mon`Tue`Wed`Thu`Fri .z.D mod 7 `Sat q)\date “Sat Mar 5 18:56:04 PST 2011″ q) see also: -W, .z.D, mod, os-commands</description>
			<content type="html"><![CDATA[<pre><code>q)`Sat`Sun`Mon`Tue`Wed`Thu`Fri .z.D mod 7
`Sat
q)\date
“Sat Mar 5 18:56:04 PST 2011″
q)
</code></pre><p>see also: <a href="https://code.kx.com/q/basics/cmdline/" title="code.kx.com">-W</a>, <a href="hhttps://code.kx.com/q/ref/dotz/#zt-zt-zd-zd-timedate-shortcuts%22code.kx.com%22">.z.D</a>, <a href="https://code.kx.com/q/ref/mod/" title="code.kx.com">mod</a>, <a href="https://code.kx.com/q/basics/syscmds/#os-commands" title="code.kx.com">os-commands</a></p>
]]></content>
		</item>
		
		<item>
			<title>Is the output of meta available for use in my program?</title>
			<link>https://kdbfaq.com/is-the-output-of-meta-available-for-use-in-my-program/</link>
			<pubDate>Fri, 18 Mar 2011 23:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/is-the-output-of-meta-available-for-use-in-my-program/</guid>
			<description>Yes. meta’s result is an ordinary q table:
$ rlwrap q sp.q KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems q)type meta sp 99h q)meta sp c | t f a ---| ----- s | s s p | s p qty| i q)cols meta sp `c`t`f`a q)meta meta sp c| t f a -| ----- c| s t| c f| s a| s q) </description>
			<content type="html"><![CDATA[<p>Yes. <a href="https://code.kx.com/q/ref/meta/">meta’s</a> result is an ordinary q table:</p>
<pre><code>$ rlwrap q sp.q
KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems
q)type meta sp
99h
q)meta sp
c  | t f a
---| -----
s  | s s
p  | s p
qty| i
q)cols meta sp
`c`t`f`a
q)meta meta sp
c| t f a
-| -----
c| s
t| c
f| s
a| s
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>Who uses time series or column-oriented databases and why?</title>
			<link>https://kdbfaq.com/who-uses-time-series-or-column-oriented-databases-and-why/</link>
			<pubDate>Thu, 17 Mar 2011 23:27:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/who-uses-time-series-or-column-oriented-databases-and-why/</guid>
			<description>Like any database technology platform, time series databases have found specialized applications in several industries, including telecommunications, utility, finance, and military.
For example, cell carriers use time series databases to monitor peak mobile phone usage. Similarly, utilities use them to study optimal tariff structure to shape on-peak or off-peak electricity usage.
See wikipedia for more on time series and column-oriented databases.</description>
			<content type="html"><![CDATA[<p>Like any database technology platform, time series databases have found specialized applications in several industries, including telecommunications, utility, finance, and military.</p>
<p>For example, cell carriers use time series databases to monitor peak mobile phone usage. Similarly, utilities use them to study optimal tariff structure to shape on-peak or off-peak electricity usage.</p>
<p>See wikipedia for more on <a href="http://en.wikipedia.org/wiki/Time_series_database">time series</a> and <a href="http://en.wikipedia.org/wiki/Column-oriented_DBMS">column-oriented</a> databases.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I delete a function in namespace .z?</title>
			<link>https://kdbfaq.com/how-do-i-delete-a-function-in-namespace-z/</link>
			<pubDate>Thu, 17 Mar 2011 23:20:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-delete-a-function-in-namespace-z/</guid>
			<description>The usual way to delete a function – any entity, for that matter, is
 delete entity from namespace e.g.
 delete foo from `. However, .zis a special namespace, so delete doesn’t work:
q).z.ts: {47} q)delete ts from `.z ‘type q) There is a special command just for removing elements from .z:
q)\x .z.pi See \x (expunge).</description>
			<content type="html"><![CDATA[<p>The usual way to delete a function – any entity, for that matter, is</p>
<pre><code>    delete entity from namespace
</code></pre><p>e.g.</p>
<pre><code>    delete foo from `.
</code></pre><p>However, <!-- raw HTML omitted -->.z<!-- raw HTML omitted --> is a special namespace, so <a href="https://code.kx.com/q/ref/delete/#delete-keyword"><!-- raw HTML omitted -->delete<!-- raw HTML omitted --></a> doesn’t work:</p>
<pre><code>q).z.ts: {47}
q)delete ts from `.z
‘type
q)
</code></pre><p>There is a special command just for removing elements from <!-- raw HTML omitted -->.z<!-- raw HTML omitted -->:</p>
<pre><code>q)\x .z.pi
</code></pre><p>See <a href="https://code.kx.com/q/basics/syscmds/#x-expunge" title="code.kx.com">\x (expunge)</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I choose whether to make a field a symbol or string?</title>
			<link>https://kdbfaq.com/how-do-i-choose-whether-to-make-a-field-a-symbol-or-string/</link>
			<pubDate>Thu, 17 Mar 2011 21:52:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-choose-whether-to-make-a-field-a-symbol-or-string/</guid>
			<description>A q string is a vector of characters. If you need to manipulate the string, or the set of possible values the string might take is unbounded, then go with string.
Use symbol when the set of values is restricted, e.g., exchange names, or tickers. Symbols are faster for comparison operations (and that means lookup as well).
See string interning.</description>
			<content type="html"><![CDATA[<p>A q string is a vector of characters. If you need to manipulate the string, or the set of possible values the string might take is unbounded, then go with string.</p>
<p>Use symbol when the set of values is restricted, e.g., exchange names, or tickers. Symbols are faster for comparison operations (and that means lookup as well).</p>
<p>See <a href="http://en.wikipedia.org/wiki/String_interning">string interning</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How can I group all (other) columns?</title>
			<link>https://kdbfaq.com/how-can-i-group-all-other-columns/</link>
			<pubDate>Wed, 16 Mar 2011 22:33:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-group-all-other-columns/</guid>
			<description>Short Answer xgroup.
Explanation When you write a grouping query (i.e., one with a byclause) that lists columns in its select clause, the result nests all of the values from the selected columns. However, if no columns are listed in the select clause, the result only includes each column’s last value for each key.
For example, consider the following table:
trade: ([] time: `time$ (); sym: `symbol$ (); price: `float$ (); size: `int$ ()); `trade insert (09:30:00t + til 1000; 1000 # 10 ?</description>
			<content type="html"><![CDATA[<h3 id="short-answer">Short Answer</h3>
<p><a href="https://code.kx.com/q/ref/xgroup/"><!-- raw HTML omitted -->xgroup<!-- raw HTML omitted --></a>.</p>
<h3 id="explanation">Explanation</h3>
<p>When you write a grouping query (i.e., one with a <!-- raw HTML omitted -->by<!-- raw HTML omitted --> clause) that lists columns in its <a href="https://code.kx.com/q/ref/select/"><!-- raw HTML omitted -->select<!-- raw HTML omitted --></a> clause, the result nests all of the values from the selected columns. However, if no columns are listed in the <a href="https://code.kx.com/q/ref/select/">select</a> clause, the result only includes each column’s last value for each key.</p>
<p>For example, consider the following table:</p>
<pre><code>trade: ([] time:  `time$   ();
           sym:   `symbol$ ();
           price: `float$  ();
           size:  `int$    ());
`trade insert (09:30:00t + til 1000; 
	1000 # 10 ? `3; 
	10.0 + 1000 ? 15.0; 
	100 + 100 * 1000 ? 10);
</code></pre><p>If we execute a query with a column in its <a href="https://code.kx.com/q/ref/select/"><!-- raw HTML omitted -->select<!-- raw HTML omitted --></a> clause, the result is nested:</p>
<pre><code>q)select price by sym from trade
sym| price                                         ..
---| ----------------------------------------------..
dgh| 13.68204 18.47666 19.59256 23.92803 12.75742 2..
dmo| 19.39943 19.1779  12.71798 10.9528  24.89916 2..
ekh| 22.16764 19.13283 23.42802 11.1409  24.42824 1..
gap| 16.33531 11.47509 13.90435 16.40958 22.59581 2..
log| 23.23925 17.83933 21.00673 14.97167 18.14587 1..
q)
</code></pre><p>However, if the <a href="https://code.kx.com/q/ref/select/"><!-- raw HTML omitted -->select<!-- raw HTML omitted --></a> clause is empty, then the query returns only the last item from each group:</p>
<pre><code>q)select by sym from trade
sym| time         price    size
---| --------------------------
dgh| 09:30:00.992 22.55807 1000
dmo| 09:30:00.999 22.72169 1000
ekh| 09:30:00.993 24.27423 300
gap| 09:30:00.995 20.08908 900
log| 09:30:00.998 24.42545 600
q)
</code></pre><p>Usually, this behavior is what you want. However, if you want to group all columns (except the grouping column), you have two options:</p>
<ol>
<li>List each column explicitly in your <a href="https://code.kx.com/q/ref/select/"><!-- raw HTML omitted -->select<!-- raw HTML omitted --></a> clause,</li>
</ol>
<pre><code>q)select time, price, size by sym from trade
sym| time                                          ..
---| ----------------------------------------------..
dgh| 09:30:00.002 09:30:00.012 09:30:00.022 09:30:0..
dmo| 09:30:00.009 09:30:00.019 09:30:00.029 09:30:0..
ekh| 09:30:00.003 09:30:00.013 09:30:00.023 09:30:0..
gap| 09:30:00.005 09:30:00.015 09:30:00.025 09:30:0..
log| 09:30:00.008 09:30:00.018 09:30:00.028 09:30:0..
q)
</code></pre><p>or,</p>
<ol start="2">
<li>Use <a href="https://code.kx.com/q/ref/xgroup/"><!-- raw HTML omitted -->xgroup<!-- raw HTML omitted --></a>:</li>
</ol>
<pre><code>q)`sym xgroup trade
sym| time                                          ..
---| ----------------------------------------------..
pln| 09:30:00.000 09:30:00.010 09:30:00.020 09:30:0..
nch| 09:30:00.001 09:30:00.011 09:30:00.021 09:30:0..
dgh| 09:30:00.002 09:30:00.012 09:30:00.022 09:30:0..
ekh| 09:30:00.003 09:30:00.013 09:30:00.023 09:30:0..
ojn| 09:30:00.004 09:30:00.014 09:30:00.024 09:30:0..
q)
</code></pre><p>The more columns your table has, the more attractive <a href="https://code.kx.com/q/ref/xgroup/"><!-- raw HTML omitted -->xgroup<!-- raw HTML omitted --></a> will be. However, every time we tried, <a href="https://code.kx.com/q/ref/xgroup/"><!-- raw HTML omitted -->xgroup<!-- raw HTML omitted --></a> was slightly slower:</p>
<pre><code>q)\t do[10000; select time, price, size by sym from trade]
246
q)\t do[10000; `sym xgroup trade]
275
q)
</code></pre><p>On the other hand, if you want the code in question to be generically applied to several tables, <a href="https://code.kx.com/q/ref/xgroup/"><!-- raw HTML omitted -->xgroup<!-- raw HTML omitted --></a> is much better than the alternatives.</p>
<p>Notice that <a href="https://code.kx.com/q/ref/xgroup/"><!-- raw HTML omitted -->xgroup<!-- raw HTML omitted --></a>, in contrast to <a href="https://code.kx.com/q/ref/select/"><!-- raw HTML omitted -->select<!-- raw HTML omitted --></a> <!-- raw HTML omitted -->by<!-- raw HTML omitted -->, does not sort the result by its key. If you need the rows sorted by key, follow <a href="https://code.kx.com/q/ref/xgroup/"><!-- raw HTML omitted -->xgroup<!-- raw HTML omitted --></a> with <a href="https://code.kx.com/q/ref/asc/#xasc"><!-- raw HTML omitted -->xasc<!-- raw HTML omitted --></a>:</p>
<pre><code>q)`sym xasc `sym xgroup trade
sym| time                                          ..
---| ----------------------------------------------..
dgh| 09:30:00.002 09:30:00.012 09:30:00.022 09:30:0..
dmo| 09:30:00.009 09:30:00.019 09:30:00.029 09:30:0..
ekh| 09:30:00.003 09:30:00.013 09:30:00.023 09:30:0..
gap| 09:30:00.005 09:30:00.015 09:30:00.025 09:30:0..
log| 09:30:00.008 09:30:00.018 09:30:00.028 09:30:0..
q)
</code></pre><p>The cost of the sort will make the <a href="https://code.kx.com/q/ref/xgroup/"><!-- raw HTML omitted -->xgroup<!-- raw HTML omitted --></a> significantly slower than using <a href="https://code.kx.com/q/ref/select/"><!-- raw HTML omitted -->select<!-- raw HTML omitted --></a>:</p>
<pre><code>q)\t do[10000; `sym xasc `sym xgroup trade]
479
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>How can I slice a vector into a series of vectors of length n?</title>
			<link>https://kdbfaq.com/how-can-i-slice-a-vector-into-a-series-of-vectors-of-length-n/</link>
			<pubDate>Wed, 16 Mar 2011 22:14:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-slice-a-vector-into-a-series-of-vectors-of-length-n/</guid>
			<description>By passing the # (take) operator a pair as its first (i.e., left) argument:
q)2 5 # til 10 0 1 2 3 4 5 6 7 8 9 q) When # is used in this way, it is referred to as “reshape.” We like to call this, “taking a box.” Just like when you apply # with an integer left argument, taking a box stops when you have taken as many items as requested, leaving the rest behind:</description>
			<content type="html"><![CDATA[<p>By passing the <a href="https://code.kx.com/q/ref/take/"><!-- raw HTML omitted --># (take)<!-- raw HTML omitted --></a> operator a pair as its first (i.e., left) argument:</p>
<pre><code>q)2 5 # til 10
0 1 2 3 4
5 6 7 8 9
q)
</code></pre><p>When <a href="https://code.kx.com/q/ref/take/"><!-- raw HTML omitted -->#<!-- raw HTML omitted --></a> is used in this way, it is referred to as “reshape.” We like to call this, “taking a box.” Just like when you apply <a href="https://code.kx.com/q/ref/take/"><!-- raw HTML omitted -->#<!-- raw HTML omitted --></a> with an integer left argument, taking a box stops when you have taken as many items as requested, leaving the rest behind:</p>
<pre><code>q)3 3 # til 10
0 1 2
3 4 5
6 7 8
q)
</code></pre><p>Similarly, when you over-take a box, you start over from the beginning of the source:</p>
<pre><code>q)4 3 # til 10
0 1 2
3 4 5
6 7 8
9 0 1
q)
</code></pre><p>If you want to take all the items from the source, pass <!-- raw HTML omitted -->0N<!-- raw HTML omitted --> as the first element of the box:</p>
<pre><code>q)0N 2 # til 10
0 1
2 3
4 5
6 7
8 9
q)
</code></pre><p>If you take a whole box, but the elements from the source don’t fit, you end up with a short list in the last row:</p>
<pre><code>q)0N 3 # til 10
0 1 2
3 4 5
6 7 8
,9
q)
</code></pre><p>See also: <a href="https://code.kx.com/q/ref/cut/"><!-- raw HTML omitted -->cut<!-- raw HTML omitted --></a> and  <a href="https://www.kdbfaq.com/how-do-i-split-a-list.html">faq on _ (drop)</a></p>
]]></content>
		</item>
		
		<item>
			<title>Can I retrieve kdb data from my web browser and save the query results to a csv file for viewing in a spreadsheet?</title>
			<link>https://kdbfaq.com/can-i-retrieve-kdb-data-from-my-web-browser-and-save-the-query-results-to-a-csv-file-for-viewing-in-a-spreadsheet/</link>
			<pubDate>Wed, 16 Mar 2011 21:47:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/can-i-retrieve-kdb-data-from-my-web-browser-and-save-the-query-results-to-a-csv-file-for-viewing-in-a-spreadsheet/</guid>
			<description>Yes. Just enter a URL in your browser whose host and port is followed by the characters .csv?. For example,
 http://server:5001/.csv?select from tablename where date=2011.02.25,fname=`JOE See also: .h.cd</description>
			<content type="html"><![CDATA[<p>Yes. Just enter a <!-- raw HTML omitted -->URL <!-- raw HTML omitted -->in your browser whose host and port is followed by the characters <!-- raw HTML omitted -->.csv?<!-- raw HTML omitted -->. For example,</p>
<pre><code>    http://server:5001/.csv?select from tablename where date=2011.02.25,fname=`JOE
</code></pre><p>See also: <a href="https://anonymous:anonymous@code.kx.com/trac/wiki/Doth" title="code.kx.com">.h.cd</a></p>
]]></content>
		</item>
		
		<item>
			<title>Is the q language simply syntactic sugar on top of k?</title>
			<link>https://kdbfaq.com/is-the-q-language-simply-syntactic-sugar-on-top-of-k/</link>
			<pubDate>Wed, 16 Mar 2011 02:50:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/is-the-q-language-simply-syntactic-sugar-on-top-of-k/</guid>
			<description>Not really. There’s been a meaningful expansion in the language to support tables and such. If you are curious, take a look at the code in $QHOME/q.k, it will help you understand what portions of q are implemented natively vs in k.</description>
			<content type="html"><![CDATA[<p>Not really. There’s been a meaningful expansion in the language to support tables and such. If you are curious, take a look at the code in $QHOME/q.k, it will help you understand what portions of q are implemented natively vs in k.</p>
]]></content>
		</item>
		
		<item>
			<title>I noticed a list with a  `s# prefix attached. What does this mean?</title>
			<link>https://kdbfaq.com/i-noticed-a-list-with-a-s-prefix-attached-what-does-this-mean/</link>
			<pubDate>Wed, 16 Mar 2011 02:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-noticed-a-list-with-a-s-prefix-attached-what-does-this-mean/</guid>
			<description>`s is one of q’s data attributes, and indicates that the data in the list is sorted. When q knows that a list is sorted, it can perform some operations much faster. In contrast to the other attribute types, the sorted attribute has zero memory overhead (no data structure needs to be created to support it):
q)d: (-10000 ? `4) ¡ til 10000 q)key d `namk`eefb`dnkg`pfme`ndpk`bhck`bdga`hkdk`gpja`oiof.. q)value d 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 .</description>
			<content type="html"><![CDATA[<p>`s is one of q’s data attributes, and indicates that the data in the list is sorted. When q knows that a list is sorted, it can perform some operations much faster. In contrast to the other attribute types, the sorted attribute has zero memory overhead (no data structure needs to be created to support it):</p>
<pre><code>q)d: (-10000 ? `4) ¡ til 10000
q)key d
`namk`eefb`dnkg`pfme`ndpk`bhck`bdga`hkdk`gpja`oiof..
q)value d
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ..
q)\t do[100000; d key[d] 5000] 443
q)d: (asc key d) ! value[d] iasc key d
q)key d
`s#`aaab`aaak`aaap`aabb`aabn`aace`aadj`aaeg`aaeh`a..
q)\t do[100000; d key[d] 5000] 89
q)
</code></pre><p>Notice that <code>value d</code> above did not have the `s attribute; that is, the <a href="https://code.kx.com/q/ref/til/"><code>til</code></a> function does not return a list with the `s attribute applied. In general, for a list to have the `s attribute, you must either sort the list (with <a href="https://code.kx.com/q/ref/asc/"><code>asc</code></a> as above) or let q know explicitly that the list is sorted by applying the `s attribute to a list that you know is already sorted:</p>
<pre><code>q)x: `s # til 10
q)x
`s#0 1 2 3 4 5 6 7 8 9
q)
</code></pre><p>If you try to apply `s to a list that isn’t actually sorted, you’ll get an <!-- raw HTML omitted -->‘s-fail<!-- raw HTML omitted --> error:</p>
<pre><code>q)`s # 3 2 1
‘s-fail
q)
</code></pre><p>You can add elements to the end of a sorted list without losing the sorted attribute if the new elements do not violate the sorted-ness of the result:</p>
<pre><code>q)x: `s # 1 2 3
q)x
`s#1 2 3
q)x ,: 4 5 6
q)x
`s#1 2 3 4 5 6
q)x ,: 7 7 7
q)x
`s#1 2 3 4 5 6 7 7 7
q)
</code></pre><p>However, other modifications to a sorted list will cause the list to lose its attribute:</p>
<pre><code>q)x: `s # 1 2 3
q)x
`s#1 2 3
q)x, 0
1 2 3 0
q)reverse x / reverse function removes it
3 2 1
q)
</code></pre><p>This is true even if the modifications result in a sorted list:</p>
<pre><code>q) x: `s # 1 2 3
q)1 _ x
2 3
q)2 # x
1 2
q)
</code></pre><p>You can remove the sorted attribute explicitly by applying a null attribute to the list:</p>
<pre><code>q)`#1 2 3 / application of a null attribute
1 2 3
q)
</code></pre><p>See also the following function definitions: <a href="https://code.kx.com/q/ref/attr/" title="code.kx.com"><!-- raw HTML omitted -->attr<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/take/" title="code.kx.com"><!-- raw HTML omitted -->#<!-- raw HTML omitted --></a>.</p>
<p>For even more detail, see <a href="https://code.kx.com/q/ref/#attributes" title="kx.com">Section 42 of the Abridged Q Language Manual</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>What does ‘\l .’ or ‘system “l .”‘ do?</title>
			<link>https://kdbfaq.com/what-does-l-or-system-l-do/</link>
			<pubDate>Tue, 15 Mar 2011 22:28:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-does-l-or-system-l-do/</guid>
			<description>Typically, it’s used to reinitialize and alert an existing kdb process of a new partition. Note that command triggers the execution of any q scripts existing in the current working directory of the running kdb process.
This command allows kdb to continue running and servicing requests while a new partition is constructed. Running kdb remains unware of the new partition until the \l . command is issued.
See also: .Q.l</description>
			<content type="html"><![CDATA[<p>Typically, it’s used to reinitialize and alert an existing kdb process of a new partition. Note that command triggers the execution of any q scripts existing in the current working directory of the running kdb process.</p>
<p>This command allows kdb to continue running and servicing requests while a new partition is constructed. Running kdb remains unware of the new partition until the <code>\l .</code> command is issued.</p>
<p>See also: <a href="https://code.kx.com/q/ref/dotq/#ql-load" title="code.kx.com">.Q.l</a></p>
]]></content>
		</item>
		
		<item>
			<title>How do I comment q code?</title>
			<link>https://kdbfaq.com/how-do-i-comment-q-code/</link>
			<pubDate>Tue, 15 Mar 2011 03:15:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-comment-q-code/</guid>
			<description>A till-end-of-line comment begins with a single slash that appears either –
 at the start of a non-empty line,  / this line is ignored /so is this one or
is preceded by a space:  foo: 47; / this is also a comment 42+/1 2 3 / The first / does NOT start a comment! In the last example, the first slash functions as the adverb over.
Begin a block comment with a lone backslash at the start of a line, and finish it with sole slash –</description>
			<content type="html"><![CDATA[<p>A till-end-of-line comment begins with a single slash that appears either –</p>
<ol>
<li>at the <em>start of a <strong>non-empty</strong></em> line,</li>
</ol>
<pre><code>/ this line is ignored
/so is this one
</code></pre><p>or</p>
<ol start="2">
<li>is <em>preceded by a space</em>:</li>
</ol>
<pre><code>foo: 47;      / this is also a comment
42+/1 2 3     / The first / does NOT start a comment!
</code></pre><p>In the last example, the first slash functions as the adverb <a href="https://code.kx.com/q/ref/overloads/#slash"><!-- raw HTML omitted -->over<!-- raw HTML omitted --></a>.</p>
<p>Begin a block comment with a lone backslash at the start of a line, and finish it with sole slash –</p>
<pre><code>\
All of this is a block comment.
Even /\ this is OK.
/
x: 47              / this line (before the slash) is code
</code></pre><p>or the reverse:</p>
<pre><code>/
The opposite works, too.
Using block comments to comment out code can be
confusing unless you pick one way and stick to it.
\
</code></pre><p>A <a href="https://code.kx.com/q/ref/overloads/#backslash" title="code.kx.com">\</a> does not have to be matched; it then serves as an end-of-file indicator:</p>
<pre><code>\
all lines below are
i
g
n
o
r
e
d
</code></pre><p>Lastly, if a script’s first line begins with ‘#!’, that line is skipped, e.g.:</p>
<pre><code>#! blah.. blah..
</code></pre>]]></content>
		</item>
		
		<item>
			<title>Can a historical database be partitioned on multiple levels – say, by date, then symbol?</title>
			<link>https://kdbfaq.com/can-a-historical-database-be-partitioned-on-multiple-levels-say-by-date-then-symbol/</link>
			<pubDate>Tue, 15 Mar 2011 02:23:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/can-a-historical-database-be-partitioned-on-multiple-levels-say-by-date-then-symbol/</guid>
			<description>No. Only one level of partitioning (by date, month, year or integer) is supported.</description>
			<content type="html"><![CDATA[<p>No. Only one level of partitioning (by date, month, year or integer) is supported.</p>
]]></content>
		</item>
		
		<item>
			<title>‘exit’ fails to terminate kdb console.  How do I gracefully exit a kdb process?</title>
			<link>https://kdbfaq.com/exit-fails-to-terminate-kdb-console-how-do-i-gracefully-exit-a-kdb-process/</link>
			<pubDate>Tue, 15 Mar 2011 01:56:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/exit-fails-to-terminate-kdb-console-how-do-i-gracefully-exit-a-kdb-process/</guid>
			<description>exit 0 or \ or simply control+d from a console.
Inside a function, the double backslash requires escaping. Use value &amp;quot;\\\\&amp;quot; or system \\
Note: kdb process exits can be trapped via .z.exit.</description>
			<content type="html"><![CDATA[<p><a href="https://code.kx.com/q/ref/exit/"><!-- raw HTML omitted -->exit 0<!-- raw HTML omitted --></a> or <a href="https://code.kx.com/q/basics/syscmds/#quit"><!-- raw HTML omitted -->\<!-- raw HTML omitted --></a> or simply control+d from a console.</p>
<p>Inside a function, the double backslash requires escaping. Use <a href="https://code.kx.com/q/ref/value/"><code>value &quot;\\\\&quot;</code></a> or <a href="https://code.kx.com/q/ref/system/"><code>system \\</code></a></p>
<p>Note: kdb process exits can be trapped via <a href="https://code.kx.com/q/ref/dotz/#zexit-action-on-exit"><!-- raw HTML omitted -->.z.exit<!-- raw HTML omitted --></a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How do i interpret the output of function .Q.w[]?</title>
			<link>https://kdbfaq.com/how-do-i-interpret-the-output-of-function-q-w/</link>
			<pubDate>Mon, 14 Mar 2011 01:39:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-interpret-the-output-of-function-q-w/</guid>
			<description>An example explains it best:
$ rlwrap q KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems q).Q.w[] used| 108432 / bytes malloced heap| 67108864 / heap bytes available peak| 67108864 / heap high-watermark in bytes wmax| 0 / workspace limit from -w param mmap| 0 / amount of memory mapped syms| 537 / number of symbols interned symw| 15616 / bytes used by 537 symbols q) Note how .Q.w is simply a pretty print output of \w and the workspace memory footprint from \w 0.</description>
			<content type="html"><![CDATA[<p>An example explains it best:</p>
<pre><code>$ rlwrap q
KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems
q).Q.w[] 
used| 108432   / bytes malloced
heap| 67108864 / heap bytes available
peak| 67108864 / heap high-watermark in bytes
wmax| 0        / workspace limit from -w param
mmap| 0        / amount of memory mapped
syms| 537      / number of symbols interned
symw| 15616    / bytes used by 537 symbols
q)
</code></pre><p>Note how <a href="https://code.kx.com/q/ref/dotq/#qw-memory-stats">.Q.w</a> is simply a pretty print output of <a href="https://code.kx.com/q/basics/syscmds/#w-workspace">\w</a> and the workspace memory footprint from <a href="https://code.kx.com/q/basics/syscmds/#w-workspace">\w 0</a>. </p>
<pre><code>q).Q.w
k){`used`heap`peak`wmax`mmap`syms`symw!(.”\\w”),.”\\w 0″}
q)\w
108304 67108864 67108864 0 0j
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>I’ve setup many views based on a single large table. How much of a performance penalty will I pay?</title>
			<link>https://kdbfaq.com/ive-setup-many-views-based-on-a-single-large-table-how-much-of-a-performance-penalty-will-i-pay/</link>
			<pubDate>Sun, 13 Mar 2011 17:19:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/ive-setup-many-views-based-on-a-single-large-table-how-much-of-a-performance-penalty-will-i-pay/</guid>
			<description>A view is syntactic sugar for a canned query. Unless the view is referenced, it does not expend computational resources.
See also: view, views, :: , .z.b and \b</description>
			<content type="html"><![CDATA[<p>A view is syntactic sugar for a canned query. Unless the view is referenced, it does not expend computational resources.</p>
<p>See also: <a href="https://code.kx.com/q/ref/view/">view</a>, <a href="https://code.kx.com/q/ref/view/">views</a>, <a href="https://code.kx.com/q/ref/identity/"><!-- raw HTML omitted -->::<!-- raw HTML omitted --></a> , <a href="https://code.kx.com/q/ref/dotz/#zb-dependencies"><!-- raw HTML omitted -->.z.b<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/basics/syscmds/#b-views"><!-- raw HTML omitted -->\b<!-- raw HTML omitted --></a></p>
]]></content>
		</item>
		
		<item>
			<title>I want to keep kdb rdb super fast and prevent users from introducing large latencies by using a timeout argument of 2 seconds.  is this a good idea?</title>
			<link>https://kdbfaq.com/i-want-to-keep-kdb-rdb-super-fast-and-prevent-users-from-introducing-large-latencies-by-using-a-timeout-argument-of-2-seconds-is-this-a-good-idea/</link>
			<pubDate>Sun, 13 Mar 2011 17:12:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-want-to-keep-kdb-rdb-super-fast-and-prevent-users-from-introducing-large-latencies-by-using-a-timeout-argument-of-2-seconds-is-this-a-good-idea/</guid>
			<description>It is true that no single user query will block for more than the time specified in the -T command line argument. However, be sure to disable timeout via \T 0 prior to executing the end-of-day batch processing, or it will fail with a ‘stoperror.</description>
			<content type="html"><![CDATA[<p>It is true that no single user query will block for more than the time specified in the <a href="https://code.kx.com/q/basics/cmdline/#-t-timeout">-T</a> command line argument. However, be sure to disable timeout via <a href="https://code.kx.com/q/basics/syscmds/#t-timeout">\T 0</a> prior to executing the end-of-day batch processing, or it will fail with a <!-- raw HTML omitted -->‘stop<!-- raw HTML omitted --> error.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I efficiently retrieve the first n rows of a query result?</title>
			<link>https://kdbfaq.com/how-do-i-efficiently-retrieve-the-first-n-rows-of-a-query-result/</link>
			<pubDate>Sun, 13 Mar 2011 04:25:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-efficiently-retrieve-the-first-n-rows-of-a-query-result/</guid>
			<description>select[n]. The first example below retrieves the first 10 rows, whereas the second example retrieves the last 10 rows:
select [10] from table where date=2011.02.27 select [-10] from table where date=2011.02.27 If the table is in memory, you can use the virtual column i to retrieve a specific range of rows:
If you want to retrieve specific rows by index from a partitioned table, use .Q.ind.
C.f. # (take) and sublist</description>
			<content type="html"><![CDATA[<p><a href="https://code.kx.com/q/ref/select/" title="code.kx.com">select[n]</a>. The first example below retrieves the first 10 rows, whereas the second example retrieves the last 10 rows:</p>
<pre><code>select [10] from table where date=2011.02.27
select [-10] from table where date=2011.02.27
</code></pre><p>If the table is in memory, you can use the virtual column i to retrieve a specific range of rows:</p>
<!-- raw HTML omitted -->
<p>If you want to retrieve specific rows by index from a partitioned table, use <a href="https://code.kx.com/q/ref/dotq/#qind-partitioned-index" title="code.kx.com">.Q.ind</a>.</p>
<p>C.f. <a href="https://code.kx.com/q/ref/take/" title="code.kx.com"># (take)</a> and <a href="https://code.kx.com/q/ref/sublist/" title="code.kx.com">sublist</a></p>
]]></content>
		</item>
		
		<item>
			<title>How can I have kdb automatically load q code at startup in every session?</title>
			<link>https://kdbfaq.com/how-can-i-have-kdb-automatically-load-q-code-at-startup-in-every-session/</link>
			<pubDate>Sun, 13 Mar 2011 02:55:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-have-kdb-automatically-load-q-code-at-startup-in-every-session/</guid>
			<description>Every time you start q, it looks for a file called q.q (in $QHOME, if defined, or current working directory otherwise). If q finds q.q, it will execute it before presenting a prompt or calling any script you provided on the command line.
If you want to call the file something else, or keep it separate from your q installation, you can set the environment variable QINIT to the path to your initialization file.</description>
			<content type="html"><![CDATA[<p>Every time you start q, it looks for a file called q.q (in <code>$QHOME</code>, if defined, or current working directory otherwise). If q finds q.q, it will execute it before presenting a prompt or calling any script you provided on the command line.</p>
<p>If you want to call the file something else, or keep it separate from your q installation, you can set the environment variable <code>QINIT</code> to the path to your initialization file.</p>
<p>It is also possible to add k code to q.k (which will be executed before q.q), although we’ve never needed to.</p>
]]></content>
		</item>
		
		<item>
			<title>How can I set a trigger on a kdb table?</title>
			<link>https://kdbfaq.com/how-can-i-set-a-trigger-on-a-kdb-table/</link>
			<pubDate>Sun, 13 Mar 2011 00:36:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-set-a-trigger-on-a-kdb-table/</guid>
			<description>Triggers went away in k4; kdb does not provide a table trigger mechanism. However, your needs may be satisfied with views and/or the function .z.vs</description>
			<content type="html"><![CDATA[<p>Triggers went away in k4; kdb does not provide a table trigger mechanism. However, your needs may be satisfied with <a href="http://code.kx.com/trac/wiki/Reference/view">views</a> and/or the function <a href="http://code.kx.com/trac/wiki/Reference/dotzdotvs">.z.vs</a></p>
]]></content>
		</item>
		
		<item>
			<title>peach is great.  Can I simply use it everywhere in place of each?</title>
			<link>https://kdbfaq.com/peach-is-great-can-i-simply-use-it-everywhere-in-place-of-each/</link>
			<pubDate>Sat, 12 Mar 2011 18:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/peach-is-great-can-i-simply-use-it-everywhere-in-place-of-each/</guid>
			<description>No. Multithreaded q code cannot have side effects, so the functions called by peach must be side-effect free. You will receive the error ‘mq if you try otherwise.
See also: kdb error code table</description>
			<content type="html"><![CDATA[<p>No. Multithreaded q code cannot have side effects, so the functions called by peach must be side-effect free. You will receive the error ‘mq if you try otherwise.</p>
<p>See also:  <a href="https://code.kx.com/q4m3/B_Error_Messages/" title="code.kx.com">kdb error code table</a></p>
]]></content>
		</item>
		
		<item>
			<title>How do I load in a csv file into kdb with the headers as table fieldnames?</title>
			<link>https://kdbfaq.com/how-do-i-load-in-a-csv-file-into-kdb-with-the-headers-as-table-fieldnames/</link>
			<pubDate>Sat, 12 Mar 2011 04:24:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-load-in-a-csv-file-into-kdb-with-the-headers-as-table-fieldnames/</guid>
			<description>Insert the keyword enlist before the delimiter argument to 0: or 1:.
(“SSS”; enlist “,”) 0: `:filename.csv See also: field parsing and operator 0:</description>
			<content type="html"><![CDATA[<p>Insert the keyword <a href="https://code.kx.com/q/ref/enlist/">enlist</a> before the delimiter argument to 0: or 1:.</p>
<pre><code>(“SSS”; enlist “,”) 0: `:filename.csv
</code></pre><p>See also: <a href="https://code.kx.com/q4m3/11_IO/#115-parsing-records" title="code.kx.com">field parsing</a> and operator <a href="https://code.kx.com/q/ref/file-text/" title="code.kx.com">0:</a></p>
]]></content>
		</item>
		
		<item>
			<title>I’m purchasing new kdb server hardware. How should it be configured?</title>
			<link>https://kdbfaq.com/im-purchasing-new-kdb-server-hardware-how-should-it-be-configured/</link>
			<pubDate>Sat, 12 Mar 2011 02:53:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/im-purchasing-new-kdb-server-hardware-how-should-it-be-configured/</guid>
			<description>It depends on the usage pattern you expect, but as a rule of thumb, allocate the hardware dollars in the following order:
 memory disk i/o cpu  </description>
			<content type="html"><![CDATA[<p>It depends on the usage pattern you expect, but as a rule of thumb, allocate the hardware dollars in the following order:</p>
<ol>
<li>memory</li>
<li>disk i/o</li>
<li>cpu</li>
</ol>
]]></content>
		</item>
		
		<item>
			<title>What are the implicit, default argument names to a function?</title>
			<link>https://kdbfaq.com/what-are-the-implicit-default-argument-names-to-a-function/</link>
			<pubDate>Sat, 12 Mar 2011 00:32:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-are-the-implicit-default-argument-names-to-a-function/</guid>
			<description>x, yand z. This applies both to named and anonymous functions:
q)f: {x + y + z} q)f[1; 2; 3] 6 q){x + y + z}[1; 2; 3] 6 q) If zappears in the definition of an argument-less function, then the function takes 3 arguments. It is not necessary for xor yto appear:
q)f: {z} q)f[3] {z}[3] q)f[3; 4; 5] 5 q) Similarly, if y appears but z does not appear, then the function takes 2 arguments.</description>
			<content type="html"><![CDATA[<p><!-- raw HTML omitted -->x<!-- raw HTML omitted -->, <!-- raw HTML omitted -->y<!-- raw HTML omitted --> and <!-- raw HTML omitted -->z<!-- raw HTML omitted -->. This applies both to named and anonymous functions:</p>
<pre><code>q)f: {x + y + z}
q)f[1; 2; 3] 6
q){x + y + z}[1; 2; 3] 6
q)
</code></pre><p>If <!-- raw HTML omitted -->z<!-- raw HTML omitted --> appears in the definition of an argument-less function, then the function takes 3 arguments. It is not necessary for <!-- raw HTML omitted -->x<!-- raw HTML omitted --> or <!-- raw HTML omitted -->y<!-- raw HTML omitted --> to appear:</p>
<pre><code>q)f: {z}
q)f[3]
{z}[3]
q)f[3; 4; 5]
5
q)
</code></pre><p>Similarly, if y appears but z does not appear, then the function takes 2 arguments. What may surprise you is that, if none of <!-- raw HTML omitted -->x<!-- raw HTML omitted -->, <!-- raw HTML omitted -->y<!-- raw HTML omitted -->, or <!-- raw HTML omitted -->z<!-- raw HTML omitted --> appear, then the function takes a single argument called <!-- raw HTML omitted -->x<!-- raw HTML omitted -->:</p>
<pre><code>q)f: {42}
q)f[] 42
q)value f
0xa00001
,`x
`symbol$()
,`
42
“{42}”
q)
</code></pre><p>This is only of practical import if you want to test a function for how many arguments it takes. If you really want to define a function taking no arguments, you might try to use an empty parameter list:</p>
<pre><code>q)f: {[] 47}
q)f[] 42
q)value f
0xa00001
,`
`symbol$()
,`
47
“{[] 47}”
q)
</code></pre><p>While we’ve succeeded only in defining a function with a single, unnamed parameter, all is not lost. If you follow a convention of always declaring nullary functions in this way, that’s enough to test at runtime how many arguments a function requires.</p>
]]></content>
		</item>
		
		<item>
			<title>Why can’t kdb’s debugger tell me exactly which line in the function invoked the error?</title>
			<link>https://kdbfaq.com/why-cant-kdbs-debugger-tell-me-exactly-which-line-in-the-function-invoked-the-error/</link>
			<pubDate>Fri, 11 Mar 2011 04:40:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/why-cant-kdbs-debugger-tell-me-exactly-which-line-in-the-function-invoked-the-error/</guid>
			<description>q simply does not seem to hold that information during run time. It knows the state of the stack and function undergoing execution prior to the error event, but cannot map the program counter to a specific line in the q code.
Although it can’t directly tell you the name of the function in which you’ve trapped, it does know the body of the current function via the variable .z.s (self).</description>
			<content type="html"><![CDATA[<p>q simply does not seem to hold that information during run time. It knows the state of the stack and function undergoing execution prior to the error event, but cannot map the program counter to a specific line in the q code.</p>
<p>Although it can’t directly tell you the name of the function in which you’ve trapped, it does know the <em>body</em> of the current function via the variable <a href="https://code.kx.com/q/ref/dotz/#zs-self"><!-- raw HTML omitted -->.z.s (self)<!-- raw HTML omitted --></a>. Using <a href="https://code.kx.com/q/ref/dotz/#zs-self"><!-- raw HTML omitted -->.z.s (self)<!-- raw HTML omitted --></a>, you can use the following handy code to deduce the name of the function:</p>
<pre><code>function_name: {[body] names: value “\\f”;
bodies: value each names;
matches: names where body ~/: bodies;
$[0 = count matches;
‘ “Not found (try a different namespace?)”;
  1 = count matches;
first matches;
/ else
matches]}
</code></pre><p>Here’s how you use it:</p>
<pre><code>q)f: {break}
q)f[] {break}
‘break
q))function_name .z.s
`f
q))
</code></pre><p>Things get more complicated if you put functions into different namespaces:</p>
<pre><code>q)\d .foo
q.foo)bar: {break}
q.foo)\d .
q).foo.bar[] {break}
‘break
q.foo))`.[`function_name] .z.s
`bar
q.foo))
</code></pre><p>As you can see, q puts you into the namespace that was <em>in effect at the time the function was defined</em>. You may want to put function_name into a file that you load into every namespace so you don’t have to remember to type `.[`function_name].</p>
<p>Note that that namespace that q breaks into is not necessarily the namespace in which the function is defined:</p>
<pre><code>q).foo.baz: {break}
q).foo.baz[] {break;}
‘break
q))function_name .z.s
‘Not found (try a different namespace?)
q))\d .foo
q.foo))`.[`function_name] .z.s
`baz
q.foo))
</code></pre><p>Especially interesting, regarding this last example, is that function_name returns the correct function even though bar and baz have identical bodies:</p>
<pre><code>q.foo))bar
{break}
q.foo)baz
{break}
q.foo))string[bar] ~ string baz
1b
q.foo))bar ~ baz
0b
q.foo))
</code></pre>]]></content>
		</item>
		
		<item>
			<title>Why doesn’t ‘\cd /fs/local/db;’ work?</title>
			<link>https://kdbfaq.com/why-doesnt-cd-fs-local-db-work/</link>
			<pubDate>Fri, 11 Mar 2011 04:14:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/why-doesnt-cd-fs-local-db-work/</guid>
			<description>Try removing the trailing semicolon. You’ve just entered directory db;not db.</description>
			<content type="html"><![CDATA[<p>Try removing the trailing semicolon. You’ve just entered directory <!-- raw HTML omitted -->db;<!-- raw HTML omitted --> not <!-- raw HTML omitted -->db<!-- raw HTML omitted -->.</p>
]]></content>
		</item>
		
		<item>
			<title>What companion tools to kdb are useful?</title>
			<link>https://kdbfaq.com/what-companion-tools-to-kdb-are-useful/</link>
			<pubDate>Fri, 11 Mar 2011 02:50:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-companion-tools-to-kdb-are-useful/</guid>
			<description>Must Haves  rlwrap rlwrap (Mac OS X) taskset  Useful  screen byobu  See also: kdb related software</description>
			<content type="html"><![CDATA[<h3 id="must-haves">Must Haves</h3>
<ul>
<li><a href="https://github.com/hanslub42/rlwrap">rlwrap</a></li>
<li><a href="https://formulae.brew.sh/formula/rlwrap">rlwrap (Mac OS X)</a></li>
<li><a href="http://www.cyberciti.biz/faq/taskset-cpu-affinity-command/">taskset</a></li>
</ul>
<h3 id="useful">Useful</h3>
<ul>
<li><a href="http://www.gnu.org/software/screen/">screen</a></li>
<li><a href="https://launchpad.net/byobu">byobu</a></li>
</ul>
<p>See also: <a href="https://www.kdbfaq.com/tag/sybase">kdb related software</a></p>
]]></content>
		</item>
		
		<item>
			<title>How does ‘protected execution’ (or exception handling) work in q?</title>
			<link>https://kdbfaq.com/how-does-protected-execution-or-exception-handling-work-in-q/</link>
			<pubDate>Thu, 10 Mar 2011 04:27:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-does-protected-execution-or-exception-handling-work-in-q/</guid>
			<description>Protected execution is q’s model of exception handling. If you are familiar with exception models (such as try, catch, and throw) from another language, you will notice a resemblance.
In any exception handling model, there is a block of code to attempt to execute and one or more blocks of code to invoke should the attempted block fail. Moreover, the error handling blocks have a proscribed form. Lastly, there is a mechanism to raise an exception.</description>
			<content type="html"><![CDATA[<p>Protected execution is q’s model of exception handling. If you are familiar with exception models (such as <!-- raw HTML omitted -->try<!-- raw HTML omitted -->, <!-- raw HTML omitted -->catch<!-- raw HTML omitted -->, and <!-- raw HTML omitted -->throw<!-- raw HTML omitted -->) from another language, you will notice a resemblance.</p>
<p>In any exception handling model, there is a block of code to attempt to execute and one or more blocks of code to invoke should the attempted block fail. Moreover, the error handling blocks have a proscribed form. Lastly, there is a mechanism to raise an exception.</p>
<p>Let’s look at a simple example in q and break it down:</p>
<pre><code>LaidBackLoad: {[file]
  @[{system &quot;l &quot;, x; 1b}; / code to attempt
    file;                 / argument
    {[err] 0N! err; 0b}]} / error handler
</code></pre><p>In q, there is only one error handling block, and both the try block and the error handling block must be functions. In addition, the error handler takes a single parameter, which – if the error handler is called – will be a string.</p>
<p>In our example, the function to try takes only a single parameter, and that’s why the protected execution expression starts with an <!-- raw HTML omitted -->@<!-- raw HTML omitted -->. If your try function takes more than one parameter, use <!-- raw HTML omitted -->.<!-- raw HTML omitted --> instead:</p>
<pre><code>LaidBackEqual: {
  .[{x = y};              / code to attempt
    (x; y);               / arguments
    {[err] 0N! err; 0b}]} / error handler
</code></pre><p>You signal an error (which may be a symbol or a string) using the <a href="https://code.kx.com/q/ref/signal/">‘ (signal)</a> operator:</p>
<pre><code>CantBeNegative: {if [x &lt; 0; ‘ “Must be &gt;= 0”]; x}
</code></pre><p>This is exactly the same mechanism that q uses to let us know when we have done something wrong:</p>
<pre><code>q)(1 2 3) = 1 2
‘length
q)
</code></pre><p>There is one last detail to note when reviewing the above examples. Protected execution expressions are <em>expressions</em>, and they have a value. If the try function does not signal, then the expression’s value is the try function’s return value. Otherwise, the protected execution expression’s value is the value returned by the error handler.</p>
]]></content>
		</item>
		
		<item>
			<title>How can I find a listing of tables in a given namespace?</title>
			<link>https://kdbfaq.com/how-can-i-find-a-listing-of-tables-in-a-given-namespace/</link>
			<pubDate>Thu, 10 Mar 2011 04:11:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-find-a-listing-of-tables-in-a-given-namespace/</guid>
			<description>To list the tables in the current namespace, use \a; to list the tables from a specific namespace, both \a namespaceand tables `namespacework:
$ q sp.q KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems +`p`city!(`p$`p1`p2`p3`p4`p5`p6`p1`p2;`london`london`london`l.. (+(,`color)!,`blue`green`red)!+(,`qty)!,900 1000 1200 +`s`p`qty!(`s$`s1`s1`s1`s2`s3`s4;`p$`p1`p4`p6`p2`p2`p4;300 200 100 400 200 300) q)\a `p`s`sp q)\a . `p`s`sp q)tables `. `p`s`sp q) </description>
			<content type="html"><![CDATA[<p>To list the tables in the current namespace, use <!-- raw HTML omitted -->\a<!-- raw HTML omitted -->; to list the tables from a specific namespace, both <!-- raw HTML omitted -->\a namespace<!-- raw HTML omitted --> and <!-- raw HTML omitted -->tables `namespace<!-- raw HTML omitted --> work:</p>
<pre><code>$ q sp.q
KDB+ 2.7 2011.02.16 Copyright © 1993-2011 Kx Systems
+`p`city!(`p$`p1`p2`p3`p4`p5`p6`p1`p2;`london`london`london`l..
(+(,`color)!,`blue`green`red)!+(,`qty)!,900 1000 1200
+`s`p`qty!(`s$`s1`s1`s1`s2`s3`s4;`p$`p1`p4`p6`p2`p2`p4;300 200 100 400 200 300)
q)\a
`p`s`sp
q)\a .
`p`s`sp
q)tables `.
`p`s`sp
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>What is a dyadic function?</title>
			<link>https://kdbfaq.com/what-is-a-dyadic-function/</link>
			<pubDate>Thu, 10 Mar 2011 03:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-is-a-dyadic-function/</guid>
			<description>A function that takes two arguments. Dyadic is to binary as Aphrodite is to Venus.
See wikipedia’s definition.</description>
			<content type="html"><![CDATA[<p>A function that takes two arguments. Dyadic is to binary as Aphrodite is to Venus.</p>
<p>See wikipedia’s <a href="http://en.wikipedia.org/wiki/APL_syntax_and_symbols#Dyadic_functions">definition</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I delete a column from a table?</title>
			<link>https://kdbfaq.com/how-do-i-delete-a-column-from-a-table/</link>
			<pubDate>Wed, 09 Mar 2011 04:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-delete-a-column-from-a-table/</guid>
			<description>The delete command works for that, too. To remove a column named xyzfrom table t, use
delete xyz from `t // in place delete (backquote) delete xyz from t // returns a copy minus column xyz </description>
			<content type="html"><![CDATA[<p>The <a href="https://anonymous:anonymous@code.kx.com/trac/wiki/Reference/delete"><!-- raw HTML omitted -->delete<!-- raw HTML omitted --></a> command works for that, too. To remove a column named <!-- raw HTML omitted -->xyz<!-- raw HTML omitted --> from table <!-- raw HTML omitted -->t<!-- raw HTML omitted -->, use</p>
<pre><code>delete xyz from `t // in place delete (backquote)
delete xyz from t  // returns a copy minus column xyz
</code></pre>]]></content>
		</item>
		
		<item>
			<title>I understand white space matters in q code.  Where does it matter?</title>
			<link>https://kdbfaq.com/i-understand-white-space-matters-in-q-code-where-does-it-matter/</link>
			<pubDate>Wed, 09 Mar 2011 04:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-understand-white-space-matters-in-q-code-where-does-it-matter/</guid>
			<description>The first character before a ‘/’ that begins a comment must be whitespace (newline is OK). Every line after the first in a multiline expressions must be indented.  The latter rule applies, for example, to functions. The following is not valid q: Even a function’s closing brace must be indented if it appears on a line by itself:
 Function definition is not the only time you have to be careful to follow this rule, however.</description>
			<content type="html"><![CDATA[<ul>
<li>The first character before a ‘/’ that begins a comment must be whitespace (newline is OK).</li>
<li>Every line after the first in a multiline expressions must be indented.</li>
</ul>
<p>The latter rule applies, for example, to functions. The following is <!-- raw HTML omitted -->not valid q:<!-- raw HTML omitted --></p>
<script type="application/javascript" src="https://gist.github.com/ahnj/b0181cdbf1629e90231fe20c62febbdd.js"></script>

<p>Even a function’s closing brace must be indented if it appears on a line by itself:</p>
<script type="application/javascript" src="https://gist.github.com/ahnj/e3698e79bd75e7ef7e660c660d43773a.js"></script>

<p>Function definition is not the only time you have to be careful to follow this rule, however. In the following example, g is not the list (47; 48); rather, g is a projection of the comma operator with its first argument set to 47:</p>
<pre><code>g: 47,
48
</code></pre>]]></content>
		</item>
		
		<item>
			<title>I know SQL and don’t care to learn q. Can I still get my work done while benefiting from kdb’s speed?</title>
			<link>https://kdbfaq.com/i-know-sql-and-dont-care-to-learn-q-can-i-still-get-my-work-done-while-benefiting-from-kdbs-speed/</link>
			<pubDate>Wed, 09 Mar 2011 03:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-know-sql-and-dont-care-to-learn-q-can-i-still-get-my-work-done-while-benefiting-from-kdbs-speed/</guid>
			<description>Yes and no. q supports SQL out of the box. In many cases, you will see an improvement in performance compared to a similar traditional RDBMS. However, q does not optimize your queries for you, so some queries may actually take more time.
James Gosling stated that he purposely made Java syntax C-like to facilitate the adoption of the JVM platform. q’s query language was similarly designed to resemble SQL.Begin with what you know, and incrementally refine your queries using q-specific features to get the best performance possible.</description>
			<content type="html"><![CDATA[<p>Yes and no. q supports <!-- raw HTML omitted -->SQL <!-- raw HTML omitted -->out of the box. In many cases, you will see an improvement in performance compared to a similar traditional <!-- raw HTML omitted -->RDBMS. <!-- raw HTML omitted --> However, q does not optimize your queries for you, so some queries may actually take more time.</p>
<p><a href="http://en.wikipedia.org/wiki/James_Gosling">James Gosling</a> stated that he purposely made Java syntax C-like to facilitate the adoption of the <!-- raw HTML omitted -->JVM <!-- raw HTML omitted -->platform. q’s query language was similarly designed to resemble <!-- raw HTML omitted -->SQL.<!-- raw HTML omitted --> Begin with what you know, and incrementally refine your queries using q-specific features to get the best performance possible.</p>
]]></content>
		</item>
		
		<item>
			<title>How do I delete the nth row from a table?</title>
			<link>https://kdbfaq.com/how-do-i-delete-the-nth-row-from-a-table/</link>
			<pubDate>Tue, 08 Mar 2011 04:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-delete-the-nth-row-from-a-table/</guid>
			<description>Use delete and the virtual column i:
 delete from `t where i = n Don’t forget the backquote if you intend to delete-in-place.</description>
			<content type="html"><![CDATA[<p>Use <a href="https://code.kx.com/q/ref/delete/"><!-- raw HTML omitted -->delete<!-- raw HTML omitted --></a> and the virtual column <!-- raw HTML omitted -->i<!-- raw HTML omitted -->:</p>
<pre><code>    delete from `t where i = n
</code></pre><p>Don’t forget the backquote if you intend to delete-in-place.</p>
]]></content>
		</item>
		
		<item>
			<title>What does it mean for a q function or table to be a ‘first class’ type?</title>
			<link>https://kdbfaq.com/what-does-it-mean-for-a-q-function-or-table-to-be-a-first-class-type/</link>
			<pubDate>Tue, 08 Mar 2011 03:47:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-does-it-mean-for-a-q-function-or-table-to-be-a-first-class-type/</guid>
			<description>Like any other value, you can do the following with functions:
 pass them as arguments to other functions return them from functions create new functions at run time  In fact, since the syntax of q is consistent with the semantic similarity between calling a function and indexing a data structure, sometimes you won’t even care whether a particular value is a function or data.
Tables can be treated as ordinary data as well.</description>
			<content type="html"><![CDATA[<p>Like any other value, you can do the following with functions:</p>
<ul>
<li>pass them as arguments to other functions</li>
<li>return them from functions</li>
<li>create new functions at run time</li>
</ul>
<p>In fact, since the syntax of q is consistent with the semantic similarity between calling a function and indexing a data structure, sometimes you won’t even care whether a particular value is a function or data.</p>
<p>Tables can be treated as ordinary data as well. In a typical database, tables can only be manipulated and queried using a special language via a specific access mechanism (.NET’s <a href="http://msdn.microsoft.com/library/bb308959.aspx"><!-- raw HTML omitted -->LINQ<!-- raw HTML omitted --></a> is Microsoft’s effort to bridge the gap). In q, although you can use a query language when convenient, you can also use any other feature of the q language that you might want. For example, sometime it’s much simpler or faster to express a table update using <a href="https://code.kx.com/q/ref/apply/"><!-- raw HTML omitted -->. (apply)<!-- raw HTML omitted --></a>.</p>
]]></content>
		</item>
		
		<item>
			<title>What kdb connection libraries exist?</title>
			<link>https://kdbfaq.com/what-kdb-connection-libraries-exist/</link>
			<pubDate>Tue, 08 Mar 2011 02:44:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-kdb-connection-libraries-exist/</guid>
			<description> Java C C# Python Python qpy Matlab R  </description>
			<content type="html"><![CDATA[<ul>
<li><a href="https://code.kx.com/q/interfaces/">Java</a></li>
<li><a href="https://code.kx.com/q/interfaces/">C</a></li>
<li><a href="https://code.kx.com/q/interfaces/">C#</a></li>
<li><a href="https://code.kx.com/q/interfaces/pyq/">Python</a></li>
<li><a href="https://bitbucket.org/halotis/qpy">Python qpy</a></li>
<li><a href="https://code.kx.com/q/interfaces/">Matlab</a></li>
<li><a href="https://code.kx.com/q/interfaces/">R</a></li>
</ul>
]]></content>
		</item>
		
		<item>
			<title>What are some of the hard limits of kdb I should know about?</title>
			<link>https://kdbfaq.com/what-are-some-of-the-hard-limits-of-kdb-i-should-know-about/</link>
			<pubDate>Mon, 07 Mar 2011 03:25:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-are-some-of-the-hard-limits-of-kdb-i-should-know-about/</guid>
			<description>no more than 2GB over IPC  number of tables mapped is limited by number of file descriptors allowed by OS maximum of 32 global references per function maximum of 23 local variables per function maximum of 96 constants within a function enums are limited to 57 – (type values 20h to 76h) 4096 maximum compressed files open (for versions earlier than 3.1T2013.02.21) 999 nested columns in splayed table 1022 maximum incoming network connections maximum of eight function parameters maximum number of mapped nested columns 1024 maximum number of active `g# indices 1024 maximum branch (if; do; while; $[]) distance is 255 byte codes away (from PC to PC+255bytes!</description>
			<content type="html"><![CDATA[<ul>
<li>no more than 2GB over <!-- raw HTML omitted --><!-- raw HTML omitted -->IPC <!-- raw HTML omitted --><!-- raw HTML omitted --></li>
<li>number of tables mapped is limited by number of file descriptors allowed by OS</li>
<li>maximum of 32 global references per function</li>
<li>maximum of 23 local variables per function</li>
<li>maximum of 96 constants within a function</li>
<li>enums are limited to 57 – (type values 20h to 76h)</li>
<li>4096 maximum compressed files open (for versions earlier than 3.1T2013.02.21)</li>
<li>999 nested columns in splayed table</li>
<li>1022 maximum incoming network connections</li>
<li>maximum of eight function parameters</li>
<li>maximum number of mapped nested columns 1024</li>
<li>maximum number of active `g# indices 1024</li>
<li>maximum branch (if; do; while; $[]) distance is 255 byte codes away (from PC to PC+255bytes!) – if you get a ‘branch error, you have to break the code up into smaller pieces</li>
</ul>
<p>See also: <a href="https://code.kx.com/q4m3/B_Error_Messages/" title="code.kx.com"><!-- raw HTML omitted -->error codes <!-- raw HTML omitted --></a></p>
]]></content>
		</item>
		
		<item>
			<title>Is q a purely functional language?</title>
			<link>https://kdbfaq.com/is-q-a-purely-functional-language/</link>
			<pubDate>Mon, 07 Mar 2011 03:23:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/is-q-a-purely-functional-language/</guid>
			<description>No. Please see wikipedia entry on Purely functional and programming language family tree diagram (K is found toward the left, as a decendent of APL &amp;amp; Scheme.</description>
			<content type="html"><![CDATA[<p>No. Please see wikipedia entry on <a href="http://en.wikipedia.org/wiki/Purely_functional">Purely functional</a> and programming language  <a href="http://rigaux.org/language-study/diagram.png">family tree diagram</a> (K is found toward the left, as a decendent of <a href="http://en.wikipedia.org/wiki/APL_(programming_language)"><!-- raw HTML omitted -->APL<!-- raw HTML omitted --></a> &amp; Scheme.</p>
]]></content>
		</item>
		
		<item>
			<title>Is function overloading supported in q?</title>
			<link>https://kdbfaq.com/is-function-overloading-supported-in-q/</link>
			<pubDate>Mon, 07 Mar 2011 02:52:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/is-function-overloading-supported-in-q/</guid>
			<description>Despite the fact that many native functions are overloaded, no. The last function definition simply overwrites the prior ones.</description>
			<content type="html"><![CDATA[<p>Despite the fact that many native functions are overloaded, no. The last function definition simply overwrites the prior ones.</p>
<!-- raw HTML omitted -->
]]></content>
		</item>
		
		<item>
			<title>Why can’t I use exec on partitioned tables?</title>
			<link>https://kdbfaq.com/why-cant-i-use-exec-on-partitioned-tables/</link>
			<pubDate>Sun, 06 Mar 2011 04:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/why-cant-i-use-exec-on-partitioned-tables/</guid>
			<description>We don’t know. We imagine that kx has something clever up their sleeve that hasn’t been released yet. For now, just use exec select from tablename.</description>
			<content type="html"><![CDATA[<p>We don’t know. We imagine that <a href="http://kx.com">kx</a> has something clever up their sleeve that hasn’t been released yet. For now, just use <!-- raw HTML omitted -->exec select from tablename<!-- raw HTML omitted -->.</p>
]]></content>
		</item>
		
		<item>
			<title>What’s the difference between kdb, kdb&#43;, k, k4 and q?</title>
			<link>https://kdbfaq.com/whats-the-difference-between-kdb-kdb-k-k4-and-q/</link>
			<pubDate>Sun, 06 Mar 2011 03:00:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/whats-the-difference-between-kdb-kdb-k-k4-and-q/</guid>
			<description>kdb is the predecessor to kdb+®. At one point kdb was an application on top of k. At kdbfaq, we refer to kdb+® as kdb. q is the programming language of kdb. It’s a small layer of syntatic sugar on top of k, plus several significant extensions and new datatypes. k4 is simply an old name for q.
See $QHOME/q.k to see how much of q is written in k.</description>
			<content type="html"><![CDATA[<p>kdb is the predecessor to kdb+®.  At one point kdb was an application on top of k.   At kdbfaq, we refer to kdb+® as kdb. q is the programming language of kdb. It’s a small layer of syntatic sugar on top of k, plus several significant extensions and new datatypes. k4 is simply an old name for q.</p>
<p>See $QHOME/q.k to see how much of q is written in k.</p>
]]></content>
		</item>
		
		<item>
			<title>What does error output ‘nyi mean?</title>
			<link>https://kdbfaq.com/what-does-error-output-nyi-mean/</link>
			<pubDate>Sun, 06 Mar 2011 02:59:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-does-error-output-nyi-mean/</guid>
			<description>‘nyimeans, “not yet implemented.” Sometimes you see this error for expressions that are simply wrong. In any case, you need to try a different approach.
See also: kdb error code table</description>
			<content type="html"><![CDATA[<p><!-- raw HTML omitted -->‘nyi<!-- raw HTML omitted --> means, “not yet implemented.” Sometimes you see this error for expressions that are simply wrong. In any case, you need to try a different approach.</p>
<p>See also:  <a href="https://code.kx.com/q4m3/B_Error_Messages/" title="code.kx.com">kdb error code table</a></p>
]]></content>
		</item>
		
		<item>
			<title>I know kdb is a in-memory database.  my dataset is over two terabytes in size. However my RAM is limited to 32GB.  How will this work?</title>
			<link>https://kdbfaq.com/i-know-kdb-is-a-in-memory-database-my-dataset-is-over-two-terabytes-in-size-however-my-ram-is-limited-to-32gb-how-will-this-work/</link>
			<pubDate>Sun, 06 Mar 2011 02:47:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/i-know-kdb-is-a-in-memory-database-my-dataset-is-over-two-terabytes-in-size-however-my-ram-is-limited-to-32gb-how-will-this-work/</guid>
			<description>Like any computer process, the maximum amount of data loaded into memory is limited by the real physical memory addressable by your process. On a 32-bit server, this can be little as 2GB. On a 64-bit server, 64TB is possible as of this writing, and that limit will continue to increase in the future.
However, with memory mapped tables, the size of your table can theoretically be as large as your disk (assuming it does not exceed the kdb limitations{.</description>
			<content type="html"><![CDATA[<p>Like any computer process, the maximum amount of data loaded into memory is limited by the real physical memory addressable by your process. On a 32-bit server, this can be little as 2GB. On a 64-bit server, 64TB is possible as of this writing, and that limit will continue to increase in the future.</p>
<p>However, with <a href="http://en.wikipedia.org/wiki/Memory-mapped_file">memory mapped</a> tables, the size of your table can theoretically be as large as your disk (assuming it does not exceed the kdb <a href="https://www.kdbfaq.com/what-are-some-of-the-hard-limits-of-kdb-i-should-know-about.html">limitations</a>{.}). As long as the operations you perform on your database don’t require more than your <!-- raw HTML omitted -->RAM <!-- raw HTML omitted -->can handle at once, you’ll be fine. That’s how kdb has been handling multi-terabyte databases for years.</p>
]]></content>
		</item>
		
		<item>
			<title>Can q script be compiled down to native code?</title>
			<link>https://kdbfaq.com/can-q-script-be-compiled-down-to-native-code/</link>
			<pubDate>Sat, 05 Mar 2011 03:35:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/can-q-script-be-compiled-down-to-native-code/</guid>
			<description>We are not aware of an available q-to-native-code compiler.
If your goal is to prevent clients from being able to read your code, see this related faq.</description>
			<content type="html"><![CDATA[<p>We are not aware of an available q-to-native-code compiler.</p>
<p>If your goal is to prevent clients from being able to read your code, see this <a href="https://www.kdbfaq.com/i-dont-want-to-give-away-my-q-source-code-can-i-compile-it-o.html">related faq</a>.</p>
]]></content>
		</item>
		
		<item>
			<title>Is polymorphism supported in q?</title>
			<link>https://kdbfaq.com/is-polymorphism-supported-in-q/</link>
			<pubDate>Sat, 05 Mar 2011 02:54:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/is-polymorphism-supported-in-q/</guid>
			<description>While q has no notion of inheritance, class, metaclass, or prototype, you can create structures packaged with associated functions and invoke those functions via the structures. Consider the following tired OO example expressed in q:
Draw: {[shape] shape[`draw] shape} (Sadly, we cannot write shape.draw shape; dot notation is not supported for local variables, including arguments.)
Given an appropriate set of constructors –
NewCircle: {[x; y; radius] `x`y`radius`draw ! (x; y; radius; {[circle] … })} NewRectangle: {[x; y; w; h] `x`y`w`h`draw !</description>
			<content type="html"><![CDATA[<p>While q has no notion of inheritance, class, metaclass, or prototype, you can create structures packaged with associated functions and invoke those functions via the structures. Consider the following tired OO example expressed in q:</p>
<pre><code>Draw: {[shape] shape[`draw] shape}
</code></pre><p>(Sadly, we cannot write shape.draw shape; dot notation is not supported for local variables, including arguments.)</p>
<p>Given an appropriate set of constructors –</p>
<pre><code>NewCircle: {[x; y; radius] `x`y`radius`draw ! (x; y; radius; {[circle] … })}
NewRectangle: {[x; y; w; h] `x`y`w`h`draw ! (x; y; w; h; {[rect] …})}
</code></pre><p>etc, the following does exactly what you would expect:</p>
<pre><code>shapes: (NewCircle[0; 0; 1];
NewRectangle[-1; -2; 4; 2]);
Draw each shapes;
</code></pre>]]></content>
		</item>
		
		<item>
			<title>How can I glue two tables side by side?</title>
			<link>https://kdbfaq.com/how-can-i-glue-two-tables-side-by-side/</link>
			<pubDate>Fri, 04 Mar 2011 23:46:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-can-i-glue-two-tables-side-by-side/</guid>
			<description>If the tables have the same number of rows, you can use the function ^ (fill):
q)t: ([] x: `a`b; y: 1 2) q)u: ([] z: &amp;quot;YN&amp;quot;) q)t ^ u / works only when count[t] = count[u] x y z ----- a 1 Y b 2 N q) </description>
			<content type="html"><![CDATA[<p>If the tables have the same number of rows, you can use the function <a href="https://code.kx.com/q/ref/fill/"><!-- raw HTML omitted -->^ (fill)<!-- raw HTML omitted --></a>:</p>
<pre><code>q)t: ([] x: `a`b; y: 1 2)
q)u: ([] z: &quot;YN&quot;)
q)t ^ u / works only when count[t] = count[u] 
x y z
-----
a 1 Y
b 2 N
q)
</code></pre>]]></content>
		</item>
		
		<item>
			<title>How do I sort?</title>
			<link>https://kdbfaq.com/how-do-i-sort/</link>
			<pubDate>Fri, 04 Mar 2011 02:45:47 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-sort/</guid>
			<description>Short answer: asc and desc:
q)asc 3 5 2 0 1 `s#0 1 2 3 5 q)desc 3 5 2 0 1 5 3 2 1 0 q) Notice that, in the case of asc, q attaches the `sattribute to the result. (There is no corresponding attribute for a descending sort.)
As an aside, you may be surprised to discover that calling asc on an attribute-free list that happens to be in sorted order will have the `s attribute applied to it as a side effect:</description>
			<content type="html"><![CDATA[<p>Short answer: <a href="https://code.kx.com/q/ref/asc/"><!-- raw HTML omitted -->asc<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/desc/"><!-- raw HTML omitted -->desc<!-- raw HTML omitted --></a>:</p>
<pre><code>q)asc 3 5 2 0 1
`s#0 1 2 3 5
q)desc 3 5 2 0 1
5 3 2 1 0
q)
</code></pre><p>Notice that, in the case of <a href="https://code.kx.com/q/ref/asc/"><!-- raw HTML omitted -->asc<!-- raw HTML omitted --></a>, q attaches the <a href="https://www.kdbfaq.com/i-noticed-a-list-with-a-s-prefix-attached-what-does-this-mea.html"><!-- raw HTML omitted -->`s<!-- raw HTML omitted --> attribute</a> to the result. (There is no corresponding attribute for a descending sort.)</p>
<p>As an aside, you may be surprised to discover that calling <a href="https://code.kx.com/q/ref/asc/"><!-- raw HTML omitted -->asc<!-- raw HTML omitted --></a> on an attribute-free list that happens to be in sorted order will have the `s attribute applied to it as a side effect:</p>
<pre><code>q)list: til 1000
q)attr list
`
q)asc list
`s#0 1 2 3 4 5 6 7 8 9 10 ..
q)list
`s#0 1 2 3 4 5 6 7 8 9 10 ..
q)
</code></pre><p>Also take a look at <a href="https://code.kx.com/q/ref/asc/#iasc" title="code.kx.com">iasc</a> and <a href="https://code.kx.com/q/ref/desc/#idesc" title="code.kx.com">idesc</a>.</p>
<p>Finally, to sort a table instead of a list, see <a href="https://code.kx.com/q/ref/asc/#xasc"><!-- raw HTML omitted -->xasc<!-- raw HTML omitted --></a> and <a href="https://code.kx.com/q/ref/desc/#xdesc"><!-- raw HTML omitted -->xdesc<!-- raw HTML omitted --></a>. Read more about sorting tables from this <a href="https://www.kdbfaq.com/what-is-qs-equivalent-to-sqls-order-by.html">faq</a></p>
]]></content>
		</item>
		
		<item>
			<title>What happens if I duplicate a partition name across multiple segments?</title>
			<link>https://kdbfaq.com/what-happens-if-i-duplicate-a-partition-name-across-multiple-segments/</link>
			<pubDate>Fri, 04 Mar 2011 02:24:34 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-happens-if-i-duplicate-a-partition-name-across-multiple-segments/</guid>
			<description>The content of the table is split across n segments. For example, par.txt specifies 3 segments below and slices a table named vltablename by symbol into 3 segments.
For example:
$ cat /vol/db/par.txt /vol/disk1/segment /vol/disk2/segment /vol/disk3/segment $ $ ls /vol/disk*/segment/2011.03.07/vltable /vol/disk1/segment/2011.03.07/vltable # sym A-I /vol/disk2/segment/2011.03.07/vltable # sym J-R /vol/disk3/segment/2011.03.07/vltable # sym R-Z $ Note that the typical `p# attribute of column sym will be missing in the query result. Remember to re-apply the attribute prior to use.</description>
			<content type="html"><![CDATA[<p>The content of the table is split across n segments. For example, <a href="https://code.kx.com/q/database/segment/">par.txt</a> specifies 3 segments below and slices a table named vltablename by symbol into 3 segments.</p>
<p>For example:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">$ cat /vol/db/par.txt
/vol/disk1/segment
/vol/disk2/segment
/vol/disk3/segment
$
</code></pre></div><div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">$ ls /vol/disk*/segment/2011.03.07/vltable 
/vol/disk1/segment/2011.03.07/vltable <span style="color:#75715e"># sym A-I</span>
/vol/disk2/segment/2011.03.07/vltable <span style="color:#75715e"># sym J-R</span>
/vol/disk3/segment/2011.03.07/vltable <span style="color:#75715e"># sym R-Z</span>
$
</code></pre></div><p>Note that the typical `p# attribute of column sym will be missing in the query result. Remember to re-apply the attribute prior to use.</p>
<p>See also: <a href="https://code.kx.com/q/ref/dotq/#qu-date-based" title="code.kx.com">.Q.u</a>, and <a href="https://code.kx.com/q/ref/dotq/#qpar-locate-partition" title="code.kx.com">.Q.par</a></p>
]]></content>
		</item>
		
		<item>
			<title>I’m used to sprinkling print statements to debug my code.  How can I do the same in q?</title>
			<link>https://kdbfaq.com/im-used-to-sprinkling-print-statements-to-debug-my-code-how-can-i-do-the-same-in-q/</link>
			<pubDate>Thu, 03 Mar 2011 04:42:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/im-used-to-sprinkling-print-statements-to-debug-my-code-how-can-i-do-the-same-in-q/</guid>
			<description>Like printf, 0N! is your friend. When you place 0N! before an expression, it prints the result of that expression to the console and then returns it:
q)1 + 0N! til 10 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10 q) 0N! does change the functionality of your code in one subtle, albeit usually harmless, way. If you place 0N!</description>
			<content type="html"><![CDATA[<p>Like printf, <a href="https://code.kx.com/q/ref/display/"><!-- raw HTML omitted -->0N!<!-- raw HTML omitted --></a> is your friend. When you place <a href="https://code.kx.com/q/ref/display/"><!-- raw HTML omitted -->0N!<!-- raw HTML omitted --></a> before an expression, it prints the result of that expression to the console and then returns it:</p>
<pre><code>q)1 + 0N! til 10
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
q)
</code></pre><p><a href="https://code.kx.com/q/ref/display/"><!-- raw HTML omitted -->0N!<!-- raw HTML omitted --></a> does change the functionality of your code in one subtle, albeit usually harmless, way. If you place <a href="https://code.kx.com/q/ref/display/"><!-- raw HTML omitted -->0N!<!-- raw HTML omitted --></a> before a modifier-assignment operator (e.g. +:, -:), then the result of that assignment is no longer null; it is the value assigned:</p>
<pre><code>q){x +: 47} 1
q){0N! x +: 47} 1
48
48
q)
</code></pre><p>See also: <a href="http://code.kx.com/trac/wiki/DotQ/DotQDots" title="code.kx.com">.Q.s</a> and <a href="http://code.kx.com/trac/wiki/Reference/BangSymbolInternalFunction" title="code.kx.com">.Q.s1</a></p>
]]></content>
		</item>
		
		<item>
			<title>How do I debug code in kdb?</title>
			<link>https://kdbfaq.com/how-do-i-debug-code-in-kdb/</link>
			<pubDate>Thu, 03 Mar 2011 04:38:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/how-do-i-debug-code-in-kdb/</guid>
			<description>You can enable error trapping via the -e command line option at kdb start-up:
$ q -e 1 or from the q console
 q)\e 1 Upon an error, kdb halts and outputs the body of the function (.z.s (self)) in which the error occurred as well as an error message. You are free to inspect the values of any global or local variables to try to diagnose the source of the problem.</description>
			<content type="html"><![CDATA[<p>You can enable error trapping via the <a href="https://code.kx.com/q/basics/cmdline/">-e</a> command line option at kdb start-up:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">$ q -e <span style="color:#ae81ff">1</span>
</code></pre></div><p>or from the q console</p>
<pre><code>    q)\e 1
</code></pre><p>Upon an error, kdb halts and outputs the body of the function (<a href="https://code.kx.com/q/ref/dotz/#zs-self"><!-- raw HTML omitted -->.z.s (self)<!-- raw HTML omitted --></a>) in which the error occurred as well as an error message. You are free to inspect the values of any global or local variables to try to diagnose the source of the problem. At this point you have the following options:</p>
<ul>
<li>type <a href="https://code.kx.com/q/basics/debug/#debugging"><!-- raw HTML omitted -->‘<!-- raw HTML omitted --></a>(single quote) to pop the stack.</li>
<li>type <a href="https://code.kx.com/q/basics/debug/#debugging"><!-- raw HTML omitted -->:<!-- raw HTML omitted --></a>(colon) to resume execution</li>
<li>type <a href="https://code.kx.com/q/basics/debug/#debugging"><!-- raw HTML omitted -->\<!-- raw HTML omitted --></a>(slash) to exit debug mode</li>
</ul>
<p>There is no ability step into a function call or move up and down the stack.</p>
]]></content>
		</item>
		
		<item>
			<title>What data structures does q provide out of the box?</title>
			<link>https://kdbfaq.com/what-data-structures-does-q-provide-out-of-the-box/</link>
			<pubDate>Thu, 03 Mar 2011 03:55:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/what-data-structures-does-q-provide-out-of-the-box/</guid>
			<description>The q language has only 3 non-atomic data structures:
 lists dictionaries tables  However, q does use other structures internally (e.g., hash tables) to enhance the performance of operations on the above language-level structures.</description>
			<content type="html"><![CDATA[<p>The q language has only 3 non-atomic data structures:</p>
<ul>
<li>lists</li>
<li>dictionaries</li>
<li>tables</li>
</ul>
<p>However, q does use other structures internally (e.g., hash tables) to enhance the performance of operations on the above language-level structures.</p>
]]></content>
		</item>
		
		<item>
			<title>Does q pass-by-value or pass-by-reference?</title>
			<link>https://kdbfaq.com/does-q-pass-by-value-or-pass-by-reference/</link>
			<pubDate>Wed, 02 Mar 2011 03:34:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/does-q-pass-by-value-or-pass-by-reference/</guid>
			<description>Semantically, q is pass-by-value. However, q only copies values of structures (i.e., lists, dictionaries, or tables) if they are modified by the callee, so q often performs as well as pass-by-reference.
What do you do if you want to have the callee modify variables passed by the caller? As our reader cyprus points out, you can pass the name of a global variable:
modifier: {[variable_name] variable_name set 47; } caller: {[] global:: &amp;quot;global&amp;quot;; modifier `global; show global; // prints 47 } Whether this should be called pass-by-reference is the subject of many flame wars; Wikipedia’s entry on Evaluation strategy provides a cogent, balanced explanation of the varying interpretations of that (and related) terms.</description>
			<content type="html"><![CDATA[<p>Semantically, q is pass-by-value. However, q only copies values of structures (i.e., lists, dictionaries, or tables) if they are modified by the callee, so q often performs as well as pass-by-reference.</p>
<p>What do you do if you want to have the callee modify variables passed by the caller? As our reader cyprus points out, you can pass the name of a global variable:</p>
<pre><code>modifier: {[variable_name]
 variable_name set 47;
 }
caller: {[]
 global:: &quot;global&quot;;
 modifier `global;
 show global; // prints 47
 }
</code></pre><p>Whether this should be called pass-by-reference is the subject of many flame wars; Wikipedia’s entry on <a href="http://en.wikipedia.org/wiki/Evaluation_strategy">Evaluation strategy</a> provides a cogent, balanced explanation of the varying interpretations of that (and related) terms. What’s important to know are the following:</p>
<ul>
<li>it is impossible for a callee to modify a caller’s local variables, and</li>
<li>passing a large structure between functions is inexpensive until a callee modifies it.</li>
</ul>
]]></content>
		</item>
		
		<item>
			<title>Is it possible to hold partitioned table and unpartitioned table named the same on a single kdb process?</title>
			<link>https://kdbfaq.com/is-it-possible-to-hold-partitioned-table-and-unpartitioned-table-named-the-same-on-a-single-kdb-process/</link>
			<pubDate>Wed, 02 Mar 2011 00:27:00 +0000</pubDate>
			
			<guid>https://kdbfaq.com/is-it-possible-to-hold-partitioned-table-and-unpartitioned-table-named-the-same-on-a-single-kdb-process/</guid>
			<description>No. Because they share the same namespace, you can only have one type or the other.</description>
			<content type="html"><![CDATA[<p>No. Because they share the same namespace, you can only have one type or the other.</p>
]]></content>
		</item>
		
	</channel>
</rss>
