<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Tales from the Evil Empire</title><link>https://weblogs.asp.net:443/bleroy/</link><description>Bertrand Le Roy's blog</description><item><title>Secrets of the Grey Beards: drawing circles with additions and shifts</title><link>https://weblogs.asp.net:443/bleroy/secrets-of-the-grey-beards-drawing-circles-with-additions-and-shifts</link><description>&lt;p&gt;A long time ago, before GPUs, before multicore processors and gigabytes of RAM, clever algorithms were the only way to render complex graphics in real-time. Those algorithms are now mostly forgotten as nobody needs them or is interested in them. Nobody? Well, almost. I like to reverse-engineer the clever tricks programmers of that era were using (in fact, I was one of them), and I hope you'll follow me on this exploration.&lt;/p&gt;
&lt;!--more--&gt;
&lt;script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=MML_HTMLorMML"&gt;&lt;/script&gt;
&lt;p&gt;In this post, I'm going to show you algorithms that solve the seemingly simple task of drawing a circle, and we'll do so with very strong constraints on the operations we're allowed to use. In the early days of video games, the late 70s and early 80s, the processors in home computers and game consoles were mostly 8-bit processors such as the &lt;a href="http://www.6502.org/users/obelisk/6502/instructions.html"&gt;6502&lt;/a&gt; and the &lt;a href="https://www.zilog.com/docs/z80/z80cpu_um.pdf"&gt;Z80&lt;/a&gt;. Those processors were not only slow by today's standards with frequencies around 1-2MHz and no parallel execution of any kind, they had very limited instruction sets, without multiplication and division operations, and with only support for integer numbers. That doesn't mean that multiplications were impossible, but just that they were very, very expensive. As a consequence, algorithms avoiding them were preferable.&lt;/p&gt;
&lt;p&gt;Operations that 8-bit processors were very good at running fast, because they can be implemented with few simple logic gates, include additions and bit shifting.&lt;/p&gt;
&lt;p&gt;The way mathematicians would describe circles is often with equations such as &lt;math&gt;&lt;mrow&gt;&lt;msup&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt;&lt;mo&gt;+&lt;/mo&gt;&lt;msup&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;msup&gt;&lt;mi&gt;r&lt;/mi&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt;&lt;mrow&gt;&lt;/mrow&gt;&lt;/mrow&gt;&lt;/math&gt; or &lt;math&gt;&lt;mo&gt;{&lt;/mo&gt;&lt;mtable columnalign="left"&gt;&lt;mtr&gt;&lt;mtd&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mi&gt;r&lt;/mi&gt;&lt;mi&gt;cos&lt;/mi&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/mtd&gt;&lt;/mtr&gt;&lt;mtr&gt;&lt;mtd&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mi&gt;r&lt;/mi&gt;&lt;mi&gt;sin&lt;/mi&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/mtd&gt;&lt;/mtr&gt;&lt;/mtable&gt;&lt;/math&gt;.&lt;/p&gt;
&lt;p&gt;Both of those involve multiplications, or worse, trigonometric function evaluation. So what are we to do?&lt;/p&gt;
&lt;p&gt;The first thing we can notice is that the first equation is quadratic, so everything in there, once differentiated, becomes linear, and as such, easy to compute using additions and multiplications by constants. Let's keep that differentiation idea but it's the second system of equations that I'm going to differentiate, to come up with the first algorithm:&lt;/p&gt;
&lt;p&gt;&lt;math&gt;&lt;mo&gt;{&lt;/mo&gt;&lt;mtable columnalign="left"&gt;&lt;mtr&gt;&lt;mtd&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mo&gt;-&lt;/mo&gt;&lt;mi&gt;r&lt;/mi&gt;&lt;mi&gt;sin&lt;/mi&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/mtd&gt;&lt;/mtr&gt;&lt;mtr&gt;&lt;mtd&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mi&gt;r&lt;/mi&gt;&lt;mi&gt;cos&lt;/mi&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/mtd&gt;&lt;/mtr&gt;&lt;/mtable&gt;&lt;/math&gt;&lt;/p&gt;
&lt;p&gt;We can then notice that we can spot the expressions for &lt;math&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;/math&gt; and &lt;math&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;/math&gt; in those differential equations and reformulate them as follows.&lt;/p&gt;
&lt;p&gt;&lt;math&gt;&lt;mo&gt;{&lt;/mo&gt;&lt;mtable columnalign="left"&gt;&lt;mtr&gt;&lt;mtd&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mo&gt;-&lt;/mo&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/mtd&gt;&lt;/mtr&gt;&lt;mtr&gt;&lt;mtd&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/mtd&gt;&lt;/mtr&gt;&lt;/mtable&gt;&lt;/math&gt;&lt;/p&gt;
&lt;p&gt;What that tells us is that when the angle &lt;math&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/math&gt; changes by an infinitesimally small amount &lt;math&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/math&gt;, &lt;math&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;/math&gt; changes by &lt;math&gt;&lt;mo&gt;-&lt;/mo&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/math&gt; and &lt;math&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;/math&gt; changes by &lt;math&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mo&gt;ⅆ&lt;/mo&gt;&lt;mi&gt;&amp;theta;&lt;/mi&gt;&lt;/math&gt;. This still contains a multiplication, but only by the constant amount we want to vary the angle between two steps of the rendering. If we choose that amount to be the inverse of a power of two &lt;math&gt;&lt;mfrac bevelled="true"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;msup&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;mi&gt;n&lt;mi&gt;&lt;/mi&gt;&lt;/mi&gt;&lt;/msup&gt;&lt;/mfrac&gt;&lt;/math&gt; so that the corresponding change in coordinate is always under one pixel, thus ensuring continuity, we can avoid the multiplication because multiplication by the inverse of a power of two is the same as shifting bits to the right by a number of bits that is that power: &lt;code&gt;x/2^n&lt;/code&gt; is the same as &lt;code&gt;x &amp;gt;&amp;gt; n&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We still have the problem of determining the value of &lt;math&gt;&lt;mi&gt;n&lt;/mi&gt;&lt;/math&gt;, but we only have to do it once per circle, so this is less of a hot path. It turns out, all you have to do is shift 1 left (which is the same as enumerating powers of two) until you run over &lt;math&gt;&lt;mi&gt;r&lt;/mi&gt;&lt;/math&gt;:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/013bb2910591f4eaa21943f8c526681a.js"&gt;&lt;/script&gt;
&lt;noscript&gt;
&lt;pre&gt;
let n = 0;
for (let twopown = 1; twopown &lt; r; n++, twopown &lt;&lt;= 1);
&lt;/pre&gt;
&lt;/noscript&gt;
&lt;p&gt;And this is it, we now have a working algorithm:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/a524655066d4e5967747f53ebca9af5c.js"&gt;&lt;/script&gt;
&lt;noscript&gt;
&lt;pre&gt;
// Now we can start from (r, 0) and apply the differential equations at each step
let x = r &lt;&lt; bdp, y = 0, t = 0;
while (x &gt;= y) { // We only need draw 1/8th of the circle, symmetries will do the rest
  const [screenx, screeny] = [x &gt;&gt; bdp, y &gt;&gt; bdp];
  drawPointAndSymmetries(ctx, xc, screenx, yc, screeny);
  // Side effect: it's trivial to derive a table of sine and cosine values
  // from this algorithm while we're here...
  sine[t] = y;
  cosine[t] = x;
  t++;
  // Apply the differential equations
  [x, y] = [x - (y &gt;&gt; n), y + (x &gt;&gt; n)];
}
&lt;/pre&gt;
&lt;/noscript&gt;
&lt;p&gt;The call to &lt;code&gt;drawPointAndSymmetries&lt;/code&gt; is just using the axial symmetries of a circle to only compute one eights of the circle:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/b4948553e6ff3861e7ff7dd34cbdd7a9.js"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;
function drawPointAndSymmetries(ctx, xc, screenx, yc, screeny) {
  // Draw the current pixel and all its easily computable symmetries
  ctx.fillRect(xc + screenx, yc + screeny, 1, 1);
  ctx.fillRect(xc - screenx, yc + screeny, 1, 1);
  ctx.fillRect(xc + screenx, yc - screeny, 1, 1);
  ctx.fillRect(xc - screenx, yc - screeny, 1, 1);
  ctx.fillRect(xc + screeny, yc + screenx, 1, 1);
  ctx.fillRect(xc - screeny, yc + screenx, 1, 1);
  ctx.fillRect(xc + screeny, yc - screenx, 1, 1);
  ctx.fillRect(xc - screeny, yc - screenx, 1, 1);
}
&lt;/pre&gt;&lt;/noscript&gt;
&lt;p&gt;If you're wondering about &lt;code&gt;bdp&lt;/code&gt;, this is the fixed point bit depth that we use to make decimal calculations using only integers. It's 8 in the sample below, meaning eight bits of precision under the decimal point.&lt;/p&gt;
&lt;p&gt;This works fine, but we can do better and faster.&lt;/p&gt;
&lt;p&gt;Imagine we wanted to walk the circle in the dark. If we could erect a wall around the circle, we could just walk straight ahead and whenever we hit the wall, take a lateral step away from it. This strategy produces a trajectory that is very close to the circle. It also works on any concave shape, not just circles.&lt;/p&gt;
&lt;p&gt;The wall in question is called a discriminating function. It's a function of the coordinates that evaluates as positive outside of the shape and as negative inside. It's called discriminating because by just evaluating it on a point, you can discriminate whether you are inside or outside.&lt;/p&gt;
&lt;p&gt;For a circle, it's easy to build a discriminating function from the circle's equation: &lt;math&gt;&lt;mrow&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mfenced open="(" separators="," close=")"&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;/mfenced&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;msup&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt;&lt;mo&gt;+&lt;/mo&gt;&lt;msup&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt;&lt;mo&gt;-&lt;/mo&gt;&lt;msup&gt;&lt;mi&gt;r&lt;/mi&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt;&lt;mrow&gt;&lt;/mrow&gt;&lt;/mrow&gt;&lt;/math&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Graph of the discriminating function for a circle of radius 2" src="https://aspblogs.blob.core.windows.net:443/media/bleroy/Posts/circles/Discriminating-function-circle.png" /&gt;&lt;/p&gt;
&lt;p&gt;It may seem like computing this function for every point is going to be challenging because of all those squarings. In this case again, &lt;em&gt;variations&lt;/em&gt; of the function from pixel to pixel are going to be sufficient if we know the value at any point.&lt;/p&gt;
&lt;p&gt;When we move one pixel to the right, here's how the function varies:&lt;/p&gt;
&lt;p&gt;&lt;math&gt;&lt;mrow&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mfenced open="(" separators="," close=")"&gt;&lt;mrow&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mo&gt;+&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mrow&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;/mfenced&gt;&lt;mo&gt;-&lt;/mo&gt;&lt;mrow&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mfenced open="(" separators="," close=")"&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;/mfenced&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mo&gt;+&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mrow&gt;&lt;/mrow&gt;&lt;/math&gt;&lt;/p&gt;
&lt;p&gt;This is of course very easy to compute: shift &lt;math&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;/math&gt; left and add one.&lt;/p&gt;
&lt;p&gt;Whenever the new value of the discriminating function goes positive, we need to make a side step, for which it is also easy to compute the discriminating function variation:&lt;/p&gt;
&lt;p&gt;&lt;math&gt;&lt;mrow&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mfenced open="(" separators="," close=")"&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mrow&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;mo&gt;-&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mrow&gt;&lt;/mfenced&gt;&lt;mo&gt;-&lt;/mo&gt;&lt;mrow&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mfenced open="(" separators="," close=")"&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;/mfenced&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;mo&gt;-&lt;/mo&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;/mrow&gt;&lt;/mrow&gt;&lt;/math&gt;&lt;/p&gt;
&lt;p&gt;Subtract left-shifted &lt;math&gt;&lt;mi&gt;y&lt;/mi&gt;&lt;/math&gt; from one.&lt;/p&gt;
&lt;p&gt;You may also notice that this second algorithm has no need for fixed-point decimal numbers, it can work on regular integer coordinates, which further simplifies it and makes it more efficeint.&lt;/p&gt;
&lt;p&gt;Here's the implementation:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/adfc0d0b685e1d9598e16afc5e1bbbde.js"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;
// Start with a value half a pixel inside the circle: f(0, r - 1/2) = 1/4 - r and 1/4 falls below precision.
let x = 0, y = r, f = -r;
drawPointAndSymmetries(ctx, xc, x, yc, y);
while (x &lt;= y) { // We only need draw 1/8th of the circle, symmetries will do the rest
    // Draw the current pixel and all its easily computable symmetries
    f += 1 + x &lt;&lt; 1;
    x++;
    drawPointAndSymmetries(ctx, xc, x, yc, y);
    if (f &gt; 0) {
        f += 1 - y &lt;&lt; 1;
        y--;
        drawPointAndSymmetries(ctx, xc, x, yc, y);
    }
}
&lt;/pre&gt;&lt;/noscript&gt;
&lt;p&gt;You can see both of those algorithms in action below:&lt;/p&gt;
&lt;p&gt;&lt;iframe width="820" height="800" src="https://bleroy.github.io/3d-junkyard/AddAndShift/index.html"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;The source code can be found here: &lt;a href="https://github.com/bleroy/3d-junkyard/tree/main/AddAndShift"&gt;https://github.com/bleroy/3d-junkyard/tree/main/AddAndShift&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;But of course, this is javascript running on a modern computer, and I sold this as a way to draw a circle on vintage 8-bit computers. Does it work on old computers? Yes, of course it does. Here's the algorithm implemented and running on an Atari 8-bit computer in 6502 assembly (what you see below is an actual emulator in your browser, hosted by the excellent &lt;a href="https://8bitworkshop.com"&gt;https://8bitworkshop.com&lt;/a&gt;; if you see the circle as a little oval, that's normal, vintage computers often have pixels that are not exactly square):&lt;/p&gt;
&lt;p&gt;&lt;iframe width="640" height="460" style="border: none;" src="https://8bitworkshop.com/v3.11.0/player.html?p=atari8-800&amp;amp;r=TFpHAAAgAAAAAaNpdXoxAQMFCQypKI3EAqkAjcUCqQaNxgKpWI3HAqnUjcgJTDACqaKNMQKpIo0vAtipII0AEqkKjYASogAYvYASaRSdgRK9ABJpAJ0BEujgZNDqCSr8EqkyjfsSSf9pAY36EiDroK78EorojvwSChhpARht%2BhIJzq36EjAa8Bis%2BxKYiIz7EgpJ%2FxhpAgUIFzit%2FBLN%2BxIwwupMnaCKSkpKjf8SiikHqr1too3%2BEr11oo39Ehi5gBJt%2FxKF0LkFAnuF0aIAodAN%2FhKB0AlR7QUFEekFBhH9CRFgrvwSGK37EmkyqCChBQKROKky7fsSCUUYrfwJT677EgkFCU%2F8EgUFBWD%2FDB8MHgwVcHAQSwAgCwweDBlBAKKAQCAQCAQCAQECBAgQIECABR%2F1DB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB8MHwwfDB4MHQwDAKAABACg"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;Here's the source code for this:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/78cd1b73243c52ed7a45057354eb5026.js"&gt;&lt;/script&gt;</description><pubDate>Sat, 30 Dec 2023 20:47:05 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/secrets-of-the-grey-beards-drawing-circles-with-additions-and-shifts</guid></item><item><title>Use explicit Lambdas with LINQ</title><link>https://weblogs.asp.net:443/bleroy/linq-lambdas</link><description>&lt;p&gt;Here's an interesting bug... What's wrong with this code?&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/d55d22a941dc10020cf7ab0fd966838d.js"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;var clones = source.Select(SourceType.Clone);&lt;/pre&gt;&lt;/noscript&gt;
&lt;p&gt;In principle, nothing. Your IDE might even encourage you to write this instead of the longer (but also more expressive):&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/cf91f8342af8c648443b2ea69c72373c.js"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;var clones = source.Select(item =&gt; SourceType.Clone(item));&lt;/pre&gt;&lt;/noscript&gt;
&lt;p&gt;Let me give you a couple of hints... First, the second version, the explicit one, works perfectly well, while the first one behaves very oddly in some contexts. Second, here's the signature for the Clone method:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/d981e0a6ee61bf1cfa82bbcfe3969606.js"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;public static SourceType Clone(SourceType source, int maxDepth = -1)&lt;/pre&gt;&lt;/noscript&gt;
&lt;p&gt;Here's the key:&amp;nbsp;&lt;a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=net-7.0"&gt;LINQ's select method&lt;/a&gt; can take basically two signatures for its argument function. The first one is a simple mapping that takes a single parameter. The second takes the source item as its first argument, but has a second argument that is the index of the current element being processed in the source enumeration.&lt;/p&gt;
&lt;p&gt;Now surely you can see how this causes a subtle bug in the first version of our code. Seeing that our method has an overload that takes two argument, the second being an integer, the compiler thinks our function needs the index as its second argument. Essentially, the compiler interprets our code as this:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/0e7c01bf426e0fa621a2baa11182cc20.js"&gt;&lt;/script&gt;
&lt;noscript&gt;&lt;pre&gt;var clones = source.Select((item, index) =&gt; SourceType.Clone(item, index));&lt;/pre&gt;&lt;/noscript&gt;
&lt;p&gt;As the code runs, our Clone method will get called with 0, 1, 2, 3, etc. as its max depth parameter, resulting, presumably, in very shallow, then deeper and deeper clones being made. Very strange behavior that will be extremely difficult to track down...&lt;/p&gt;
&lt;p&gt;For those reasons, here's my recommendation: just be explicit, use the second version. Never pass the raw method as the argument to Select (and other LINQ methods), explicitly write a Lambda instead.&lt;/p&gt;</description><pubDate>Wed, 30 Aug 2023 22:05:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/linq-lambdas</guid><category>C#</category><category>LINQ</category></item><item><title>A breaking change in .NET argument exception message formatting</title><link>https://weblogs.asp.net:443/bleroy/argument-exception-breaking-change</link><description>&lt;p&gt;A quick reference post about an interesting change in the way .NET formats argument exception messages. This tripped me up when debugging a test that was failing on .NET Core / 6.0 whereas it had been passing forever and still passes on .NET Framework / 4.7. The test was expecting a specific error message. Because .NET Core apparently has changed the format string used for argument exception messages, that expectation was broken.&lt;/p&gt;
&lt;p&gt;Technically a breaking change, but then again expecting a specific error message is usually not the best idea.&lt;/p&gt;
&lt;p&gt;Anyway, here's how .NET 4.7 formats the exception:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;img width="462" height="44" alt="" src="https://aspblogs.blob.core.windows.net:443/media/bleroy/Posts/argument-exception/netfx.png" /&gt;&lt;/p&gt;
&lt;p&gt;And here's how .NET 6.0 does:&lt;/p&gt;
&lt;p&gt;&lt;img width="328" height="36" alt="" src="https://aspblogs.blob.core.windows.net:443/media/bleroy/Posts/argument-exception/NetCore.png" /&gt;&lt;/p&gt;
&lt;p&gt;The fix for the test of course is to test for the presence of the message that was passed in when creating the exception as a substring of the exception's Message property, instead of expecting the whole formatted message.&lt;/p&gt;</description><pubDate>Wed, 01 Mar 2023 00:55:42 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/argument-exception-breaking-change</guid></item><item><title>3D before GPUs Part 1: Dungeon Master</title><link>https://weblogs.asp.net:443/bleroy/dungeon-master</link><description>&lt;p id="3d-before-gpus-part-1-dungeon-master"&gt;In this series, I'll reverse-engineer algorithms from video games dating back to that time when the CPU was all you had. Today, we're looking at &lt;a href="https://en.wikipedia.org/wiki/Dungeon_Master_(video_game)"&gt;Dungeon Master&lt;/a&gt;, a fantastic game by FTL that set the gold standard for RPGs for the years to follow. It looked amazing, and still does to this day. It changed everything.&lt;/p&gt;
&lt;p&gt;&lt;img src="https://aspblogs.blob.core.windows.net:443/media/bleroy/Posts/threedee/dm/DM.png" alt="Dungeon Master" style="max-width: 640px;" /&gt;&lt;/p&gt;
&lt;!--more--&gt;
&lt;p&gt;Eye of the Beholder and Ultima Underworld are examples of later games that owe almost everything to Dungeon Master.&lt;/p&gt;
&lt;p&gt;&lt;img src="https://aspblogs.blob.core.windows.net:443/media/bleroy/Posts/threedee/dm/EyeOfTheBeholder.png" alt="Eye of the Beholder" style="max-width: 640px;" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="https://aspblogs.blob.core.windows.net:443/media/bleroy/Posts/threedee/dm/UltimaUnderworld.jpg" alt="Ultima Underworld" style="max-width: 640px;" /&gt;&lt;/p&gt;
&lt;p&gt;Before Dungeon Master, dungeon crawlers existed of course, but were often limited to crude wireframe graphics.&lt;/p&gt;
&lt;p&gt;&lt;img src="https://aspblogs.blob.core.windows.net:443/media/bleroy/Posts/threedee/dm/Ultima.png" alt="Ultima" /&gt;&lt;/p&gt;
&lt;p&gt;The way Dungeon Master rendered the walls of its dungeons was by cleverly overlaying and clipping bitmaps for the floor, ceiling and walls. There were of course many other objects to compose, such as monsters, doors, fountains or scrolls, but for the purposes of this post, we'll limit ourselves to the corridors and leave the rest to your imagination.&lt;/p&gt;
&lt;p&gt;For this, we need only one tile for the background, ceiling and floor, that will be the background that we'll fall back to when no other object is in front:&lt;/p&gt;
&lt;p&gt;&lt;img src="https://bleroy.github.io/3d-junkyard/DungeonMaster/img/Background.png" alt="The background tile" /&gt;&lt;/p&gt;
&lt;p&gt;We also need three tiles for the front wall at the three distances where the wall is still visible: the dark corridors of Dungeon Master are dimly lit, and everything farther than 3 units conveniently fades into darkness...&lt;/p&gt;
&lt;p&gt;&lt;img src="https://bleroy.github.io/3d-junkyard/DungeonMaster/img/FrontNear.png" alt="Front wall, close by" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="https://bleroy.github.io/3d-junkyard/DungeonMaster/img/FrontFar.png" alt="Front wall, a little farther" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="https://bleroy.github.io/3d-junkyard/DungeonMaster/img/FrontFarther.png" alt="Front wall, as far as it gets" /&gt;&lt;/p&gt;
&lt;p&gt;Also note that these wall textures don't need to be the full width of the screen, they just need to tile, so repeating the texture appears seamless.&lt;/p&gt;
&lt;p&gt;Then we have one tile for the left wall and one tile for the right wall, that we'll clip as needed:&lt;/p&gt;
&lt;p&gt;&lt;img src="https://bleroy.github.io/3d-junkyard/DungeonMaster/img/WallLeft.png" alt="Left wall tile" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="https://bleroy.github.io/3d-junkyard/DungeonMaster/img/WallRight.png" alt="Right wall tile" /&gt;&lt;/p&gt;
&lt;p&gt;And finally we need two tiles for the second row of walls on the left and right that are sometimes barely visible in the distance:&lt;/p&gt;
&lt;p&gt;&lt;img src="https://bleroy.github.io/3d-junkyard/DungeonMaster/img/WallFarLeft.png" alt="Left faraway wall tile" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="https://bleroy.github.io/3d-junkyard/DungeonMaster/img/WallFarRight.png" alt="Right faraway wall tile" /&gt;&lt;/p&gt;
&lt;p&gt;Here's a drawing of what those panes correspond to, when viewed from above:&lt;/p&gt;
&lt;p&gt;&lt;img src="https://aspblogs.blob.core.windows.net:443/media/bleroy/Posts/threedee/dm/DM_overhead.png" alt="The field of view from above" /&gt;&lt;/p&gt;
&lt;p&gt;The HTML for the whole setup is extremely simple:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/c4f77aca4659453fd8c21321e18c1930.js"&gt;&lt;/script&gt;
&lt;p&gt;Each potentially visible pane of wall is represented by a div with classes enabling their precise targeting by CSS. The divs are ordered from back to front so we don't have to worry about depth and closer walls naturally occlude the ones behind them.&lt;/p&gt;
&lt;p&gt;CSS is then used to dimension, position, texture and clip each pane. Here's for example the style for the middle-left wall:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/83bc15ed195c078e50c67a78e988957b.js"&gt;&lt;/script&gt;
&lt;p&gt;JavaScript is used to make panes visible or hidden based on the map data for the level:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/a826e3aea5f69956f5a674addeff5315.js"&gt;&lt;/script&gt;
&lt;p&gt;We first peek at the map locations in view of the party, then set the visibility of the corresponding wall panes.&lt;/p&gt;
&lt;p&gt;There's one last trick that Dungeon Master uses to make its levels feel more real at a very low cost: every time the party moves, all textures are flipped horizontally to their mirror image. This is important because it gives the illusion that something changed without costing anything since the images stored in memory are exactly the same, just rendered flipped. The textures have actually been designed so that what you see one square away looks like the mirror image of what's immediately around you. So flipping the textures gives a semi-realistic illusion of movement despite the fact that everything moves square by square rather than progressively and smoothly.&lt;/p&gt;
&lt;p&gt;In my reverse-engineered web version, I was able to reproduce this very easily by toggling an additional CSS class, "alternate", on the parent viewport element, every time the party moves or rotates:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/3cfc8b29e66b045cb513eccfbe1113cb.js"&gt;&lt;/script&gt;
&lt;p&gt;The CSS for the alternate viewport just applies a transform that applies a horizontal scale of "-1". Tile elements have a reversed version that adjusts the clipping of the texture if necessary:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/683f7ad80a5a7907efdc35f4c68088ef.js"&gt;&lt;/script&gt;
&lt;p&gt;That's pretty much all you need to reproduce the rendering of Dungeon Master walls and get a result that is very close to the original.&lt;/p&gt;
&lt;p&gt;In the end, Dungeon Master's rendering of its levels is about as simple and low-cost as it gets, but still manages to create an immersive and great-looking environment.&lt;/p&gt;
&lt;p&gt;Here's the final result, that you can use from your browser, right here (the level is that Hall of Champions, the first level of the game):&lt;/p&gt;
&lt;p&gt;&lt;iframe width="660" height="290" style="border: 0;" src="https://bleroy.github.io/3d-junkyard/DungeonMaster/default.html"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;Go ahead, click on the arrows and play, it really works from this post!&lt;/p&gt;
&lt;p&gt;If you want to see some gameplay from the original, here's a video I recorded a few weeks ago where I go through the first couple of levels of the game, and proceed to die a horrible death:&lt;/p&gt;
&lt;p&gt;&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/9yL8xyJ1rdE" title="YouTube video player" frameborder="0" allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="allowfullscreen"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;Like and subscribe!&lt;/p&gt;
&lt;p&gt;In the next post, I'll look at &lt;a href="https://en.wikipedia.org/wiki/Rescue_on_Fractalus!"&gt;Rescue on Fractalus&lt;/a&gt;, the first game from LucasFilm that introduced a very innovative fractal rendering technique for mountain ranges.&lt;/p&gt;
&lt;p&gt;The full code for this demo is on GitHub:&amp;nbsp;&lt;a href="https://github.com/bleroy/3d-junkyard/tree/main/DungeonMaster"&gt;3d-junkyard/DungeonMaster at main &amp;middot; bleroy/3d-junkyard (github.com)&lt;/a&gt;&lt;/p&gt;</description><pubDate>Thu, 29 Jul 2021 01:49:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/dungeon-master</guid><category>Gaming</category><category>JavaScript</category></item><item><title>LunrCore, a lightweight search library for .NET</title><link>https://weblogs.asp.net:443/bleroy/lunrcore</link><description>&lt;p&gt;&lt;img alt="" src="https://aspblogs.blob.core.windows.net:443/media/bleroy/Posts/lunr/LunrCore.png" style="margin-left: 8px;" width="256" height="256" align="right" /&gt; I'm pretty much convinced almost all applications need search. No matter what you're building, you'll likely handle data, and no matter how well you organize it, a good text search is often the fastest way for your users to find what they're looking for. As such, search should be a commodity, a feature that should be as easy as possible to integrate. I'm so convinced of that in fact that my day job is on &lt;a href="https://azure.microsoft.com/en-us/services/search/"&gt;Azure Cognitive Search&lt;/a&gt;, a Microsoft product that provides search as a service and makes indexing smart by adding a customizable pipeline of AI and machine learning enrichments.&lt;/p&gt;
&lt;p&gt;A month ago, I saw this tweet:&lt;/p&gt;
&lt;blockquote class="twitter-tweet"&gt;
&lt;p dir="ltr" lang="en"&gt;The .NET library ecosystem is sometimes so unequipped. Every 5 years, I'm looking for a .NET library that could build a search index (inverted index, with stems, fuzzy search...etc.) that I could plug into a JS frontend library (e.g lunr.js), and it's still the same no lib's land&lt;/p&gt;
&amp;mdash; Alexandre Mutel (@xoofx) &lt;a href="https://twitter.com/xoofx/status/1275878129786109954?ref_src=twsrc%5Etfw"&gt;June 24, 2020&lt;/a&gt;&lt;/blockquote&gt;
&lt;script src="https://platform.twitter.com/widgets.js"&gt;&lt;/script&gt;
&lt;p&gt;Being a user of&amp;nbsp;&lt;a href="https://lunrjs.com/"&gt;lunr.js&lt;/a&gt; myself (I used it as the search engine in my Node CMS project, &lt;a href="http://decentcms.org/"&gt;Decent CMS&lt;/a&gt;), I agreed totally, and felt I had to do something. Of course, .NET has&amp;nbsp;&lt;a href="https://lucenenet.apache.org/"&gt;Lucene.NET&lt;/a&gt;, a port of Java's &lt;a href="https://lucene.apache.org/"&gt;Lucene&lt;/a&gt;, and that's a fantastic library. We've been using it forever in &lt;a href="http://www.orchardcore.net/"&gt;Orchard&lt;/a&gt;, and it's a high-performance and mature project. It is however not that simple and it can in some situations lack flexibility. It's what your choice should be if you're building anything at scale, but if all you're trying to do is to plug search into your app with minimal headache and a very gentle learning curve, now you have LunrCore as an option...&lt;/p&gt;
&lt;p&gt;LunrCore is a direct port of &lt;a href="https://lunrjs.com/"&gt;lunr.js&lt;/a&gt;. If you don't know it,&amp;nbsp;&lt;a href="https://lunrjs.com/"&gt;lunr.js&lt;/a&gt; is a very nice JavaScript library that implements a simple search engine with a focus on simplicity. I really love it because it hits that sweet spot of commodity that I was talking about at the beginning of this post. Easy to integrate, easy to use, and still has almost all the features you'd expect:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Index anything: just feed it a dictionary of strings to objects&lt;/li&gt;
&lt;li&gt;Stemmers&lt;/li&gt;
&lt;li&gt;Fuzzy search with edit distance and wildcards&lt;/li&gt;
&lt;li&gt;Boost&lt;/li&gt;
&lt;li&gt;Term presence or absence&lt;/li&gt;
&lt;li&gt;Scoring&lt;/li&gt;
&lt;li&gt;Stop words&lt;/li&gt;
&lt;li&gt;Search over fields or the entire document&lt;/li&gt;
&lt;li&gt;Pluggable indexing and search pipelines&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Creating an index is as simple as this:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/e65b2c33ec9f132dcb5a4b61df243ad1.js"&gt;&lt;/script&gt;
&lt;p&gt;Then, searching it can be done through expressive search query strings or through an object model of combinable clauses.&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/12c176b4dfb45d70a49ca67f6171b1ee.js"&gt;&lt;/script&gt;
&lt;p&gt;Being a port of an existing JavaScript library, we also have an additional trick up our sleeves: an index can be prepared on the server, then sent down into the browser for super-fast client-side searches. The JSON that LunrCore produces when serializing an index can be consumed by the original lunr.js library. I think that is pretty cool if I may say so myself.&lt;/p&gt;
&lt;p&gt;The library is of course open source under the MIT license, which means everybody should be able to use it to build commercial and non-commercial applications with no strings attached. It has no runtime dependency beyond the SDK, BCL AsyncInterfaces and System.Text.Json, making it even more of a no-brainer to integrate anywhere. I'd love to hear what you think and what you built with it, so don't hesitate to drop me a note (or even contribute something &lt;a href="https://github.com/bleroy/lunr-core"&gt;on GitHub&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Package: &lt;a href="https://www.nuget.org/packages/LunrCore"&gt;https://www.nuget.org/packages/LunrCore&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Repository: &lt;a href="https://github.com/bleroy/lunr-core"&gt;https://github.com/bleroy/lunr-core&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The original JavaScript library: &lt;a href="https://lunrjs.com/guides/getting_started.html"&gt;https://lunrjs.com/guides/getting_started.html&lt;/a&gt;&lt;/p&gt;</description><pubDate>Sun, 26 Jul 2020 09:02:08 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/lunrcore</guid></item><item><title>Why I dislike tuple return types</title><link>https://weblogs.asp.net:443/bleroy/why-i-dislike-tuple-return-types</link><description>&lt;p&gt;Tuples are great additions to C#. They're simple &lt;span style="text-decoration: line-through;"&gt;im&lt;/span&gt;mutable structures made of a small number of members organized in a specific order. For example, a point on a plane could be represented as a pair of X and Y coordinates, or a person's name could be represented as a title, first, middle and last names. If the types are that simple, and have no custom logic associated with them, using a tuple looks like a lightweight and simple implementation that requires a lot less effort than a simple class or struct. Dynamic and functional languages have long enjoyed tuples, of course, but I like how the C# implementation manages to stay true to the core tenets of the language, in particular type safety.&lt;/p&gt;
&lt;p&gt;However, I personally cringe a little every time I see a public API returning a tuple. I really, really dislike them as return types. Let me explain why.&lt;/p&gt;
&lt;p&gt;As a user of a method, you will use what you know of the return type, and use the data contained therein according to your needs. There's a whole category of backwards-compatible changes to a class, such as adding a new member, that are trivial with classes and require no change or even recompilation of client code, that become very difficult with tuples.&lt;/p&gt;
&lt;p&gt;This comes from the fact that with tuples, you need to copy the very definition of the type everywhere you use it, whereas with a class, you only use its name as a reference to the type. Almost no refactoring is possible with tuples without finding all of the code in the world that uses your tuple return type, and modifying it as well. This is at best impractical. Tooling can't even help you much beyond CTRL+SHIFT+F and finding all references to the method. I know from experience that tracking down those types in a large codebase can be far from trivial.&lt;/p&gt;
&lt;p&gt;It's actually less effort in the end to write a simple class. I have a lot of hope for &lt;a href="https://github.com/dotnet/csharplang/blob/master/proposals/records.md"&gt;records&lt;/a&gt; (&lt;a href="https://github.com/dotnet/csharplang/issues/39"&gt;vote&lt;/a&gt;) as a better option to use wherever you need lightweight types, but in the meantime, I prefer in most cases to write a simple class rather than to return a tuple.&lt;/p&gt;
&lt;p&gt;There's also the fact that a named type can in most cases better convey the semantics and intentions of your code than a tuple, which is pure structure. Finally, the temptation to write Cthulhuesque abominations such as &lt;code&gt;IEnumerable&amp;lt;(string, IDictionary&amp;lt;string, (string, string)&amp;gt;)&amp;gt;&lt;/code&gt; exists. When you have to put the name of your method on a different line than its return type, you know you've gone too far.&lt;/p&gt;
&lt;p&gt;So at this point, you may ask, what do I still think tuples are good for? That is a fair question... I have several answers to that.&lt;/p&gt;
&lt;p&gt;First, I don't think tuples should &lt;em&gt;always&lt;/em&gt; be avoided as return types. When the semantics of a method are to manipulate or produce a tuple, they are more than acceptable, in fact nothing else makes sense:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/2f2751df1b0279a6d529288edf3db083.js"&gt;&lt;/script&gt;
&lt;p&gt;I think tuples are also fantastic at simplifying code that produces and processes intermediary results. I particularly like to use them as return types of Lambdas in LINQ expressions:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/c49022353e2017007c1fd8927445d8cd.js"&gt;&lt;/script&gt;
&lt;script src="https://gist.github.com/bleroy/f27ef03bc1a1cca6119584d643fe682b.js"&gt;&lt;/script&gt;
&lt;p&gt;This totally non-optimized, allocation-happy and non parameter validating piece of code conveys the idea: it uses a simple tuple as an intermediary structure between the &lt;code&gt;Zip&lt;/code&gt; call and the &lt;code&gt;SelectMany&lt;/code&gt;. The tuple brings real value here, as doing the same thing without it would be considerably more tedious and less expressive (let's put aside the existence of a &lt;code&gt;Pair&lt;/code&gt; class that could be used in this simple case, the general point remains). The proximity of the code that produces the tuple to the code that consumes it, associated with a tight scope means none of the objections I have to using tuples as public API return types apply here. It's pure goodness.&lt;/p&gt;
&lt;p&gt;Another very compelling feature of C# tuples is deconstruction, and I wish we also had it for anonymous objects &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment"&gt;like JavaScript does&lt;/a&gt;. Deconstruction allows you to directly assign values inside of a tuple that only lives as part of that assignment. It is a very convenient way to access and use the components in the tuple:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/e08694e5f9bd94db9219acdc76f31561.js"&gt;&lt;/script&gt;
&lt;p&gt;This is really lovely, and the good news is that tuples are not the only types this works on: you can add type-safe deconstructing capabilities to your own classes by implementing something like this:&lt;/p&gt;
&lt;script src="https://gist.github.com/bleroy/cb732fbb6e4cc1bda6cd6b4d5b18856a.js"&gt;&lt;/script&gt;
&lt;p&gt;The &lt;code&gt;GetMiddlePoint&lt;/code&gt; deconstruction sample above will work exactly the same whether the method returns a &lt;code&gt;(double, double)&lt;/code&gt; tuple or an instance of a &lt;code&gt;Point&lt;/code&gt; class that implements a &lt;code&gt;Deconstruct&lt;/code&gt; method. This is a great way to refactor a tuple-returning method to return an instance of a class instead, while keeping client code untouched (recompiling may be necessary). To me this is the best of both worlds: a deconstruct-aware class remains easy to refactor cleanly, and can still present the greatly expressive deconstruction capabilities of a tuple.&lt;/p&gt;</description><pubDate>Sun, 16 Feb 2020 23:53:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/why-i-dislike-tuple-return-types</guid><category>C#</category><category>Opinion</category></item><item><title>The case of the defined undefined property</title><link>https://weblogs.asp.net:443/bleroy/the-case-of-the-defined-undefined-property</link><description>&lt;p&gt;&lt;a href="https://www.flickr.com/photos/thefangmonster/1123118356"&gt;&lt;img width="240" height="180" title="Ant Farm, by Noah Sussman, included under CC  BY 2.0" align="left" style="margin: 0px 10px 10px 0px; border: 0px currentcolor; border-image: none; float: left; display: inline; background-image: none;" alt="Ant Farm, by Noah Sussman, included under CC  BY 2.0" src="https://aspblogs.blob.core.windows.net/media/bleroy/Open-Live-Writer/0793bf7b84d3_B688/1123118356_263a5abbb8_z_ea307400-76e1-4665-a464-7ef64217995b.jpg" border="0"&gt;&lt;/a&gt;I like JavaScript, for some reason, I really do, and I still write and maintain a few &lt;a href="https://github.com/DecentCMS/DecentCMS"&gt;open source JavaScript&lt;/a&gt; &lt;a href="https://github.com/bleroy/6502"&gt;projects&lt;/a&gt;. It’s undeniable that it has &lt;a href="https://amzn.to/2V7BRt7"&gt;bad parts&lt;/a&gt; though, that remain today, even in strict &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_Next_support_in_Mozilla"&gt;ES2017&lt;/a&gt;. In this post, I want to show you one that builds an interesting bug farm.&lt;/p&gt;&lt;p&gt;Being a dynamic language, JavaScript allows you to add properties to pretty much any object, on the fly. This can be done using the dot notation (&lt;font face="Courier New"&gt;a.b = 1&lt;/font&gt;), or the indexer notation (&lt;font face="Courier New"&gt;a['b'] = 1&lt;/font&gt;). The indexer notation is more verbose, but it also allows for more flexible scenarios. For example, you can use the value of a variable or function parameter to set a value on an object:&lt;/p&gt;&lt;p&gt;&lt;script src="https://gist.github.com/bleroy/9bbc15a274a728db7829243144d96a49.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;That looks innocuous, but what would happen if we put JavaScript’s careless tendency to convert anything on-the-fly into the mix? What would happen if we used an undefined variable as the index? Let’s find out.&lt;/p&gt;&lt;p&gt;&lt;script src="https://gist.github.com/bleroy/7b77305aa7b143ea27d03179f3c4ff80.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;Ouch! That looks bad. So what happened here? Well, the value of b here is undefined, but JavaScript needs a number or a string in this context, so it converts your undefined value to the string ‘undefined’ and then uses that as the index value. When we try to retrieve the value of the property indexed by c, the same conversion happens, and we retrieve the same value.&lt;/p&gt;&lt;p&gt;Seems far-fetched? Check this one out:&lt;/p&gt;&lt;p&gt;&lt;script src="https://gist.github.com/bleroy/bdbc7c371c2e42e5d313641f4358f5fd.js"&gt;&lt;/script&gt;&lt;/p&gt;&lt;p&gt;Notice the spelling on lines 15 and 16. This is a much more likely case where a typo in the program goes undetected and caused unexpected results. The consequences can be very serious, depending on the context. In normal conditions, everything seems to work fine. You set a property, retrieve it, and the value is the one you set. This is an illusion however, because you’re creating that bucket of undefined properties that all leak one another’s value. You might set a value for one user, for example, in some cache in a Node application, only to have it propagate to another user. That is bad™.&lt;/p&gt;&lt;p&gt;Any bug is bad, but a bug that can go undetected until it causes mayhem is worse. So what can you do to detect something like this? Well, maybe JavaScript’s strict mode should error on implicit conversion of undefined to string: I can’t think of a situation where you would intentionally do that, and even if there’s one, being explicit about it would be better. Since it doesn’t, however, one thing we can do is build a little trap.&lt;/p&gt;&lt;p&gt;Here’s a bookmarklet that you can bookmark to set-up the trap (keep in mind your browser will likely not let this run just anywhere, like on https, but you can always run the same code in the F12 console):&lt;/p&gt;&lt;p&gt;&lt;a href="javascript:{Object.defineProperty(Object.prototype, undefined, {set: function(v) {debugger;}})};void(0);"&gt;undefined trap&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Here's the source code for it:&lt;/p&gt;&lt;p&gt;&lt;script src="https://gist.github.com/bleroy/91122ad41180d0dfe46dabb77ee7dc94.js"&gt;&lt;/script&gt;&lt;/p&gt;&lt;p&gt;Once you’ve executed the bookmarklet by clicking on the bookmark, the active web page in your browser is now instrumented so that if any object property is set with undefined (or the string ‘undefined’), the browser will break execution into the debugger. Go up one level in the stack trace, and you’ll see the responsible code. It may not be the ultimate answer to this problem, but it may help find a few hidden and nasty issues in your client-side code.&lt;/p&gt;&lt;p&gt;&lt;img width="815" height="372" title="The debugger breaking on undefined property setting" style="margin: 8px auto; border: 0px currentcolor; border-image: none; float: none; display: block; background-image: none;" alt="The debugger breaking on undefined property setting" src="https://aspblogs.blob.core.windows.net/media/bleroy/Open-Live-Writer/0793bf7b84d3_B688/image_53230d34-8eb3-419f-89be-21bbbddfffcf.png" border="0"&gt;&lt;/p&gt;</description><pubDate>Wed, 26 Dec 2018 16:00:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/the-case-of-the-defined-undefined-property</guid><category>JavaScript</category><category>Dynamic languages</category></item><item><title>Quantum computing and topological qubits explained clearly</title><link>https://weblogs.asp.net:443/bleroy/quantum-computing-and-topological-qubits-explained-clearly</link><description>&lt;p&gt;
&lt;script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/latest.js?config=MML_CHTML"&gt;&lt;/script&gt;
Don't let yourself be intimidated by all the quantum jargon. The bases of quantum computing are not that complicated, and I can explain them to anyone who understands programming, &lt;a href="https://en.wikipedia.org/wiki/Logic_gate"&gt;classical logic gates&lt;/a&gt;, &lt;a href="https://www.khanacademy.org/math/algebra2/introduction-to-complex-numbers-algebra-2/the-complex-numbers-algebra-2/v/complex-number-intro"&gt;the bare minimum about complex numbers&lt;/a&gt; and &lt;a href="https://www.khanacademy.org/math/linear-algebra"&gt;linear algebra&lt;/a&gt;&amp;hellip; I'll do so in the light of &lt;a href="https://gizmodo.com/how-will-microsofts-wild-electron-splitting-topological-1824142429"&gt;Microsoft's recent announcement of a new discovery&lt;/a&gt; that could bring us much more stable quantum computers.&lt;/p&gt;
&lt;p&gt;But first, a &lt;strong&gt;disclaimer&lt;/strong&gt;: I do work at Microsoft, but I don't work on the quantum computing team. I'm just an enthusiast developer who happens to be trained in quantum mechanics.&lt;/p&gt;
&lt;h3&gt;What did Microsoft just announce?&lt;/h3&gt;
&lt;p&gt;Microsoft's quantum computing group &lt;a href="https://www.nature.com/articles/nature26142"&gt;announced in Nature they had observed &amp;ldquo;quantized Majorana conductance&amp;rdquo;&lt;/a&gt;. Unless you're well-versed in quantum mechanics, I don't recommend you check it out, as even the abstract is quite technical. Let me explain what it's essentially saying.&lt;/p&gt;
&lt;p&gt;There's a type of particle called a &amp;ldquo;&lt;a href="https://en.wikipedia.org/wiki/Majorana_fermion"&gt;Majorana fermion&lt;/a&gt;&amp;rdquo; (after &lt;a href="https://en.wikipedia.org/wiki/Ettore_Majorana"&gt;Ettore Majorana&lt;/a&gt;, who predicted their existence in 1937) that is its own anti-particle. Don't worry if you don't know exactly what that entails, that's not the important part. What's important is that specially prepared pairs of these particles can exhibit a very interesting property: it is possible to entangle the states of those particles, in the same way that you'd braid two pieces of string together.&lt;/p&gt;
&lt;p&gt;&lt;img title="Topological states" alt="Topological states" src="https://aspblogs.blob.core.windows.net/media/bleroy/Open-Live-Writer/3de2e81cff69_92BE/Topology_3.png" width="240" height="115" /&gt;&lt;/p&gt;
&lt;p&gt;Imagine two rubber bands attached at both of their ends to some common support that cannot move. The bands may for example be parallel to each other. That's one state. Now exchange one of the extremities of each rubber band. That's another state. Notice that even though the rubber bands can be deformed, there is no way to go from one state to the other, except by detaching the extremities and reattaching them. The bands will continue to have, in one case an even numbers of overlaps, and in the other an odd number of overlaps. This sort of property that can resist continuous deformation of the system is the subject of a branch of mathematics called topology (of which a whole sub branch is the study of braids). Pairs of Majorana fermions, if properly prepared, can exhibit such properties.&lt;/p&gt;
&lt;p&gt;Majorana fermions were theoretical until recent years. We think neutrinos (a very elusive type of particle involved in radioactivity) may be Majorana fermions, but we're not sure yet. Last Summer, &lt;a href="https://phys.org/news/2017-07-evidence-majorana-fermion-particle-antiparticle.html"&gt;the first smoking gun of quasi-particles behaving like Majorana fermions has been announced by a group of scientists from Stanford&lt;/a&gt;. Quasi-particles are configurations of quantum fields in a material that behave like elementary particles, but aren't. They are typically found in two-dimensional materials like the contact surface between two materials, or single-dimensional materials like a wire.&lt;/p&gt;
&lt;p&gt;What the Microsoft quantum computing group announced this first week of April 2018 is that they have strong and consistent evidence for the presence of Majorana quasi-particles in nanowires. In simpler words, they have a device with the elusive Majoranas in it.&lt;/p&gt;
&lt;h3&gt;Why is it important?&lt;/h3&gt;
&lt;p&gt;Being immune to deformations is a very interesting property if you want to build a quantum computer. Quantum states tend to be confined to small scales and low temperatures, because interaction with large and warm systems will destroy them. Even a small perturbation from the environment can have catastrophic effects on the &amp;ldquo;quantumness&amp;rdquo; of the system, which is precisely what we're interested in with quantum computing. You can deal with it in a few ways: you can keep the system small (but that limits how much you can achieve), you can add redundancy to the system (but that makes it more difficult to scale the system up), or you can find more stable quantum systems (that's the direction the Microsoft team has chosen to take).&lt;/p&gt;
&lt;p&gt;Topological quantum states can still be destroyed by the environment, but there are ways to mitigate the problem that other sorts of quantum states don't have access to. Typically, the only thing that can destroy a topologically entangled pair of Majoranas, is the interaction with another pair in a state that can collide with it. This does happen, because in quantum mechanics, such pairs spontaneously pop into existence all the time. You can make that very unlikely however, with a simple trick: move both halves of the pair apart as much as you can. The particles will remain entangled (so their state remains unchanged), but for another pair to be able to destroy the state, it would have to be similarly stretched across space. This is considerably less likely than if the pair was spatially close together.&lt;/p&gt;
&lt;p&gt;The Microsoft results, the implementation of Majorana states, are a very important step on the path of stable, reliable, and scalable quantum computing. This is why it matters.&lt;/p&gt;
&lt;p&gt;But let's take a step back, and try to understand what quantum computing is, and why we want it.&lt;/p&gt;
&lt;h3&gt;A quick intro to quantum mechanics&lt;/h3&gt;
&lt;p&gt;I should probably stress out before I go any further that while I'll teach you rudiments of quantum mechanics, this is not going to give you a deep understanding of it. It will however give you an understanding of the mechanisms at work in quantum computing. In other words, you won't necessarily understand Schr&amp;ouml;dinger's cat much better, but you'll be able to understand and use basic quantum algorithms.&lt;/p&gt;
&lt;h4&gt;Quantum states&lt;/h4&gt;
&lt;p&gt;In any text about quantum mechanics, you'll read a lot about &amp;ldquo;quantum states&amp;rdquo;. I've already used the term a lot in this post without properly defining it. A state is the condition a system is in. For example, a bit can have one of two states: 0 and 1. A byte's state can be any integer between 0 and 255. You could also say that a byte's state is described by the states of each of its eight constituent bits. Now that's interesting, because those eight bits can be seen as independent sub-states. They are &lt;em&gt;orthogonal&lt;/em&gt;. You could describe a byte as a point in an eight-dimensional space where each dimension is one of the bits, and where the coordinates can be 0 or 1. When you think about it, any classical physical system can be described with a set of coordinates over elementary, orthogonal states.&lt;/p&gt;
&lt;p&gt;For example, the state of a ball may be described by its position (three coordinates), and its velocity (three coordinates again).&lt;/p&gt;
&lt;p&gt;Quantum states are pretty much the same, with an interesting twist&amp;hellip; A quantum state is also described with a set of coordinates, but in a more abstract space than what we've considered so far, and with complex coordinates.&lt;/p&gt;
&lt;p&gt;Now hold it right there&amp;hellip; Complex numbers? Why? How can complex numbers appear in nature? I can only see real numbers around. Well, in our classical perception of the world, yes, only real numbers ever show up. If you measure the width of your desk, you will never, ever measure &lt;math&gt;&lt;mfenced&gt;&lt;mrow&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;mo&gt;+&lt;/mo&gt;&lt;mn&gt;3i&lt;/mn&gt;&lt;/mrow&gt;&lt;/mfenced&gt;&lt;/math&gt; meters. In the quantum world, however, complex numbers are the norm. Complex numbers are also, in many ways, easier to manipulate and more &amp;ldquo;natural&amp;rdquo; than real numbers. All second degree complex equations have solutions, for instance, whereas real ones don't (&lt;math&gt;&lt;msup&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt;&lt;mo&gt;+&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/math&gt; for example).&lt;/p&gt;
&lt;p&gt;A good way to think about complex numbers in physics is to imagine them as a real amplitude with a &lt;em&gt;phase&lt;/em&gt;, rather than a combination of real and imaginary parts. The phase is an angle between 0 and &lt;math&gt;&lt;mn&gt;2&amp;pi;&lt;/mn&gt;&lt;/math&gt; (360&amp;deg; in radians). Positive numbers have a 0 phase, negative numbers have a &lt;math&gt;&lt;mn&gt;&amp;pi;&lt;/mn&gt;&lt;/math&gt; phase, &lt;em&gt;i&lt;/em&gt; has a &lt;math&gt;&lt;mn&gt;&amp;pi;&lt;/mn&gt;&lt;mo&gt;/&lt;/mo&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/math&gt; phase, and all other values are possible. When you multiply two numbers, the amplitudes get multiplied, and the phases get added (modulo &lt;math&gt;&lt;mn&gt;2&amp;pi;&lt;/mn&gt;&lt;/math&gt;). When you add two numbers, you can imagine them as being drawn one at the end of the other.&lt;/p&gt;
&lt;p&gt;&lt;img title="Adding and multiplying complex numbers" alt="Adding and multiplying complex numbers" src="https://aspblogs.blob.core.windows.net/media/bleroy/Open-Live-Writer/3de2e81cff69_92BE/Complex_02b3618f-05f3-4a02-b32b-cae0bf231024.png" width="581" height="480" /&gt;&lt;/p&gt;
&lt;p&gt;Depending on how the phases align or not, adding complex numbers may result in constructive or destructive interference.&lt;/p&gt;
&lt;p&gt;&lt;img title="Constructive and destructive interference" alt="Constructive and destructive interference" src="https://aspblogs.blob.core.windows.net/media/bleroy/Open-Live-Writer/3de2e81cff69_92BE/Interference_c96f1720-9233-4e4e-8645-764e75f71079.png" width="864" height="227" /&gt;&lt;/p&gt;
&lt;p&gt;This ability for out of phase states to interfere, much like waves do, is key to quantum weirdness. Let's look at the specifics.&lt;/p&gt;
&lt;p&gt;Let's get back to our classical bit and try to understand what would be a quantum equivalent, a &amp;ldquo;qubit&amp;rdquo;. To build this, we start from two orthogonal states (that's the first difference with the classical bit where 0 and 1 are not orthogonal). We'll arbitrarily label these states &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; and &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;. This is just a weird physicist's notation, labelling two states. There is no numerical value associated with them, they are just equivalents of the zero and one states of a classical bit.&lt;/p&gt;
&lt;p&gt;The state of the qubit can be described by complex coordinates along those two orthogonal states:&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mi&gt;q&lt;/mi&gt;&lt;/mfenced&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mi&gt;a&lt;/mi&gt;&lt;mo&gt;&amp;middot;&lt;/mo&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mi&gt;b&lt;/mi&gt;&lt;mo&gt;&amp;middot;&lt;/mo&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;So far, we've just thrown some definitions, without explaining where they're coming from, what they represent, or what they mean. &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; and &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; may be any possible pair of orthogonal values that we may &lt;em&gt;measure&lt;/em&gt; for the same quantity. For example, they may represent the spin of an electron being up or down, or they may be the untangled and tangled states of the braid we were talking about earlier. The calculations will be the same no matter what the physical substrate actually is. This is good: we wouldn't want our &lt;a href="https://docs.microsoft.com/en-us/quantum/quantum-qr-intro?view=qsharp-preview"&gt;Q#&lt;/a&gt; code to have to look different whether we run it on a &lt;a href="http://meetings.aps.org/Meeting/MAR18/Session/A33.1"&gt;Google qubit&lt;/a&gt;, or on a Microsoft Majorana topological qubit.&lt;/p&gt;
&lt;p&gt;Our qubit already is a superset of a classical bit: &lt;code&gt;{a: 1, b: 0}&lt;/code&gt; and &lt;code&gt;{a: 0, b: 1}&lt;/code&gt; correspond to classical bit values 0 and 1. We do have however other possible states: other complex values for a and b, which physicists call superpositions. There is just one constraint on these coordinates, and to understand it, we'll introduce some physical meaning with what happens when we measure a quantum state.&lt;/p&gt;
&lt;h4&gt;Measurement&lt;/h4&gt;
&lt;p&gt;In order to extract information from the system, we need to measure it. Measuring has the effect of collapsing the state of the system along one, and one only, of the possible classical states, &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; and &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;. The probability of getting one or the other is the square of the amplitude of the state's component along it (if the states are &lt;em&gt;normalized&lt;/em&gt;, more on this in a second). Applying this to the two base states, we can see that for &lt;math&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mn&gt;1&lt;/mn&gt;&lt;mo&gt;&amp;middot;&lt;/mo&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mn&gt;0&lt;/mn&gt;&lt;mo&gt;&amp;middot;&lt;/mo&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;, the probability of measuring &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; is 1, and the probability of measuring &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; is zero. For &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;, those are reversed. We thus get confirmation that those two states are measured as themselves. They are classical states, and have no uncertainty associated with them.&lt;/p&gt;
&lt;p&gt;Now let's look at a state that is a superposition of both states, the &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mi&gt;q&lt;/mi&gt;&lt;/mfenced&gt;&lt;/math&gt; state above. The probability to get &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; is &lt;math&gt;&lt;msup&gt;&lt;mfenced open="|" close="|"&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;/mfenced&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt;&lt;/math&gt;, and the probability to get &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; is &lt;math&gt;&lt;msup&gt;&lt;mfenced open="|" close="|"&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;/mfenced&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt;&lt;/math&gt;. No other result is possible, which means that the sum of those probabilities should be 1. The probabilities of a complete set of possible outcomes always sum up to 1. Numerically, this translates as &lt;math&gt; &lt;msup&gt;&lt;mfenced open="|" close="|"&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;/mfenced&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;msup&gt;&lt;mfenced open="|" close="|"&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;/mfenced&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msup&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/math&gt;. This is what we mean by &amp;ldquo;normalized state&amp;rdquo;, and it is a constraint that we'll enforce to keep the formulas simple: not enforcing it would add a scale factor to the probability formula. Not a big deal, but it's fine to see it as a useful convention.&lt;/p&gt;
&lt;p&gt;Can you guess what the probabilities will be to measure either value from a qubit built as a superposition of equal amounts of each state?&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mi&gt;p&lt;/mi&gt;&lt;/mfenced&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mo&gt;&amp;middot;&lt;/mo&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mo&gt;&amp;middot;&lt;/mo&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;The squared amplitude for each value is the same: &lt;math&gt;&lt;mfrac&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/mfrac&gt;&lt;/math&gt;. This means that, as expected, each value is equally likely, and that the probabilities add up to 1.&lt;/p&gt;
&lt;p&gt;Once a state has been measured, its state becomes whichever base state happens to have been randomly selected. It is no longer a superposition. So in the previous example, a measure will give one or the other value half the time. Let's say we measured &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;. The state is now &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;, so if we measure it again, because it is now this state, and we've seen &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; measured as &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; 100% of the time, we will always measure &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img title="Representation of a measurement operation (source Wikipedia)" alt="Representation of a measurement operation (source Wikipedia)" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/Qcircuit_measure-arrow.svg/150px-Qcircuit_measure-arrow.svg.png" /&gt;&lt;/p&gt;
&lt;p&gt;We now have the basic understanding of a qubit, and of what happens when we attempt to measure it. Let's now look at what operations we can perform on qubits, in which we'll introduce the quantum building blocks that are analogous to classical logic gates.&lt;/p&gt;
&lt;h3&gt;Quantum operators&lt;/h3&gt;
&lt;p&gt;It is possible to transform quantum states while keeping their quantum properties (unlike what happens when measuring them). Those transformations must obey a number of rules in order to be valid, and one of those rules is that the transformed state must still be a valid quantum state, for which the probabilities of observing the various possible states have a sum of 1. Such transformations are called &amp;ldquo;unitary&amp;rdquo;, and they can be described with matrices. Applying the transformation is the same thing as multiplying the matrix by the vector representing the state.&lt;/p&gt;
&lt;p&gt;Let's start with one of the simplest operations we can do: NOT. A NOT gate, both in classical and quantum computing, transforms 0 into 1, and 1 into 0. The matrix for this is easy to build:&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mfenced open="[" close="]"&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;It's easy to see that this works as expected:&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mfenced open="[" close="]"&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;mfenced open="[" close="]"&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mfenced open="[" close="]"&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;mspace width="2em"&gt;&lt;/mspace&gt; &lt;mfenced open="[" close="]"&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;mfenced open="[" close="]"&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mfenced open="[" close="]"&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;A NOT gate is usually represented with the following symbol:&lt;/p&gt;
&lt;p&gt;&lt;img title="NOT (source Wikipedia)" alt="NOT (source Wikipedia)" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/23/Qcircuit_NOT.svg/150px-Qcircuit_NOT.svg.png" /&gt;&lt;/p&gt;
&lt;p&gt;Another interesting gate is the Hadamard gate, or H gate:&lt;/p&gt;
&lt;p&gt;&lt;img title="Hadamard gate (source Wikipedia)" alt="Hadamard gate (source Wikipedia)" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Hadamard_gate.svg/150px-Hadamard_gate.svg.png" /&gt;&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;mrow&gt; &lt;msqrt&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msqrt&gt; &lt;/mrow&gt; &lt;/mfrac&gt; &lt;mfenced open="[" close="]"&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mtd&gt; &lt;mtd&gt; &lt;mn&gt;-1&lt;/mn&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;This gate transforms &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; into &lt;math&gt; &lt;mfrac&gt; &lt;mrow&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt; &lt;/mrow&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;/math&gt;, and &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; into &lt;math&gt; &lt;mfrac&gt; &lt;mrow&gt; &lt;mfenced open="|" close="⟩"&gt; &lt;mn&gt;0&lt;/mn&gt; &lt;/mfenced&gt; &lt;mo&gt;-&lt;/mo&gt; &lt;mfenced open="|" close="⟩"&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;/mfenced&gt; &lt;/mrow&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt;&lt;/msqrt&gt; &lt;/mfrac&gt; &lt;/math&gt;. This is interesting because if you started with one of the base states, you can use this to transform it into a superposition.&lt;/p&gt;
&lt;p&gt;Let's move on to gates that involve more than one qubit. Things are going to get a lot more exciting and spooky, because this will open the door to quantum entanglement.&lt;/p&gt;
&lt;p&gt;To represent two qubits, we just use a &lt;a href="https://en.wikipedia.org/wiki/Tensor_product"&gt;tensor product&lt;/a&gt;. The individual base states for our dual-qubit quantum states are all tensor products of the base states of both qubits. There's 4 of them, that we'll use as the bases for the space of 2-qubit states:&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mi&gt;00&lt;/mi&gt;&lt;/mfenced&gt;&lt;mspace width="2em"&gt;&lt;/mspace&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mi&gt;01&lt;/mi&gt;&lt;/mfenced&gt;&lt;mspace width="2em"&gt;&lt;/mspace&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mi&gt;10&lt;/mi&gt;&lt;/mfenced&gt;&lt;mspace width="2em"&gt;&lt;/mspace&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mi&gt;11&lt;/mi&gt;&lt;/mfenced&gt;&lt;mspace width="2em"&gt;&lt;/mspace&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;Extrapolating from this, you should start to see how this will will scale: a 8 qubit system will be represented by vectors in a space whose base are the tensor products of eight individual states, each of which have two base states. That's a &lt;math&gt;&lt;msup&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;mn&gt;8&lt;/mn&gt;&lt;/msup&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mn&gt;256&lt;/mn&gt;&lt;/math&gt; dimensional space. As you can see, the number of degrees of freedom of the system literally grows exponentially with the number of qubits, and yet, the number of gates you need to process them grows only linearly. That is what makes quantum computers more powerful (for algorithms that can take advantage of them) than classical ones. I cannot stress enough that this is one case where the word &amp;ldquo;exponential&amp;rdquo; is actually justified, because it is so rarely the case. It also shows how the benefits of quantum computing are ones of scalability: it can solve problems where the complexity grows too fast for classical computers, by growing the computing power non-linearly.&lt;/p&gt;
&lt;p&gt;If we build a state from two qubits&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mi&gt;a&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mi&gt;b&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt; and &lt;math&gt; &lt;mi&gt;c&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mi&gt;d&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;That same state can be represented in terms of tensor products as:&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mi&gt;ac&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mi&gt;ad&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;01&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mi&gt;bc&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;10&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mi&gt;bd&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;11&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;Remember however that any linear combination of the four base states is possible. Is it always possible to express such a state as the tensor product of two qubits? In other words, given a state &lt;math&gt; &lt;mi&gt;A&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mi&gt;B&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;01&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mi&gt;C&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;10&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mi&gt;D&lt;/mi&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;11&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;, is it always possible to find &lt;math&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;/math&gt;, &lt;math&gt;&lt;mi&gt;b&lt;/mi&gt;&lt;/math&gt;, &lt;math&gt;&lt;mi&gt;c&lt;/mi&gt;&lt;/math&gt;, and &lt;math&gt;&lt;mi&gt;d&lt;/mi&gt;&lt;/math&gt; such that:&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mfenced open="{" close=""&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mi&gt;A&lt;/mi&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mi&gt;ac&lt;/mi&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mi&gt;B&lt;/mi&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mi&gt;ad&lt;/mi&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mi&gt;C&lt;/mi&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mi&gt;bc&lt;/mi&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt; &lt;mi&gt;D&lt;/mi&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mi&gt;bd&lt;/mi&gt; &lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;The answer is no. For example, &lt;math&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;11&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt; cannot be expressed as a tensor product of states of individual qubits. It's easy to see that since &lt;math&gt;&lt;mi&gt;B&lt;/mi&gt;&lt;mo&gt;=&lt;/mo&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/math&gt;, &lt;math&gt;&lt;mi&gt;a&lt;/mi&gt;&lt;/math&gt; or &lt;math&gt;&lt;mi&gt;d&lt;/mi&gt;&lt;/math&gt; would have to be zero, but that would make &lt;math&gt;&lt;mi&gt;D&lt;/mi&gt;&lt;/math&gt; zero, which is false.&lt;/p&gt;
&lt;p&gt;Such a state, that can be realized in a two-qubit system, but isn't a simple combination of two qubits, is called an entangled state. This name is justified by an interesting property, which is that the measurement of the two bits is tightly coupled.&lt;/p&gt;
&lt;p&gt;In the example above (known as a Bell state), the two states that can be measured are &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; and &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;11&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;. All other states have a zero probability of coming up. Another way to say this is that if the first bit is measured as a 1, the second bit will also be measured as a 1, and the same goes for measuring a zero. There is still chance involved in the measurement, but the system's bits are strangely coupled. It looks like the first bit is communicating its own measure to the second one, instantly (and even potentially, over huge distances that couldn't be covered by a physical signal that would have to be faster than light, which is impossible).&lt;/p&gt;
&lt;p&gt;From a quantum perspective, nothing really weird is going on: there is only one state, that spans what we as classical observers identify as two separate entities. There is only one measurement being performed, over a single system, even if that system is delocalized. When we choose to measure the individual classical bits, we're slicing into that state in "diagonal", we're looking at the physical system from a point of view that isn't particularly natural. The weirdness is in our perspective.&lt;/p&gt;
&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Bell_state"&gt;There's more to quantum entanglement&lt;/a&gt; (for instance it's what enables &lt;a href="https://en.wikipedia.org/wiki/Quantum_teleportation"&gt;quantum teleportation&lt;/a&gt;), but you should know enough from that brief introduction to understand its usefulness in the context of quantum computing. Entangled states are those states that cannot be described as the combination of its qubits. They highlight those cases where the system is more than the sum of its parts.&lt;/p&gt;
&lt;p&gt;Another consequence of the existence of entangled states is that you can't take shortcuts when simulating qubits on classical hardware: you need to consider the whole exponentially growing set of base states, and can't consider the qubits in isolation. This means that the simulation will become impractical very fast, as the number of qubits grows.&lt;/p&gt;
&lt;p&gt;So how do we build one of those states? For that, we'll need new multiple-qubit gates. The first we need is the controlled NOT gate, or CNOT. With this gate, the first qubit acts as a control (it's unchanged by the operation), and the second bit is inverted only if the first qubit is &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; (otherwise it's left alone):&lt;/p&gt;
&lt;p&gt;&lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/CNOT_gate.svg/150px-CNOT_gate.svg.png" alt="CNOT gate (source Wikipedia)" title="CNOT gate (source Wikipedia)" align="middle" /&gt;&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mi&gt;CNOT&lt;/mi&gt; &lt;mo&gt;=&lt;/mo&gt; &lt;mfenced open="[" close="]"&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;It's easy to verify that, as announced, we have the following mapping on the base states:&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;&amp;rarr;&lt;/mo&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt; &lt;mspace width="2em"&gt;&lt;/mspace&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;01&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;&amp;rarr;&lt;/mo&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;01&lt;/mn&gt;&lt;/mfenced&gt; &lt;mspace width="2em"&gt;&lt;/mspace&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;10&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;&amp;rarr;&lt;/mo&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;11&lt;/mn&gt;&lt;/mfenced&gt; &lt;mspace width="2em"&gt;&lt;/mspace&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;11&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;&amp;rarr;&lt;/mo&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;10&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;If we first apply a Hadamard gate on the first qubit, then CNOT on the resulting state, the resulting combination has the interesting property that it maps &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; onto the Bell state &lt;math&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;11&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;.&lt;/p&gt;
&lt;p&gt;Let's verify this. The Hadamard gate on the first qubit maps &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; onto &lt;math&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;10&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;. Then, the CNOT gate leaves &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; unchanged while it maps &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;10&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; onto &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;11&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;. QED, the resulting state is &lt;math&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;00&lt;/mn&gt;&lt;/mfenced&gt; &lt;mo&gt;+&lt;/mo&gt; &lt;mfrac&gt; &lt;mn&gt;1&lt;/mn&gt; &lt;msqrt&gt; &lt;mn&gt;2&lt;/mn&gt; &lt;/msqrt&gt; &lt;/mfrac&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;11&lt;/mn&gt;&lt;/mfenced&gt; &lt;/math&gt;, and we have successfully prepared an entangled state. It's left as an exercise to the reader that the other three base states also get mapped to entangled states.&lt;/p&gt;
&lt;p&gt;Of course, &lt;a href="https://en.wikipedia.org/wiki/Quantum_logic_gate"&gt;there are many other possible gates&lt;/a&gt;. The point being that like for classical computing, there are minimal universal sets of gates that are enough, when combined, to perform almost any calculations. Also like in classical computing, implementing an algorithm when all you have is the lowest level of gates is not exactly the easiest thing in the world. With classical computers, we have several layers of abstraction that enables us to express computations with high-level languages, but we have no such luxury (yet) with quantum computers. Even something like &lt;a href="https://www.microsoft.com/en-us/research/uploads/prod/2018/03/1803.00652.pdf"&gt;Q#&lt;/a&gt; only enables developers to mix high-level classical constructs with low-level qubit manipulation.&lt;/p&gt;
&lt;h3&gt;The trouble with quantum computers: the inaccessible state&lt;/h3&gt;
&lt;p&gt;With this, we've in principle set-up all of the basic concepts needed by quantum computing. It even looks like we have a way to simultaneously perform arbitrary calculations on all possible inputs, in the time it would take a classical computer to run the same calculations on just one input. Prepare a state such that each qubit is a perfect superposition of &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;and &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;, run it through gates that implement your calculation, and presto!, you've got a result that is the superposition of the results for all possible input values. If you had access to that result state, there are simple tricks that would enable you to actually extract each individual result.&lt;/p&gt;
&lt;p&gt;That is precisely the issue, though: we do not have access to the quantum state, not directly at least. The quantum state may be the true physical state of the system, but we can never get all the information about it. All we can do is measure it, and as we've seen, measurement is a destructive, stochastic, and lossy process. In effect, it is a general principle that you cannot extract more than &lt;math&gt;&lt;mi&gt;n&lt;/mi&gt;&lt;/math&gt; bits of information out of &lt;math&gt;&lt;mi&gt;n&lt;/mi&gt;&lt;/math&gt; qubits. Does this mean that we've just lost all the potential benefits of quantum computing? Not exactly, but it does mean that we'd better make those measurements count...&lt;/p&gt;
&lt;h3&gt;The simplest win: guess the function&lt;/h3&gt;
&lt;p&gt;Imagine that we have an unknown function that takes one classical bit as an input, and outputs one classical bit. There are only four such functions:&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mtable&gt; &lt;mtr&gt; &lt;mtd&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mo&gt;(&lt;/mo&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;mo&gt;)&lt;/mo&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mo&gt;(&lt;/mo&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;mo&gt;)&lt;/mo&gt;&lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt;&lt;msub&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/msub&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt;&lt;msub&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/msub&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt;&lt;msub&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mn&gt;2&lt;/mn&gt;&lt;/msub&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mtd&gt; &lt;/mtr&gt; &lt;mtr&gt; &lt;mtd&gt;&lt;msub&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mn&gt;3&lt;/mn&gt;&lt;/msub&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mtd&gt; &lt;mtd&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mtd&gt; &lt;/mtr&gt; &lt;/mtable&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;Two of those (&lt;math&gt;&lt;msub&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/msub&gt;&lt;/math&gt; and &lt;math&gt;&lt;msub&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mn&gt;3&lt;/mn&gt;&lt;/msub&gt;&lt;/math&gt;) are constants. If you wanted to determine if the function is one of those two constant functions with a classical computer, you have to perform exactly two operations: feed it a 0, then feed it a 1. If both results are equal, the function is constant.&lt;/p&gt;
&lt;p&gt;A quantum computer can do that in only one operation. The trick to do it is to sandwich between two Hadamard gates a special function called an oracle, that is built from the one we're trying to guess. We'll then feed a &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; into the process. The oracle to use is the following:&lt;/p&gt;
&lt;blockquote&gt;&lt;math&gt; &lt;mfenced open="|" close="⟩"&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;/mfenced&gt; &lt;mo&gt;&amp;rarr;&lt;/mo&gt; &lt;msup&gt;&lt;mrow&gt;&lt;mo&gt;(&lt;/mo&gt;&lt;mn&gt;-1&lt;/mn&gt;&lt;mo&gt;)&lt;/mo&gt;&lt;/mrow&gt;&lt;mrow&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;mo&gt;(&lt;/mo&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;mo&gt;)&lt;/mo&gt;&lt;/mrow&gt;&lt;/msup&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;/mfenced&gt; &lt;/math&gt;&lt;/blockquote&gt;
&lt;p&gt;Whether the result of the evaluation of &lt;math&gt;&lt;mi&gt;f&lt;/mi&gt;&lt;/math&gt; is 0 or 1, if the function is constant, the &lt;i&gt;same&lt;/i&gt; phase will be applied to both of the base states. This means that any quantum state will come out unchanged, except for the occasional &lt;math&gt;&lt;mo&gt;(&lt;/mo&gt;&lt;mn&gt;-1&lt;/mn&gt;&lt;mo&gt;)&lt;/mo&gt;&lt;/math&gt; phase. And remember from what we said about measurement that phase cannot change the probability of the outcomes, only the amplitudes count.&lt;/p&gt;
&lt;p&gt;Now if the function is &lt;i&gt;not&lt;/i&gt; constant, each of the base states will get opposite phase shifts. All we have to do now is add the Hadamard gates around the oracle, and feed the system the &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; state.&lt;/p&gt;
&lt;p&gt;Let's break the whole process down from beginning to end. The first Hadamard gate will change the state into a superposition of the base states. If the function is constant, the oracle will give back the &lt;i&gt;same&lt;/i&gt; state, with maybe a phase change. The second Hadamard gate will transform that back into &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;, with maybe a phase change. If the function is not constant, a different state comes out, with a phase shift on one of the base states, and not on the other. In this case, the second Hadamard gate is going to transform that into a pure &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt;. All we have to do is measure the output. If the function is constant, we'll get &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;0&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; 100% of the time, and if it's not, we'll get &lt;math&gt;&lt;mfenced open="|" close="⟩"&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;/mfenced&gt;&lt;/math&gt; 100% of the time. We have successfully obtained information from the system, without any quantum uncertainty, faster than a classical system ever could.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;We went through one of the simplest examples of a quantum algorithm that outperforms any possible classical system. The principles we've applied are the same you'd apply at a larger scale, but the benefits would then be considerably more substantial. We take a known base state, change it into some superposed quantum state, then apply some transformation, and come back to pure base states that depend on the outcome of the computation, then we measure. We will not gain the exponentially faster parallel computing we may have been led to hope for from the behavior of the quantum state and gates, but we do get very real benefits on appropriate processes. Learning and discovering those processes can be a lot more complicated than what I've shown in this article, but I hope that you've gained an understanding and an appreciation of it. Most of all, I hope things look a little less mysterious, and a lot more fascinating, that you'll be driven to read more about quantum computing. Tell me what you think in the comments, what you'd like to read in future posts, and of course, let me know if I got anything wrong.&lt;/p&gt;</description><pubDate>Mon, 30 Apr 2018 18:16:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/quantum-computing-and-topological-qubits-explained-clearly</guid><category>Microsoft</category><category>Science</category></item><item><title>Orchard Harvest 2017–Orchard Core CMS</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-orchard-core-cms</link><description>&lt;p&gt;For the last presentation of the day, Sébastien explained what Orchard Core is all about. Orchard Core runs on ASP.NET Core, and as a consequence is leaner, faster, and cross-platform. One big change is that its content is persisted as documents instead of relational tables.&lt;/p&gt; &lt;p&gt;Other differences include:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;The admin theme is now a setting.&lt;/li&gt; &lt;li&gt;The content item editor has a new live preview feature, content editor, an flow part that largely replaces the layout feature of Orchard 1. The whole thing is responsive and easy to work with.&lt;/li&gt; &lt;li&gt;A navigation is one single content item, with its hierarchy persisted as a single document. This is very fast, but preserves the extensibility of Orchard 1: menu items are still themselves content items, it’s just that they are persisted all together in the containing menu content item’s document. This also helps versioning the menu as a whole, as well as efficiently caching it.&lt;/li&gt; &lt;li&gt;The order of parts in type definitions is easier to change.&lt;/li&gt; &lt;li&gt;There are named parts.&lt;/li&gt; &lt;li&gt;Blogs are just lists of blog posts.&lt;/li&gt; &lt;li&gt;Tokens are input into Handlebar templates (for example in Autoroute).&lt;/li&gt; &lt;li&gt;The widget editor supports drag and drop between zones, and has an undo button.&lt;/li&gt; &lt;li&gt;Widgets can be used in “flow pages”, in which case their editor is displayed inline in the content item editor.&lt;/li&gt; &lt;li&gt;Recipes can have dynamic values and define variables. They are also JSON documents.&lt;/li&gt; &lt;li&gt;It’s crazy fast. 15ms to render a blog with widgets without caching on a laptop in Debug mode under load (2000 rps). This is way faster than Orchard 1 with caching on.&lt;/li&gt; &lt;li&gt;Creating and setting up a new tenant is instantaneous. So is enabling a module.&lt;/li&gt; &lt;li&gt;Memory usage: tenants are lazily loaded on their first requests, and 500 tenants fit in 2GB on a 64 bit machine.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Migrating data will not be trivial, and will have to go through import/export. Migrating modules should be easy. Modules are like a mini-MVC application, much like in Orchard 1.&lt;/p&gt; &lt;p&gt;You can follow the progress on &lt;a title="https://github.com/OrchardCMS/Orchard2/wiki/Roadmap" href="https://github.com/OrchardCMS/Orchard2/wiki/Roadmap"&gt;https://github.com/OrchardCMS/Orchard2/wiki/Roadmap&lt;/a&gt;&lt;/p&gt; &lt;p&gt;It’s also a great time to start contributing!&lt;/p&gt;</description><pubDate>Wed, 22 Feb 2017 21:57:12 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-orchard-core-cms</guid><category>Orchard</category><category>Harvest</category></item><item><title>Orchard Harvest 2017–YesSql</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-yessql</link><description>&lt;p&gt;S&amp;eacute;bastien Ros gave a surprise demo of &lt;a href="https://github.com/sebastienros/yessql"&gt;YesSql&lt;/a&gt;, the document database interface over relational databases that powers Orchard Core&amp;rsquo;s data access. YesSql stores plain objects into documents stored on a relational database. It supports SQL Server, MySql, Postgre, Sqlite, LightningDB, and in-memory. YesSql also allows for querying those objects using queryable indexes. Those indexes are projections of documents into structured tables, that only exist for the purpose of being queried.&lt;/p&gt;
&lt;p&gt;YesSql supports map indexes that map one document to one or more index records, and map-reduce indexes that aggregate documents. For all operations, you create a transactional session from a store object. The store object needs to be initialized once before the database can be used for YesSql. The session can save documents using the &lt;span face="Consolas" style="font-family: Consolas;"&gt;Save&lt;/span&gt; method, which results in a JSON-serialized record in the database. Known classes, as well as anonymous objects can be persisted.&lt;/p&gt;
&lt;p&gt;When fetching documents, it&amp;rsquo;s possible to get a dynamic object when the type is not known. If you know the type, you can &lt;span face="Consolas" style="font-family: Consolas;"&gt;GetAsync&amp;lt;KnownType&amp;gt;(id)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;An index is built by deriving from &lt;span face="Consolas" style="font-family: Consolas;"&gt;IndexProvider&amp;lt;T&amp;gt;.&lt;/span&gt; The &lt;span face="Consolas" style="font-family: Consolas;"&gt;Describe&lt;/span&gt; method defines the mapping from the type T to another type that derives from &lt;span face="Consolas" style="font-family: Consolas;"&gt;MapIndex&lt;/span&gt;, and has properties that will get serialized as individual columns of the index table in the database. That table can then be queried in rich manners by calling &lt;span face="Consolas" style="font-family: Consolas;"&gt;QueryAsync&amp;lt;T, TIndex&amp;gt;()&lt;/span&gt;, that can then be chained with &lt;span face="Consolas" style="font-family: Consolas;"&gt;Where&lt;/span&gt;, &lt;span face="Consolas" style="font-family: Consolas;"&gt;OrderBy&lt;/span&gt;, and other Linq extensions.&lt;/p&gt;
&lt;p&gt;When building an index, it&amp;rsquo;s possible to pre-filter documents, which means that there is no runtime cost to filtering when the conditions are known in advance.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s also possible to perform joined queries between several indexes.&lt;/p&gt;
&lt;p&gt;Map/reduce indexes can first do a &lt;span face="Consolas" style="font-family: Consolas;"&gt;Map&lt;/span&gt;, then usually a &lt;span face="Consolas" style="font-family: Consolas;"&gt;Group&lt;/span&gt;, and finally compute some aggregate values over the group in &lt;span face="Consolas" style="font-family: Consolas;"&gt;Reduce&lt;/span&gt;. There is an optional &lt;span face="Consolas" style="font-family: Consolas;"&gt;Delete&lt;/span&gt; method that describes how to update an index in case of document deletion, to avoid having to re-compute the whole index.&lt;/p&gt;
&lt;p&gt;All indexes are automatically maintained.&lt;/p&gt;
&lt;p&gt;During questions, S&amp;eacute;bastien explained how integer document ids are acquired: the sessions get assigned next ids one by one, and different sessions will be assigned new ids that are guaranteed to be owned by them. The result is not necessarily sequential, but enables clients to know unique ids on creation without round-tripping to the database.&lt;/p&gt;</description><pubDate>Wed, 22 Feb 2017 19:01:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-yessql</guid><category>Orchard</category><category>Harvest</category></item><item><title>Orchard Harvest 2017–Client-side components in Orchard</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-client-side-components-in-orchard</link><description>&lt;p&gt;A client-side component is defined as a component that implements its rendering and behavior on the client, with server interactions going through some APIs.&lt;/p&gt; &lt;p&gt;Such components can be implemented in Orchard using a range of technologies from simple shape templates to full-blown parts and elements. A good compromise is layout snippets. Layout snippets can be implemented with a simple SomethingSnippet.cshtml file that can simply be dropped into the Views folder of a module, and is then available as a regular element in layouts. Snippets can also be associated with a manifest that specifies metadata such as toolbox icons, and also configurable fields.&lt;/p&gt; &lt;p&gt;Daniel showed how to use a shape table provider in his module to add an API URL onto his shape from site settings.&lt;/p&gt; &lt;p&gt;To manage client-side assets, he’s using Gulp. There’s a choice however to put the generated assets in source control or not. His preference is to keep them out: they don’t get stale, don’t need to be pushed on all modifications, it reduces noise and footprint. The downside is of course that developers wanting to modify the module need to install the tooling.&lt;/p&gt; &lt;p&gt;The component client assets are Handlebars templates, TypeScript, and scss, and they are bundled using Browserify. The corresponding tooling is brought in by a package.json file.&lt;/p&gt; &lt;p&gt;Things get a little more complicated when building Angular components, because of Angular routing, which happens purely on the client and integrates into browser navigation. That requires integration with Orchard server-side routing, which doesn’t work out of the box. The way to make it work is to use the routing features from &lt;a href="https://github.com/IDeliverable/IDeliverable.Bits"&gt;the IDeliverable.Bits module&lt;/a&gt; to add a base URL tag to the page and &lt;a href="https://github.com/IDeliverable/IDeliverable.Bits/tree/master/Routing"&gt;tweak routing&lt;/a&gt; so Orchard can recognize that base URL as an Orchard route. The rest of the URL will be handled client-side by the Angular component to display the proper thing.&lt;/p&gt; &lt;p&gt;One last thing that is required is to prepare some data for the scripts to use, such as base paths. This is done by rendering those pieces of data into data-* attributes in the markup.&lt;/p&gt;</description><pubDate>Wed, 22 Feb 2017 17:32:32 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-client-side-components-in-orchard</guid><category>Orchard</category><category>Harvest</category></item><item><title>Orchard Harvest 2017–Localization</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-localization</link><description>&lt;p&gt;Benedek is one of the founders of &lt;a href="https://lombiq.com/"&gt;Lombiq&lt;/a&gt;, and the caretaker of Orchard localization. Application localization requires taking into account cultural differences such as gender, formal vs informal, pluralization, right to left, verbosity, accents, etc. In Orchard, all localizable strings should be wrapped in &lt;font face="Consolas"&gt;T()&lt;/font&gt; calls. That is enough to make the string localizable in &lt;a href="https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html"&gt;PO files&lt;/a&gt;. Some strings can contain placeholders, such as &lt;font face="Consolas"&gt;T("Hello, I’m from {0}.")&lt;/font&gt;. You can use the &lt;a href="https://github.com/bleroy/vandelay"&gt;Vandelay Industries module&lt;/a&gt;’s translation extraction feature to extract all the T strings from a module into po files. The module produces a zip archive that contains the layout of localization files that you’d unzip into the site in order to install it. To localize, you can copy any po file from its en-us directory to a new directory for the new culture, then translate the strings inside.&lt;/p&gt; &lt;p&gt;Manual translation of po files is not the only option, however. The Orchard community is crowd-sourcing and centralizing translation of the core platform and of the most common modules on &lt;a href="https://crowdin.com/"&gt;Crowdin&lt;/a&gt;. Benedek uploads po files for all new releases of Orchard onto the site, then anybody can contribute translations, with machine translation suggestions from Crowdin, and proofread existing translations. The resulting translated strings can be downloaded as an archive that can be unzipped over the web site. You can then add cultures in Orchard settings, switch the default culture and start using the new translations.&lt;/p&gt; &lt;p&gt;Now that we know how to localize static strings defined in modules, we can look at how to translate contents. Translating contents can be challenging, especially in cases where relationships between items exist, such as taxonomies, or media library picker fields. All the tools are in place in Orchard for this to work however, with the possibility to specify items as culture neutral, cloning capabilities, and culture matching of associated items. Navigation is still work in progress but is following the same path.&lt;/p&gt; &lt;p&gt;A guide to localization is available from &lt;a title="http://orchardproject.net/localization" href="http://orchardproject.net/localization"&gt;http://orchardproject.net/localization&lt;/a&gt;&lt;/p&gt; &lt;p&gt;In questions, bulk translation was mentioned, for which &lt;a href="http://gallery.orchardproject.net/Packages/Orchard.Module.Q42.DbTranslations"&gt;the q42 module&lt;/a&gt; is very useful.&lt;/p&gt; &lt;p&gt;Jorge also mentioned how the en-us translation can be used to hack the site into displaying a different string in English than what’s specified in code.&lt;/p&gt;</description><pubDate>Wed, 22 Feb 2017 16:29:49 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-localization</guid><category>Orchard</category><category>Harvest</category></item><item><title>Orchard Harvest 2017–Writing a theme for Orchard Core</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-writing-a-theme-for-orchard-core</link><description>&lt;p&gt;In the &lt;a href="http://orchardharvest.org/sessions/building-themes-using-the-latest-client-side-technologies"&gt;first session of the second day of Orchard Harvest,&lt;/a&gt; Steve Taylor showed how to build a new theme for Orchard Core. All the pieces are already in place for building themed sites, and the work is similar to Orchard 1.x themes, except for some json file editing because of missing admin UI in places. New Razor Pages features can be used, such as tag helpers, @inject directives, etc. The tag helpers in particular, coupled with Orchard’s shapes, make for very clean markup in view files. The video for the talk, when available, will be a valuable reference for people who want to get started building sites with Orchard Core: the CMS now looks feature-complete enough to do some serious work. Widgets are there, the shape system is there, search, navigation, all work. That Steve was able to build a complete site and theme under an hour (with some pre-built css and views, of course) shows how far Orchard Core has gone already.&lt;/p&gt;</description><pubDate>Wed, 22 Feb 2017 15:02:46 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-writing-a-theme-for-orchard-core</guid><category>Orchard</category><category>Harvest</category></item><item><title>Orchard Harvest 2017–What is Orchard Core SaaS Framework?</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-what-is-orchard-core-saas-framework</link><description>&lt;p&gt;Nick Mayne is one of the main developers working on Orchard 2.0, a.k.a. Orchard Core.&lt;/p&gt; &lt;p&gt;Orchard Core started as an MVC application, but this had several challenges with multi-tenancy and Glimpse integration. To solve those problems, Nick moved things around so MVC actually is a module instead. I found that really interesting as I had implemented something really similar when I built DecentCMS: Express is loaded as a module, for each tenant.&lt;/p&gt; &lt;p&gt;In his first demo, he started with a simple ASP.NET Core application, and transformed it into an Orchard Core application where the application code lives in a module instead of the startup class where it began. In the module, a simple class derives from StartupBase and overrides Configure and ConfigureServices.&lt;/p&gt; &lt;p&gt;The second demo is improving on the first one by adding actual MVC to the application. The existing module is modified to register MVC. Nick then added a new module, gave it a controller with an Index action. The result is MVC in an Orchard Core site with a module registering MVC, and another using MVC. In a full Orchard stack, the module registering MVC would be “the MVC module”, and the other would just take a dependency on it.&lt;/p&gt; &lt;p&gt;Next, Nick showed how to point the site’s host to an alternate module location. This is how themes are added: services.AddExtensionLocation(“Themes”). You can also modify manifest definitions.&lt;/p&gt; &lt;p&gt;For the moment, we haven’t created any tenants. In other words, everything has been running on the default tenant. Using services.AddSitesfolder(“App_data”, “Sites”), it’s possible to point the application to locations where tenants are defined. Nick created two sites with their own manifests, which creates two tenants with all features enabled. To differentiate them, he injected the ShellSettings into the controller, whose action can now output properties coming from each tenant manifest.&lt;/p&gt; &lt;p&gt;Finally, Nick showed how to swap MVC for Nancy. Yes, one interesting consequence of having MVC as a module is that you may not use it at all, and you may even use something else altogether, such as Nancy. Moreover, you may even have one module built on Nancy, and another on MVC, all running in the same host. This is really very cool and shows just how low footprint Orchard Core is, and how its services, such as multi-tenancy and modules, come at a very low price and impose very few constraints on the whole system. In other words, you get exactly what you want, and nothing more.&lt;/p&gt;</description><pubDate>Tue, 21 Feb 2017 21:52:01 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-what-is-orchard-core-saas-framework</guid><category>Orchard</category><category>Harvest</category></item><item><title>Orchard Harvest 2017–Scaling Orchard</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-scaling-orchard</link><description>&lt;p&gt;Rob King works for &lt;a href="http://bedegaming.com/"&gt;Bede Gaming&lt;/a&gt;, which specializes in providing a platform for gambling web sites. The company moved to Orchard in 2013, and has strong scalability requirements, with sites serving millions of requests per day.&lt;/p&gt; &lt;p&gt;One of the problems they are facing is dependency management. One of the ways they deal with that problem is that they avoid features depending on each other, but instead try to have dependencies on abstractions. Instead of having feature A depending on feature B because they have common interfaces, those interfaces are extracted into a common module, and both features are made to depend on it.&lt;/p&gt; &lt;p&gt;They cache layer rules to avoid going to the content manager to get get them.&lt;/p&gt; &lt;p&gt;The Bede web sites are typically entirely dealing with authenticated users, so caching has to implement donut caching techniques. They also use Redis for distributed output caching, plus in-memory caching.&lt;/p&gt; &lt;p&gt;They had an incident when they had a deadlock on scheduled tasks that caused the scheduled tasks table to fill up with millions of records. It was solved with a node-aware version of the scheduled task manager.&lt;/p&gt; &lt;p&gt;Being multi-node aware everywhere was key to fixing many of the problems faced.&lt;/p&gt;</description><pubDate>Tue, 21 Feb 2017 20:35:47 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-scaling-orchard</guid><category>Orchard</category><category>Harvest</category></item><item><title>Orchard Harvest 2017–What’s new in ASP.NET MVC Core 2.0</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-what-s-new-in-asp-net-mvc-core-2-0</link><description>&lt;p&gt;Taylor Mullen from the ASP.NET team is a developer working on MVC Core 2.0. In this session, he went over the design of the new Razor Pages feature. He carefully explained what is difficult with MVC currently, in order to justify the feature. He actually started by showing what it’s not: it’s not PHP-like, and it’s not a new take on previous “ASP.NET Pages” features.&lt;/p&gt; &lt;p&gt;Razor Pages enable you to get started rendering views without having to build a controller. As the page is growing more complex, the code can be moved into a “page model”, that is starting to look more like a controller, mixed with a view model, but that is actually closer in spirit to what you’d have in a MVVM pattern. This all creates a smoother “grow up” story.&lt;/p&gt; &lt;p&gt;The last piece in the puzzle is routing, which is dealt with using a nice model binding syntax on the @page directive: &lt;a href="mailto:&amp;ldquo;@page"&gt;“@page&lt;/a&gt; foo/{id:int}” would setup the route so “foo/12” would hit the page with the id int parameter set to the value 12.&lt;/p&gt; &lt;p&gt;Taylor then showed how al this is wired up together, and how the same plumbing could be used with your own custom providers, in particular for directives.&lt;/p&gt;</description><pubDate>Tue, 21 Feb 2017 19:43:55 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-what-s-new-in-asp-net-mvc-core-2-0</guid><category>Orchard</category><category>Harvest</category><category>ASP.NET</category></item><item><title>Orchard Harvest 2017: when output cache just isn’t enough</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-when-output-cache-just-isn-t-enough</link><description>&lt;p&gt;Daniel Stolt and Chris Payne from &lt;a href="http://ideliverable.com"&gt;IDeliverable&lt;/a&gt; presented some &lt;a href="http://www.ideliverable.com/products/premium-orchard-modules/ideliverable-donuts"&gt;new output caching techniques&lt;/a&gt; that they’ve developed. The problem that they’re solving is what happens when you have to output user-specific data into rendered contents. In those cases, you want to cache the constant parts of the output, while keeping holes dynamic. This is known as donut caching.&lt;/p&gt; &lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/bleroy/Open-Live-Writer/Orchard-Harvest-2017_9A0E/snip_20170221081637_2.png"&gt;&lt;img title="snip_20170221081637" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="snip_20170221081637" src="https://aspblogs.blob.core.windows.net/media/bleroy/Open-Live-Writer/Orchard-Harvest-2017_9A0E/snip_20170221081637_thumb.png" width="800" height="211"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;The holes in the donuts can be puched into rich text using a placeholder with the %%{name} notation. Those placeholders are not exactly tokens, but behave similarly, and are also extensible.&lt;/p&gt; &lt;p&gt;They also have an item-level cache part that can be added for instance to widgets, and used to set the output cache policy for that specific item, or to exclude it from the cache altogether. The item-level cache configuration is very rich, and allows for very fine-grained control. This can even be extended with your own “vary by” providers.&lt;/p&gt; &lt;p&gt;Cached output is stored into the same place as Orchard’s built-in output cache. This means that any provider that already exists can be used without changes.&lt;/p&gt; &lt;p&gt;The module also introduces some new options to evict pages that use a given widget, that gives a lot more control than the built-in feature. For instance, if you have a menu widget on all your pages, you don’t want just any change on the menu to cause the eviction of every single page in the site from output cache.&lt;/p&gt; &lt;p&gt;It’s possible to cache summary versions of items, such as the ones in search results. In this case, individual items in a results list, if they are in the cache, do not need to be re-rendered, but can come from the cache. This is quite neat as the caching structure of the page in this case is nested.&lt;/p&gt; &lt;p&gt;Finally, it is possible to trigger pre-rendering of an item into the output cache whenever it gets evicted (on a change, typically).&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.ideliverable.com/products/premium-orchard-modules/ideliverable-donuts"&gt;IDeliverable’s donut caching module&lt;/a&gt; is a premium module that can be tried for free on localhost, bought, or subscribed to.&lt;/p&gt;</description><pubDate>Tue, 21 Feb 2017 16:49:02 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-when-output-cache-just-isn-t-enough</guid><category>Orchard</category><category>Harvest</category></item><item><title>Orchard Harvest 2017 – Using external data with Orchard</title><link>https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-using-external-data-with-orchard</link><description>&lt;p&gt;Jorge Agraz is opening the conference after Sébastien Ros’ keynote with &lt;a href="http://orchardharvest.org/sessions/external-data-with-orchard"&gt;a talk about using external data in Orchard&lt;/a&gt;. Jorge work for &lt;a href="http://onestop.com/"&gt;Onestop&lt;/a&gt;, a company that builds e-commerce sites. Their web sites get their commerce data from APIs and then used to display that through their controllers with Orchard shapes. They attempted to use widgets instead of controllers, but that came with some significant maintenance problems.&lt;/p&gt; &lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/bleroy/Open-Live-Writer/44b63a874c98_8D92/snip_20170221073543_2.png"&gt;&lt;img title="The Katy Perry web site is built with Orchard" style="background-image: none; display: inline; border-image: none" border="0" alt="The Katy Perry web site is built with Orchard" src="https://aspblogs.blob.core.windows.net/media/bleroy/Open-Live-Writer/44b63a874c98_8D92/snip_20170221073543_thumb.png" width="640" height="425"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;With the latest version, commerce pages are actual Orchard content types: category, product and shopping cart. They have elements, fields, and parts to represent everything. A Product driver lazily gets data from the commerce API and instantiates more than 20 shapes from it, that can be used to display the contents. This provides a lot of flexibility, and is easier to move around between dev, staging, and production servers. The number of shape alternates in typical themes has been drastically reduced from 50 to 90 down to 6.&lt;/p&gt; &lt;p&gt;Interestingly, themes have a shape table provider that can be used to turn shapes on or off, and configure them, going beyond what placement.info can do.&lt;/p&gt;</description><pubDate>Tue, 21 Feb 2017 16:08:39 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/orchard-harvest-2017-using-external-data-with-orchard</guid><category>Orchard</category><category>Harvest</category></item><item><title>Unimportant egocentric rant: don’t .ToUpper() your titles</title><link>https://weblogs.asp.net:443/bleroy/unimportant-egocentric-rant-don-t-toupper-your-titles</link><description>&lt;p&gt;Here&amp;rsquo;s a minor inconvenience that I&amp;rsquo;m going to put out there in the hope that one or two of the horrible people responsible for it may realize the errors of their ways and make the world a marginally better place.&lt;/p&gt;
&lt;p&gt;So you like your titles to be all caps. Fine. I&amp;rsquo;m not sure why you insist on screaming like that, but that&amp;rsquo;s your choice, and it&amp;rsquo;s your web site/blog. If you are going to do this, however, please don&amp;rsquo;t do this:&lt;/p&gt;
&lt;pre&gt;@post.Title.ToUpper()&lt;/pre&gt;
&lt;p&gt;And not just because you neglected to specify a culture (you monster). No, this is wrong because next time the guy who builds &lt;a href="https://blogs.msdn.microsoft.com/dotnet/tag/week-in-net/"&gt;the week in .NET&lt;/a&gt; wants to mention your site and copies the title over, he&amp;rsquo;s going to copy this:&lt;/p&gt;
&lt;p&gt;HOW TO USE ENTITY FRAMEWORK TO KILL PUPPIES!!!&lt;/p&gt;
&lt;p&gt;instead of this:&lt;/p&gt;
&lt;p&gt;How to use Entity Framework to make a rainbow&lt;/p&gt;
&lt;p&gt;He&amp;rsquo;s going to curse loudly, his kids may hear him, and they&amp;rsquo;ll grow up to become as obnoxious as he is, all because of you. Well done.&lt;/p&gt;
&lt;p&gt;This is particularly infuriating because there is a perfectly good way to do this bad thing that you insist on doing. In your CSS, just do something like this:&lt;/p&gt;
&lt;pre&gt;h1 { text-transform: uppercase; }&lt;/pre&gt;
&lt;p&gt;There. Was that so hard?&lt;/p&gt;
&lt;p&gt;Except that no. When you copy text that has been styled this way, you&amp;rsquo;ll still get the all caps text instead of the unstyled underlying text. &lt;a href="mailto:F@$"&gt;F@$&lt;/a&gt;#!&lt;/p&gt;
&lt;p&gt;OK.&lt;/p&gt;
&lt;p&gt;Fine.&lt;/p&gt;
&lt;p&gt;Just don&amp;rsquo;t &lt;span face="Consolas" style="font-family: Consolas;"&gt;.ToUpper&lt;/span&gt; your titles. Please. It looks like crap and it&amp;rsquo;s less readable. And you sound like a Facebook comment from that uncle who ruins Thanksgiving every year.&lt;/p&gt;</description><pubDate>Sat, 09 Apr 2016 16:23:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/unimportant-egocentric-rant-don-t-toupper-your-titles</guid></item><item><title>On dependencies, dependency injection, and sanity</title><link>https://weblogs.asp.net:443/bleroy/on-dependencies-dependency-injection-and-sanity</link><description>&lt;p&gt;What's interesting about debacles such as the recent &lt;a href="http://blog.npmjs.org/post/141577284765/kik-left-pad-and-npm"&gt;left-padding&lt;/a&gt; &lt;a href="http://left-pad.io/"&gt;madness&lt;/a&gt; is how it can get you to re-think seemingly obvious concepts, and challenge some basic assumptions. Here's in particular a little reflection that just occurred to me on the way between the bathroom and my office, and that may seem super-obvious to some of you. It wasn't to me, so here goes, I'm sharing…&lt;/p&gt; &lt;p&gt;Whether you go all theoretical, call it fancy and talk about "inversion of control", or you just pragmatically do constructor injection like God intended, at this point almost everyone agrees that dependency injection is a Good Idea. You inject a contract, and the black magic inside your IoC container finds the right implementation and gives you an instance, with the right scope, lifetime, etc. Coupling is low, applications are more robust, more modular, more flexible, and unicorns flutter around happily.&lt;/p&gt; &lt;p&gt;Now when you look at the wonderful world of package managers (a clear progress over what the hell we thought we were doing before), what are we doing exactly? Well, we need a component that performs a certain task (in other words, it fulfils a specific contract). We then go on to ask The One True Package Manager to hand us a very specific version of a very specific package. And we do so USING A STRONG NAME. Pardon me for screaming, but can you see the parallel here?&lt;/p&gt; &lt;p&gt;We are "injecting" a "dependency" into our application, but it doesn't for one second occur to us that the concept is almost exactly the same. Let's go over the comparison one more time.&lt;/p&gt; &lt;table cellspacing="0" cellpadding="2" border="1"&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;Dependency Injection&lt;/td&gt; &lt;td&gt;"dependency" "injection"&lt;/td&gt;&lt;/tr&gt;&lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Ask for a contract&lt;/td&gt; &lt;td&gt;Ask for a strong and versioned package name&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Get a managed and scoped instance with members that you can call into&lt;/td&gt; &lt;td&gt;Get a set of namespaces with stuff in them that you can call into&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;So what is good practice on one side (resolution by contract) is completely out of the picture on the other. Why can't we ask for packages by contract? I don't know exactly what that would be looking like, but I have the nagging feeling that there's something to invent here. Or does something like that exist? What do you think?&lt;/p&gt;</description><pubDate>Thu, 24 Mar 2016 23:50:29 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/bleroy/on-dependencies-dependency-injection-and-sanity</guid></item></channel></rss>