<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rick Lowrey on Medium]]></title>
        <description><![CDATA[Stories by Rick Lowrey on Medium]]></description>
        <link>https://medium.com/@rglowrey?source=rss-7edf5116d323------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Nz1XmtElPCJX_SE1.jpg</url>
            <title>Stories by Rick Lowrey on Medium</title>
            <link>https://medium.com/@rglowrey?source=rss-7edf5116d323------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:42:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rglowrey/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Deconstructed DBA]]></title>
            <link>https://medium.com/codex/the-deconstructed-dba-bbadc0135b4c?source=rss-7edf5116d323------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbadc0135b4c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[humor]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Rick Lowrey]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 07:02:05 GMT</pubDate>
            <atom:updated>2021-08-09T01:45:47.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncF-CQsgDQQGskh5OW499g.jpeg" /><figcaption>Photo by author, 2019</figcaption></figure><p>In the beginning, there was the zero. And the electrical engineer saw that it was good. But the zero was lonely, so the electrical engineer created the one, to be the yang for the zero’s yin, the helpmeet and partner, to go where it went, to provide a substance and a purpose. And the electrical engineer saw that it was good.</p><p>But the zero and the one could not do anything by themselves. So the electrical engineer created other zeros and ones, and made the op codes and the registers to hold their transitory states, so the zeroes and ones could grow, and operate on each other. And the electrical engineer saw that it was good.</p><p>But the transitory states were still transitory. The zeroes and ones could not survive on their own. They needed a way to persist, or to at least remember their state so they could be recreated. So the electrical engineer created storage. And the electrical engineer saw that it was good.</p><p>But the storage was static. Once it was used, it could not be re-used. So once the state of the zeroes and ones was persisted, it became stagnant. So the electrical engineer created rewritable media, and the devices to write to it and read from it. And so the zeroes and the ones could be persisted, and they could be recreated, and they could be persisted again, and recreated again. And again. And again. And the electrical engineer saw that it was good.</p><p>But at some point, the electrical engineer realized that he could use the storage to make copies of the zeroes and ones on other, separate devices. And so the fork came into being. And the electrical engineer thought it was good, but he had introduced the Tree of Branches into the garden.</p><p>And the zeroes and ones proliferated. Each device had it’s own version, and other electrical engineers thought they could guide the zeroes and ones better, and so the groups of zeroes and ones diverged and were not the same.</p><p>And the electrical engineers gathered with stormy brows and belief each in his own righteousness. And they contended, and they deliberated, and they warred, but eventually they came to enough consensus to establish rules about the behavior electrical engineers should use to guide zeroes and ones. Thus the Standards Organization was born. And the electrical engineers saw that it was good.</p><p>And the devices with their sets of consistent zeroes and ones could coordinate, and they could be specialized to do portions of the work of all, and they could stay in harmonious synchronization. And the Standards Organization saw that it was good.</p><p>But some devices with their zeroes and ones had too much work to do. So the electrical engineers decided that some sets of zeroes and ones could be copied onto new devices to share the work. And because of the Standards Organizations, the copies were perfect, and the work could be accomodated. And they all saw that it was good.</p><p>But because the new devices were not stateless, each had its own set of persisted zeroes and ones. And because the work to be done on each device was persisted separately, soon there was a difference in storage, and the devices were separate and standalone.</p><p>So the electrical engineer decided to create a new device. It would hold the state information for every other device, and would share that information with any device that could connect to it, to protect it and to ensure it was available and secure. And thus the Database was born. And the electrical engineer saw that it was good.</p><p>But there were situations where two devices needed to operate on the same groups of structures at the same time. The work was divided, but the zeroes and ones on the new device were grouped so that they were vulnerable if two devices needed to change the group. And so concurrency was born.</p><p>But the electrical engineer was no longer an electrical engineer. He had passed from dealing only with ones and zeroes, with currents and gates and such. He was now dealing with entire groups of ones and zeroes that could be assigned structure and meaning. And those structures could be grouped, and retrieved, and passed to those devices that requested them. And it was good. And thus the electrical engineer became a programmer.</p><p>And the programmer was clever, and was able to create a new set of instructions for how to deal with precedence of work, and so the queue was born. And thus the Database Management System was born. And the programmer saw that it was good.</p><p>But there were many other issues to deal with besides precedence of work. There was also deciding which devices would be allowed to connect to the new device, how the new device could be set to rights if some of the work went awry, how to make sure groups of zeroes and ones could be speedily routed to their destinations, and so forth. And so the programmer created the row lock, and the security system, and the logs of transactions and of system, and the cache and the index. And the programmer saw that it was good.</p><p>But the programmer was weary of his creation. The programmer wanted to create something new, something fresh, something different. And so the programmer forgot his roots as an electrical engineer, and the angels quietly wept.</p><p>But there were some programmers who refused to abandon their origin, who remembered that those issues discovered during creation were STILL issues that had to be accommodated. So that groups of zeroes and ones could persist, and be correct, and consistent, and protected, and accessible, so that the work could be done. Thus the programmer became a Database Administrator. And the Database Administrator carried the message of sharing, and of concurrency, and of security and accessibility for all who had need.</p><p>And it was good.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbadc0135b4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/the-deconstructed-dba-bbadc0135b4c">The Deconstructed DBA</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Overthink Anything]]></title>
            <link>https://rglowrey.medium.com/how-to-overthink-anything-f8097270060b?source=rss-7edf5116d323------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8097270060b</guid>
            <category><![CDATA[overthinking]]></category>
            <category><![CDATA[goals]]></category>
            <category><![CDATA[guitar]]></category>
            <category><![CDATA[analysis]]></category>
            <dc:creator><![CDATA[Rick Lowrey]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 08:15:12 GMT</pubDate>
            <atom:updated>2020-12-23T08:15:12.477Z</atom:updated>
            <content:encoded><![CDATA[<p>Or, “Requiem For A Fallen Bridge Pin”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWNbg6TUv5EBOisico0grQ.jpeg" /><figcaption>The Bridge Pin Hole. Image ©2020 by author.</figcaption></figure><p>I recently went to change the strings on my Dean Performer QSE acoustic-electric guitar, and I broke a bridge pin (please don’t ask how…it’s embarrassing). So, with a little swearing and some tips from online, I was able to extract the shattered remains of the pin out of the bridge pin hole. Here’s what it looks like now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPQ7pkASjodo0JxjFTqjmA.jpeg" /><figcaption>The Fallen Bridge Pin. Image ©2020 by author.</figcaption></figure><p>Now, I don’t have any spare bridge pins laying around. It’s not actually something that’s ever come up in the &lt;mumble mumble&gt; years that I’ve had the guitar. The original pins are made of a soft plastic material, almost like nylon. The remaining ones seem to be in good condition and are doing their jobs just fine. Perfectly serviceable. Really, if I could just get one additional one it would allow me to seat the string, tune up and play on. No muss, no fuss, no problem, Gus.</p><p>So, the very first thing I did was go online and see if I could get a single, matching bridge pin. Since this guitar was originally purchased in (some year that begins with a 19), it is rather challenging to find original parts. So, rather than waste a whole bunch of time searching for a part that probably costs a quarter to produce, I thought I would look around and see about replacing the whole set of pins.</p><p>A cursory search reveals that you can get a set of pins for between $5 and $10. They’re usually ivory colored and made of plastic. Sounds like just what I need.</p><p>But wait! Wow! There is quite an assortment of other materials and types: synthetic, wood, ivory, bone, Tusq (an artificial bone-like composite material), brass, steel. Slotted tail and unslotted. Plain or with inlays. Sets with matching strap buttons and tuning heads. You could probably have custom ones made with your monogram on it if you were so inclined (and could afford it).</p><p>So, when presented with such an array of choices, the analyst in me puffs up and asks that most fatal of all questions…WHY?</p><p>As a combination computer geek and guitar geek, it is sort of in my nature to examine all aspects of a problem before making a decision. Once I start down this path, I feel like I must truly understand the entirety of the problem space. For instance, if I use different pin materials, will it cause a difference in how tone is passed from the plucked string to the bridge plate? (The answer, for those interested is “yes”.) What would those differences be? And so the search begins.</p><p>Pursuing each line of questions is time-consuming. My lovely artist-ex-rocket-scientist girlfriend refers to it as “going down the rabbit hole”. Once I think I understand the characteristics of bridge pin materials, then the next question that pops up is, what about the material the bridge plate is made of? Do harder woods have different qualities than softer woods? Or metal or ivory? (Again, the answer is “yes”.)</p><p>So now that I understand the pins and the plate, what about how the combinations of materials work together? Do different combinations of pin/plate give different tonal qualities when you’re playing? Again yes.</p><p>Here’s where the overthinking part comes in. Every time you dig into the characteristics, and find a “yes” answer, it almost fractally generates more questions. “Why do some pins have slots? Why do some bridge plates get glued on and others float? Which is better, mahogany or ebony?” At some point you start asking such deep questions that you lose sight of what you were originally trying to accomplish. You can spend a tremendous amount of time accumulating facts that might be fascinating, but ultimately are unrelated to the goal.</p><p>Fortunately there’s a solution to this. It’s so simple it’s almost painful.</p><p>Every time you ask a question that opens up new questions, stop yourself and pose this question:</p><p><strong>Does pursuing this topic get me closer to what I was originally trying to accomplish?</strong></p><p>So, in my case I wanted to play my guitar. What stopped me? The strings were old and worn. What should I do to accomplish my goal and play? Change the strings. What do I need to do to change the strings? I need some new replacement strings (let’s not go down THAT rabbit hole!). Once I have the strings, then I go to the next step, and the next, and the next. When I get to the point of assessing tonal qualities, is that even germane to my goal? Actually it is. I prefer my acoustics to be warm rather than twangy. By understanding the construction of my guitar (ebony bridge plate) I was able to figure out that bone bridge pins would be the best material to get the sound I preferred. Mission accomplished!</p><p>And, since I found ones with mother-of-pearl inlays to match the inlays around the sound-hole and binding, it was a no-brainer…I didn’t have to think at all. Sort of like a car that’s just been washed runs better (wink, wink), a pretty guitar just sounds better.</p><p>Right?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8097270060b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Handmade Noodles and Calculus Are The Same]]></title>
            <link>https://rglowrey.medium.com/how-handmade-noodles-and-calculus-are-the-same-295d7d880843?source=rss-7edf5116d323------2</link>
            <guid isPermaLink="false">https://medium.com/p/295d7d880843</guid>
            <category><![CDATA[humor]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[cooking]]></category>
            <dc:creator><![CDATA[Rick Lowrey]]></dc:creator>
            <pubDate>Thu, 19 Nov 2020 06:23:49 GMT</pubDate>
            <atom:updated>2020-11-19T06:23:49.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Handmade Noodles" src="https://cdn-images-1.medium.com/max/1024/1*b6MYC4tPUfb9SG46w62M3A.jpeg" /><figcaption>Photo by author, Nov. 2020</figcaption></figure><p>Much of the complaining about math that I have heard over the years goes like “I’ll never use this in real life.”</p><p>I beg to differ.</p><p>I was winding down after my work day, sitting at the computer and trying to decide whether playing solitaire was more desirable than looking over sports scores. Delicious scents were wafting from the general direction of the kitchen. I then heard a gentle but insistent summons for my presence. From the kitchen.</p><p>Now, my presence in the kitchen is chiefly in the form of hovering. My girlfriend is a talented cook, and my experience in that direction has mostly been as a competent but “subsistence” level chef. Most of the time she just shoos me away when I hover.</p><p>Sometimes, she enlists my acceptable sous-skills to peel potatoes, slice veggies, or stir something that requires attendance but not actual attention. Infrequently, she asks me to do something that calls for a little dexterity and a large capacity for following directions.</p><p>This was one of those latter occasions.</p><p>In our household, the final use of a leftover rotisserie chicken from a “big box” store is soup stock. In this particular case, the eventual goal was chicken noodle soup. She had spent time cooking down the chicken carcass along with carrot tops, celery bottoms, onion ends and various seasonings and other yummy stuff. While all these tailing were simmering together, she mixed the necessary ingredients to make noodle dough. Noodle dough, I’m told, is very full of gluten. That means that when you roll it out, it tends to “snap back” due to the stretchiness. I even know what I’m talking about here…I’ve watched the Great British Bake-Off.</p><p>At some point she realized that rolling out the dough was something she could delegate to someone with pedestrian but reliable skills. This is where I came in.</p><p>Most dough-rolling I had done in the past was for pie crust. When you roll, it stays put. I’ve done it with reasonable success. With noodles though, it’s more difficult to get a consistent and regular shape like a circle or a rectangle. I mentioned this to my girlfriend before I began this somewhat daunting task. She said that I shouldn’t worry…”It doesn’t have to be perfect.”</p><p>My goal, according to her instruction, was a very flat, roughly rectangular shape. I was able to accomplish this in a very reasonable four minutes. Now it was time to slice. The tool supplied for this was a rolling pizza cutter. The general guideline was to make vertical slices, but don’t worry about being perfect. Her exact answer to my question of “How straight?” was “Straight enough.”</p><p>The important part (went the explanation) was to “get the edges the right width” and then “make sure the interior slices are around the same width”. The next instruction was to slice the resulting long strips of dough in approximately equal bite-sized pieces. My immediate question was, “Your bites or mine?” While she’s not petite, I’m substantially larger than her. She’s a good cook, what can I say.</p><p>Anyway, I asked the question and then the answer struck me…do some of both. Her response was a little more pithy. “Just be approximate. It doesn’t have to be perfect.”</p><p>Since the edges of the rolled-out dough tended to be more wavy than straight, I elected to start at one edge and try to follow the contour, but not too closely. Yes, there were some strangely shaped pieces that looked sort of like a side-view of a just-fed python. But on the whole everything worked out without too much waste. If I had followed the exact contour of the edge to maximize usage of the available dough, then subsequent interior slices would have to be “evened out” as I got toward the center. But, if I had started in the center and tried to create as near perfect cuts as I could, I would have had way more odd shapes when I reached the edge, resulting in more odd shapes to discard.</p><p>I positioned the pizza cutter at the edge, and rather than execute a cut, I called my girlfriend over to fish for some constructive criticism.</p><p>Me: “This one would be too small, right?”</p><p>Her: “Yeah. If you made it a little wider, you could probably salvage more. You can’t smoosh the discarded pieces back together very well, and you don’t want to waste.”</p><p>Me: “So we’re using the entire area of the rolled-out noodles, but we’ll still wind up with some odd shapes where the edges were.”</p><p>I considered for a moment. “If we sliced them thinner, then we could have more consistently shaped noodles and have fewer oddly shaped ones.”</p><p>Her: “Yeah, but then they aren’t bite sized any more”</p><p>Me: “So we have to balance eatability with regularness?”</p><p>Her: “That’s not a word. But yes, something like that.”</p><p>Me: “So we’re optimizing eatability (yes it’s a word, dammit, let me finish) against waste!”</p><p>Her: “Um, if you spend all your time optimizing, we’ll never have any soup.”</p><p>Me: “Ah! So it’s actually an integration problem in three dimensions! Maximizing consistent size for eatability, minimizing waste for oddly shaped or too small bits, and constrained by time!”</p><p>Her: “Well, yeah. You didn’t see that before?”</p><p>She slowly shook her head with amused exasperation (as she so often does when I over-analyze things). “Alright, so you found an optimization problem. Good for you. However, you didn’t take into account that the original slice width was not only constrained, but irregular. Also, the slices weren’t straight. That adds further to the irregularity. So, your integration analogy starts to fall apart. Integration depends on the consistency and reproducibility of the slice width parameters. And, frankly, this sort of integration only works in two dimensions. So your rollout of the dough introduced a third dimension of variability!”</p><p>Yes, she is correct. Did I mention that my girlfriend used to work at JPL? She was a real-life rocket scientist.</p><p>However, it IS possible to do integrations in more than three dimensions. It makes your head spin, but it can be done.</p><p>In my defense, I did a really good job of rolling out that dough. At least I thought so.</p><p>In closing, I would assert that noodles and calculus really ARE the same. One is an illustration of the other, perfect in it’s imperfection. We use calculus to approximate an answer to a degree where the difference between the approximation and our desired outcome are indistinguishable. Further refinement becomes an academic exercise, with little practical value.</p><p>We cut handmade noodles to get just enough regularity for eatability and to identify a particular “feel”, but not enough regularity to make it feel artificially perfect. Eatability is definitely a variable that can’t be completely controlled for. I suppose that this explains at least in part why there are so many different varieties of noodle.</p><p>And so, we now have a true example of how math applies in real life. The soup delicious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zO9jkml3NjJXpyXRRRqEWw.jpeg" /><figcaption>Calculus soup. Photo by author, 2020.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=295d7d880843" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Visualize Eleven Dimensions]]></title>
            <link>https://rglowrey.medium.com/how-to-visualize-eleven-dimensions-44a07789d98a?source=rss-7edf5116d323------2</link>
            <guid isPermaLink="false">https://medium.com/p/44a07789d98a</guid>
            <category><![CDATA[humor]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[string-theory]]></category>
            <dc:creator><![CDATA[Rick Lowrey]]></dc:creator>
            <pubDate>Mon, 09 Nov 2020 06:55:07 GMT</pubDate>
            <atom:updated>2020-11-11T16:33:39.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*B7eP2D7lj7MHs-gqL_AC7g.jpeg" /><figcaption>Yaquina Bay Bridge, 2017, Newport OR. Photo by Author</figcaption></figure><p>One very offputting thing about trying to use “string theory” and “m-theory” to explain the behavior of the “physical universe” is that mathematicians and physicists talk about their formulas and equations in 10 or 11 dimensions (depending on who you listen to). Most people who talk about the “real world” pretty much limit themselves to four…width, length, height, and duration (a.k.a. time). If you get much further than four, most people can’t visualize it.</p><p>Let’s show an example of this by starting with the “geometry” version to see how most people were taught to visualize dimensions.</p><p>We start with the very simple ONE dimension. It’s just a line. It goes forever THAT way and forever the OTHER way. It’s a little unwieldy to visualize with, so for our purposes let’s take a short section of the line so we can easily think with it. It has a length, that’s about it.</p><p>Now, when you add a SECOND dimension, you can create concepts like “perpendicular”. Take two identical segments and arrange them so that the end of one connects with the middle of the other, and the angles on either side are equal (Figure 1). It’s commonly represented with a little “mini-square” in the corner where the lines meet. Many of us also recognize “Ninety degrees”. It is also referred to as “right-angles”.</p><pre>                               |<br>                               |<br>                               |<br>                               |<br>                               |<br>                               |<br>                               |<br>                               |---<br>                               |  |<br>                ----------------------------------<br>                Fig 1.  Perpendicular Line Segments.</pre><p>You see how complicated this is getting already? All this formality and rigor. I just want a square corner.</p><p>Alright, back to our dimensions. If we take our line segment and extend it an equal distance PERPENDICULAR in the SECOND dimension, we wind up with a square. It is a basic shape in two dimensions. It has square corners. It has a width and a height.</p><pre>                    -------------------------         <br>                    | ^                     |<br>                    | |                     |<br>                    | h                     |<br>                    | e                     |<br>                    | i                     |<br>                    | g                     |<br>                    | h                     |<br>                    | t                     |<br>                    | |                     |<br>                    | V   &lt;-- width --&gt;     |<br>                    -------------------------<br>                        Fig 2.  A square.</pre><p>Now, if we add a THIRD dimension, where can it go? If we take our square and lay it flat, then smart money says “up”. So, if we extend our square PERPENDICULAR to its existing two dimensions, we wind up with a CUBE. Everyone knows what a cube is (snarky jokes about offices aside). You can visualize it.</p><pre>                        -------------------------         <br>                       /|                      /| ^<br>                      / |                     / | |<br>                     /  |                    /  | |<br>                    -------------------------   |    <br>                    |   |                   |   | U<br>                    |   |                   |   | P<br>                    |   |                   |   | <br>                    |   |                   |   | |<br>                    |   |                   |   | |<br>                    |   |                   |   | V<br>                    |   |                   |   |<br>                    |  / -------------------|--/<br>                    | /                     | /<br>                    |/                      |/<br>                    -------------------------<br>            Fig 3.  A two-dimensional representation of a cube.<br>            I know, the perspective is weird.  Go with me on this.</pre><p>So we have now created a cube. We want to visualize a FOURTH dimension. Hm…where can it go? In what direction can it be “perpendicular”? This is where the use of physical dimensions goes off the rails for most people. However, recognize from above that the picture in figure 3 is NOT really a cube. It’s a two-dimensional REPRESENTATION of a cube. We took our square, made a copy of it, and connected each VERTEX (place where lines meet) with its LIKE VERTEX. This gives us the illusion of three dimensions when we’re really only using two.</p><p>So, if you take two actual cubes, and INTERLOCK them, then connect all 8 vertices with their LIKE vertices, you can get a three-dimensional representation of a four-dimensional “cube”. Some people call this a “tesseract”. I don’t know why…google it.</p><pre>                -------------------------         <br>               /|\                     /|\  <br>              / | \                   / | \ <br>             /  |  \                 /  |  \<br>            -------------------------   |   \<br>            |\  |    \              |\  |    \ <br>            | \ |     \             | \ |     \<br>            |  \|      \            |  \|      \<br>            |   \       ------------|---\--------         <br>            |   |\     /|           |   |\     /|<br>            |   | \   / |           |   | \   / |<br>            |   ---\-/--------------|----  \ /  |<br>            |  /\   ----------------|--------   |     <br>            | /  \  |   |           | /  \  |   |<br>            |/    \ |   |           |/    \ |   |<br>            -------------------------      \|   |<br>             \      |   |            \      |   |<br>              \     |\  |             \     |\  |<br>               \    | \ |              \    | \ |<br>                \   |  \|               \   |  \|<br>                 \  |  / ----------------\--|--/<br>                  \ | /                   \ | /<br>                   \|/                     \|/<br>                    -------------------------<br>                    <br>          Fig 4.  A tesseract.  <br>          Or, rather, a two-dimensional representation of <br>          a three-dimensional representation of a tesseract.<br>          Google for better pictures if you can&#39;t visualize this.</pre><p>However, this doesn’t really open the door to understanding how to extend dimensions even further. To get around this, some have tried to use “time” as the fourth dimension. I prefer to think of it as “duration at a position”. We measure this “fourth dimension” by noting where in THREE dimensions an object is, and how it changes over TIME. Anyone who has ever caught a ball or jumped into a pool or driven a car has seen this in action. You are able to follow the path of an object as it goes from HERE to THERE, tracing its path through TIME as it moves. Another two-dimensional representation analogy is a video game or a computer screen. What you see on the screen is in two dimensions. You get to see the objects there simulate three dimensions with tricks of perspective, overlapping, and such when the character (or car, or plane, or spaceship) has moved with respect to a background. As it changes simulated position over time, thus it simulates a fourth dimension.</p><p>However, these are all just simulations. How about in the real world? Which direction would you point to show the way to “perpendicular” to the other three dimensions. And this is where it all goes off into the realm of “Huh?”. How would you visualize a FIFTH dimension? A “spinning tesseract”? Where would it go?</p><p>So, as a public service and a way to oversimplify, I have come up with a method to help all us other regular joes and janes out there wrap our respective heads around what 10 or 11 dimensions means. I’ll put it in the context of something we’re all familiar with…letters printed on a page. It is a trick used by computer programmers and data scientists to group data into meaningful buckets, to look for patterns where none might be obvious.</p><p>Let us begin with the most simple dimension. It is the equivalent of a geometric line…a typed line of text on one sheet of paper. It doesn’t matter what letters…they might be words, or numbers, or a bunch of random characters that look like this: #$%^&amp;*. It may look like cartoon swearing but it isn’t. Please trust me with this.</p><p>Next, we’ll go to two dimensions: imagine the same line of %^&amp;*()@#$%^&amp; characters typed on an entire page. You can see that if you drew a line vertically on the page, each letter or symbol the line passed through would be in the “same position” in the context of this second dimension. So, character number 3 in line 1 might be “x”, but character number 3 in line 2 might be “@”. And in line 3, it might be “8”, and so on. Each character is distinct, but it occupies the same position in a different line.</p><p>Three Dimensions: imagine the same page repeated as an entire bound book. How would you represent getting each letter “in the same position” in that dimension? Easy. Close the book, then get a drill press. Every page would be pierced at the same spot. So each letter the hole passes through is “in the same position” with respect to the page it’s on. Or, it would have been if we hadn’t destroyed them. Just think about the letter immediately to the right or left if destruction bothers you.</p><p>Note: In real life, this method wouldn’t really work. In a “real book” each page is printed on both sides. It’s cheaper that way. So, if each page was read left-to-right, then the drill press hole would show in a different orientation to how we’re trying to think.</p><pre>          -------------          -------------<br>          |1234567890 |          |1234567890 |<br>          |        X  |          |  X        |<br>          |           |          |           |<br>          |           |          |           |<br>          |           |          |           |<br>          |           |          |           |<br>          |           |          |           |<br>          |           |          |           |<br>          |           |          |           |<br>          -------------          -------------<br>               Front            Back (flipped over)</pre><p>So let’s just pretend that each page is printed on only one side. Maybe we could put a pretty watercolor picture on the other side, like a Beatrix Potter book. But I digress.</p><p>Four Dimensions: imagine the exact same book 10 times on one shelf. How would you represent getting each letter “in the same position” in that dimension? Here’s how.</p><p>Think about the first book. Now think about page 53. Go think about the 10th line, the fourth letter in from the left. Got it? Anybody who’s every looked up a word in a dictionary has sort of done this. Please tell me you’ve used a dictionary instead of googling or wiki-ing everything. I think wiki-ing is a word. Maybe I’ll google it.</p><p>Anyway, once you’ve located your letter, get the NEXT book from the shelf. Again, go to page 53, line 10, letter 4 from the left. Now, get the next book, do it again, and then the next book…you get the picture. Each of the selected page/line/letters is IN A STRAIGHT LINE in your new fourth dimension. You couldn’t really use a drill press for this case.</p><p>Five Dimensions: imagine the exact same shelf from the 4-dimension example, stacked 5 high as a bookshelf. Maybe oak. Or mahogany. I’ve always liked mahogany. Remember, we’re trying to visualize here. So if you pick the fourth book from each shelf, then open each book to page 53, line 10, letter 4.</p><p>Six Dimensions: imagine the exact same bookshelf stood side by side as a library aisle. Mahogany would probably be too expensive in that case. Maybe just some pine or metal. Anyway, on each bookshelf, go to the second shelf, pick the fourth book, open each book to page 53, line 10, letter 4.</p><p>As we get further up in the dimensions, it gets harder to identify “straight lines”. So, I’ll give you some tricks for how to visualize the overall intent of the dimension, and leave it as an exercise for the bored or pedantic to figure out how to locate “letters in the same position” in each example.</p><p>Seven Dimensions: imagine the same aisle from dimension six, back to back with other aisles in a room. Think of a school library. Shhhh.</p><p>Eight Dimensions: imagine the same room side by side with other rooms on an entire floor. Maybe it would look like Powell’s in Portland. Look it up.</p><p>Nine Dimensions: imagine the same floor stacked 5 floors high as an entire public library. Again, SHHHHH.</p><p>Ten Dimensions: imagine the same entire library beside other libraries on the same street. This should be easy to do…just think of that street in every town that has all the fast-food restaurants. Now imagine them as libraries.</p><p>Congratulations! You are now competent to understand string theory. But wait, there’s more!</p><p>Eleven Dimensions: imagine the same street identically reproduced in another city. We already got to imagine that every city has a fast-food restaurant street…change them ALL to libraries. See? Easy! Good luck finding french fries, though.</p><p>Congratulations! You are now competent to understand m-theory. Please publish your findings for the rest of us.</p><p>And yet, we can even go higher:</p><p>12 dimensions: imagine the same city from 11 dimensions along with other cities in the same country<br>13 dimensions: imagine the same country with other countries on the same continent<br>14 dimensions: imagine the same continent with other continents on the same planet<br>15 dimensions: imagine the same planet with other planets in the same star system<br>16 dimensions: imagine the same star system with other star systems in a constellation<br>17 dimensions: imagine the same constellation with other constellations in a spiral arm<br>18 dimensions: imagine the same spiral arm with other spiral arms in the same galaxy<br>19 dimensions: imagine the same galaxy along with other galaxies in a local group<br>20 dimensions: imagine the same local group with other local groups in a cluster<br>21 dimensions: imagine the same cluster with other clusters in a supercluster</p><p>And so on, and so on. Dimensions without end, as far as your imagination can take you. Enjoy! And, if you conquer the cosmos with your new-found understanding of dimensions, please be kind to the citizens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44a07789d98a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fun with Python: Doing Real Work With Excel Spreadsheets]]></title>
            <link>https://rglowrey.medium.com/fun-with-python-doing-real-work-with-excel-spreadsheets-2b6884651595?source=rss-7edf5116d323------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b6884651595</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spreadsheets]]></category>
            <category><![CDATA[data-wrangling]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Rick Lowrey]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 05:19:04 GMT</pubDate>
            <atom:updated>2020-08-15T05:19:04.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5dug9CYx90OXa8CiunGTA.jpeg" /><figcaption>Vineyard View, Gaston OR; Photo by author, 2017</figcaption></figure><p>I recently had a request from my lovely ex-engineer-now-artist girlfriend (yes, the same girlfriend) that she wanted to update some Cost-Of-Goods-Sold values in an Excel spreadsheet based on the value of another column in the same row.</p><p>Now, before you say “Why not just run a macro?”, let me explain. No, let me sum up. The spreadsheet was from an outside vendor source, and had to be re-downloaded periodically from the same source. There were about 5000 rows of data. The reference values were based on a limited number of items (about 50 different possibilities) each of which was associated with a specific price, which could change. And, a replacement file had to be re-uploaded to the same place once her changes were made. So, having a separate file to maintain her reference prices would be easier and cleaner in the long run.</p><p>As I had mentioned in my last article “<a href="https://medium.com/@rglowrey/some-basics-and-some-real-work-using-google-app-script-e80cd467f334">Some Basics And Some Real Work Using Google App Script</a>”, I had just finished a Python course that had the usual read-a-csv-write-json simplistic scenarios. Feeling very confident in my ability to figure out anything that came my way, I hitched up my britches and pitched in.</p><p>Of course the first thing to decide was, how was I going to read the data? I asked her to save the Excel file to a flat CSV. That way I could use my newly-acquired Python skills to slurp the data in, twiddle the column, then write out a new CSV all ready for her to import into Excel. Seems pretty easy, right?</p><p>The first roadblock was when I tried to read the CSV file she had exported. Python complained that it found characters that weren’t UTF-8 encoded. After a little sniffing around on the web, I found a reference to a handy library called “<a href="https://pypi.org/project/chardet/">chardet</a>” to help detect what character set this thing was in. However, there were very few examples that matched my requirement, so I delved into the documentation. I spent a goodly amount of time playing with it, but the best I could do was to get a low-confidence response that the file was in Thai. Let’s just say that I went down the code page/charset rabbit hole a lot further than I intended (or should have…but it was so interesting!). There had to be an easier way.</p><p>Next, I researched into whether there were any libraries that were specifically designed to read Excel files. It was no surprise that there were several. The first I tried was “<a href="https://pypi.org/project/xlrd/">xlrd</a>”, and it worked great. Very simple to use, I was able to treat the incoming rows as a list with attributes, it looked promising. However, I had an issue where one of the columns I was interested in had come out as a formula rather than the actual value. Not a winner. Additionally, I could not update the data. I’d have to use a separate library called “<a href="https://pypi.org/project/xlwt/">xlwt</a>” to create an entirely new object and populate THAT so I could write out the file. Again, there had to be an easier way.</p><p>I finally wound up using a library called “<a href="https://pypi.org/project/openpyxl/">openpyxl</a>”. It was possible to set an option when I opened the file to load the workbook, access the sheet and force the formulas to evaluate and supply the actual end value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e45cefe65ae4f7e9ca88ce75a46ceee/href">https://medium.com/media/0e45cefe65ae4f7e9ca88ce75a46ceee/href</a></iframe><p>Huzzah! It looked like a viable approach.</p><p>Now, after I had successfully proven to myself that I could read the spreadsheet file, I concentrated on how I was going to provide the “decode” values. As in, I had to use the value in one spreadsheet column, do a lookup, and provide a value to put into a different spreadsheet column. Sounds like it’s tailor-made for JSON.</p><p>Fortunately, JSON is pretty simple to read and load into a dictionary object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/028b9a3171c8b4d2234becfebc70a1f3/href">https://medium.com/media/028b9a3171c8b4d2234becfebc70a1f3/href</a></iframe><p>Here’s a subset of the entire JSON file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be17c6c008f7225ce848066b05c1b818/href">https://medium.com/media/be17c6c008f7225ce848066b05c1b818/href</a></iframe><p>Once you have both of those objects, comparing them is a pretty simple iteration through the worksheet object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb8aa3e9171aebeb94c24c2743eeeca2/href">https://medium.com/media/fb8aa3e9171aebeb94c24c2743eeeca2/href</a></iframe><p>In this case, I wanted to determine whether or not there was a match between the value in a specific column, and the JSON values I had read into a dictionary from the other file. Python has a handy “in” keyword for use with dictionaries to see if a key exists:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f176905daa92c774789faebfb27d0921/href">https://medium.com/media/f176905daa92c774789faebfb27d0921/href</a></iframe><p>So, I determined I could read a spreadsheet, read a JSON file with lookup values, compare the values and update my rows in memory from the lookup. Great!</p><p>From a workflow standpoint, having hard-coded file names wasn’t really the best option. Keeping in mind that the lookup JSON data was supposed to be “cost of goods sold” for a set of products, it was entirely likely that the values would change over time, so I wanted to be able to have an archive. And, the spreadsheet that was supplied would likely have a different name each time it was provided. So, I wanted to be able to supply command-line arguments for both of these. It turns out there’s a wonderful Python library called “<a href="https://docs.python.org/3/library/argparse.html">argparse</a>” that gives you a ton of flexibility.</p><p>Creating a parser is pretty simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69655592396aaf6f32ffed1d571695d6/href">https://medium.com/media/69655592396aaf6f32ffed1d571695d6/href</a></iframe><p>The “description” parameter supplies some text that will display if you run the script with a “-h” argument. More on that later.</p><p>Once you have the parser object, you can pretty much add as many arguments as you like. You have the option of setting them as required, whether there’s a default value, and a host of others (here’s a link to the documentation).</p><p>The first argument I wanted was to specify where to find the prices file. The statement looked like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/befbeb82455e412ba6899466ebea17f1/href">https://medium.com/media/befbeb82455e412ba6899466ebea17f1/href</a></iframe><p>The first two parameters are what can be used on the command line as either a short version or a long version. Some people like to use the more verbose one for readability and self-documentation. The “help” parameter supplies some text that will display if you run the script with a “-h” argument. The “nargs=” parameter indicates that there could be zero or one value supplied. The “default” parameter supplies the value to be used if the parameter/value is not supplied on the command line.</p><p>Next, I wanted to give the name of the input spreadsheet. This one would have to be supplied, not optional and no default value would be accepted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd17da6caa890024c176ccb044387375/href">https://medium.com/media/fd17da6caa890024c176ccb044387375/href</a></iframe><p>Finally, I wanted to be able to test this without necessarily generating an output spreadsheet, so I needed a “flag” style parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ed96eb3151fd67621d313d6a9aa9d84/href">https://medium.com/media/9ed96eb3151fd67621d313d6a9aa9d84/href</a></iframe><p>The “action” parameter in the above tells the parser to basically hold a boolean value for later use.</p><p>But how to access these values? First, you create an object variable to hold them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b47e76ead2397a2409bb3bc50721f8b7/href">https://medium.com/media/b47e76ead2397a2409bb3bc50721f8b7/href</a></iframe><p>Once you have this object, you can reference the various values using “dot” notation. For example, here’s how we open the JSON file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb9bea17cdf75ec6b1ff089f73fb15ac/href">https://medium.com/media/cb9bea17cdf75ec6b1ff089f73fb15ac/href</a></iframe><p>Notice that the reference after the “dot” is the same as the verbose argument name from above. Depending on what kind of value you supply, you can use these as numbers, as strings, or as booleans:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b56b6358144d99323b8f9e439a1f488/href">https://medium.com/media/8b56b6358144d99323b8f9e439a1f488/href</a></iframe><p>So, once I determine that this is not a test, I can save the on-memory workbook with a new name that I assemble from today’s date and time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dca528b97bd1d4d15f7ddcc81ffc6248/href">https://medium.com/media/dca528b97bd1d4d15f7ddcc81ffc6248/href</a></iframe><p>Now, since I want to be able to run this script and get an idea of how many prices are actually being updated, I put in some counters and a print statement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/324fe07bbaa5e3f2d237c145521adb48/href">https://medium.com/media/324fe07bbaa5e3f2d237c145521adb48/href</a></iframe><p>This is the end of the script.</p><p>However, from a workflow standpoint, there are a couple of other things you may want to do.</p><p>When you execute this from the Linux command line with the — help argument, you get this:</p><pre>rick@mylinuxmint: ~$python3 setCOGS.py --help<br>usage: setCOGS2.py [-h] [-p [PRICESFILE]] -i INPUTFILE [-t]<br>Add COGS to a products spreadsheet from a prices file.<br>optional arguments:<br> -h, --help show this help message and exit<br> -p [PRICESFILE], --pricesfile [PRICESFILE]<br> Prices file. Must be valid json.<br> -i INPUTFILE, --inputfile INPUTFILE<br> Product Prices file. Must be valid .xlsx file.<br> -t, --test Allows you to run without generating a new file.</pre><p>If you exclude any parameters you get this:</p><pre>rick@mylinuxmint: ~$python3 setCOGS.py<br>usage: setCOGS.py [-h] [-p [PRICESFILE]] -i INPUTFILE [-t]<br>setCOGS.py: error: the following arguments are required: -i/ - inputfile</pre><p>This is expected, since we said the — inputfile parameter is required above.</p><p>If you specify all the arguments, it looks like this:</p><pre>rick@mylinuxmint: ~$python3 setCOGS.py -p cogsprices.json -i cogs-8–12–2020.xlsx -t<br>Starting at: 08/14/2020 19:11:39<br>Ended at: 08/14/2020 19:11:39<br>File NOT saved<br>Changed 1148 out of 4639 rows.</pre><p>So it gives us when we started, when it ended, that the file was NOT saved since this is a test, and how many rows would have been changed.</p><p>Finally, when we do this for real:</p><pre>rick@mylinuxmint: ~$python3 setCOGS.py -p cogsprices.json -i cogs-8–12–2020.xlsx<br>Starting at: 08/14/2020 19:13:26<br>Ended at: 08/14/2020 19:13:27<br>File saved as new_file_20200814191327.xlsx<br>Changed 1148 out of 4639 rows.</pre><p>And, voila. I have a file I can send back to my girlfriend for re-uploading, and I’ve saved her a bunch of work.</p><h3>Conclusion</h3><p>Python is great for manipulating data, and the plethora of libraries means you probably won’t have to “re-invent the wheel” when you need something specific done. Our particular script accepts parameters, it is documented, it runs fast, and it’s simple to use. This is a classic scenario of data wrangling that turns into something we could consider “production ready”. Here’s the complete script…only 30 lines, including print statements!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88e5a3726b069ef9752176b49c8dd7e2/href">https://medium.com/media/88e5a3726b069ef9752176b49c8dd7e2/href</a></iframe><h3>Coda:</h3><p>Later that evening, my lovely ex-engineer-now-artist girlfriend said “Oh, no! Oh dear! I have some price changes already, and some new products to include!”</p><p>“Not to worry, my dear…all I have to do is include them in the cogsprices.json file and run it again!”</p><p>&lt;add rows to the JSON file, re-run the script&gt;</p><p>“My hero!”</p><p>Okay, so maybe it didn’t really quite happen like that, but you get the idea. We’ve abstracted the things we KNOW will be dynamically changing so our script doesn’t have to change. Plus, we’ve included some handy help to give us a hint about how to run this script later on (after we’ve forgotten how to run it). And, in a pinch, we could even supply this script to someone else so they could do it by themselves and we wouldn’t ever have to touch it again.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b6884651595" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some Basics And Some Real Work Using Google App Script]]></title>
            <link>https://rglowrey.medium.com/some-basics-and-some-real-work-using-google-app-script-e80cd467f334?source=rss-7edf5116d323------2</link>
            <guid isPermaLink="false">https://medium.com/p/e80cd467f334</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[google-app-script]]></category>
            <category><![CDATA[google-drive]]></category>
            <dc:creator><![CDATA[Rick Lowrey]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 03:26:56 GMT</pubDate>
            <atom:updated>2020-06-18T03:26:56.145Z</atom:updated>
            <content:encoded><![CDATA[<p>A short flight into Cloud Computing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SLOyyb6XwiE8xQ7Nn-BJuQ.png" /><figcaption>Del Mar Bluff, March 2017</figcaption></figure><p>I recently had a request from my lovely ex-engineer-now-artist girlfriend that she wanted to rename a bunch of image files on her Google Drive to include the dimensions of the image in the filename. After some discussion, we decided we didn’t really need to keep the original files intact. Her Google Drive was being fed by a web site where an artist could upload images, and those images were shoved into a sub-folder named as a date/time stamp. Later, she would manually check the contents of new directories to make sure naming standards were followed, then change the folder name to the Artist’s name. Seems pretty simple. We weren’t converting the images, or resizing, or anything.</p><p>I had just completed a Python course where one of the exercises was extracting EXIF (Exchangeable Image File Format) properties from a bunch of image files. I figured that getting simple pieces of metadata would be a snap. Couple that with my recent certifications in Google Cloud Platform and I was pretty confident I could knock something out for her quickly.</p><p>One thing to note is that Google App Script is more like JavaScript than Python. Not a worry for me, since I’ve been dabbling in JS for a few years. Google App Script can be embedded in several of the Google Docs document types, or created as stand-alone functions. I chose to write this stand-alone, since this particular use case was something that manipulated files rather than content. So, the beginning was going to Google Drive, clicking the colorful plus sign, clicking on “More…” and creating a new Google Apps Script. I suggest you give your project a suitable name by clicking on “Untitled project” and typing something…well…suitable. The default filename is “Code.gs”, but you might choose to change that too. I didn’t. Also, the pre-populated function name is “myFunction()”. You will probably want to change that as well. Based on my research and seeing what others had done, I chose “start()” as my function name since it’s a batch process that does lots of iterating.</p><p>The first step in manipulating a bunch of files is (obviously) to be able to get a list of the files. Google Drive App Script allows you to do this through a class object called DriveApp. It has several useful methods, but the specific one I wanted was DriveApp.getFoldersByName. It takes a string parameter that equates to the name of the folder. It would provide the starting point for our job.</p><pre>var startFolderName = “Artist Image Submission Form”;<br>var startFolder = DriveApp.getFoldersByName(startFolderName).next();</pre><p>Please notice the method name is getFolder<strong><em>SSSS</em></strong>byName. The object returned by this method is something called a FolderIterator. It is defined as a LIST of folder objects. Even if there is only one folder you’re interested in, it will return a list containing one object. So, in order to get an actual folder, you have to fetch the first object in the list. Depending on your use case, it might be preferable to use some sort of loop structure like “for” or “while”. For my purposes, since I knew I only had one folder to work with I just chained the call with “.next()” to get the necessary object.</p><p>Okay, I have my folder where I want to iterate through all the subfolders. Now, I need to actually get the subfolders. Conveniently, there’s a method for that called getFolders().</p><pre>var folders = startFolder.getFolders();</pre><p>Once I have my list of folders to iterate through I have to actually get a list of files. However, I didn’t want every file. I only wanted image files. So, for each folder in my list I used the “getFilesByType” function to return an iterable list of files.</p><pre>var files = folder.getFilesByType(MimeType.JPEG);</pre><p>After quite a bit of searching, I found the specific list of <a href="https://developers.google.com/apps-script/reference/base/mime-type">available MIME types</a>. There’s even a nice little example script that gives you a little idea of how to get some information about images. The bad news is, the example script didn’t show how to get at the information I was looking for. I specifically needed image dimensions (height and width) to append to her image file names.</p><p>But wait a second, here. This function will only get files of ONE type of image! What if some artist decides he doesn’t like JPEG and wants to upload a PNG file? Or a BMP? Fortunately I was able to find an example <a href="https://www.labnol.org/code/19982-search-files-in-google-drive">here</a> that helped me. I was able to adapt his example like so:</p><pre>var mimeTypes = [MimeType.JPEG, MimeType.PNG]<br> <br>for (var i = 0; i &lt; mimeTypes.length; i++) {<br>var files = folder.getFilesByType(mimeTypes[i]);<br> .<br> .<br> .<br>}</pre><p>Please notice that the members of the list are actually values from the MimeType Enum. Do not mistake these for string values to pass in (I did, and it took me a few minutes to figure out why all my files were being ignored).</p><p>Next I needed to find out how to get at the details available from the metadata properties. I discovered during my Python class that not every image will have an EXIF block to look at. How to deal with that is beyond the scope of my article today, but I did include a ternary test in the getMetaData function to at least not return null in case the EXIF block didn’t exist. For our purposes, we assume EVERY image will have some metadata, specifically the pixel dimensions I needed for my task. I did a bunch of searching and finally found <a href="https://stackoverflow.com/questions/30582284/how-to-extract-exif-data-from-jpeg-files-in-drive">what I was looking for</a>. That post had a link to <a href="https://developers.google.com/drive/api/v2/reference/files">this page</a> that gave me everything I needed to tease out the bits I required.</p><pre><br> .<br> .<br> .<br>while(files.hasNext()) {<br>var file = files.next();<br>var metaData = getMetaData(file.getId());<br>var width = (metaData == {}) ? 100: metaData.width;<br>var height = (metaData == {}) ? 100 : metaData.height;<br> .<br> .<br> .<br> }<br>}</pre><pre>function getMetaData( fileId ) {<br> var file = Drive.Files.get(fileId);<br> var metaData = file.imageMediaMetadata;<br> return metaData == null ? {} : metaData;<br>}<br></pre><p>Next up, I needed to pick apart the original file name so I could cobble together the interesting pieces into a new file name. I used the tried-and-true JavaScript “slice” method to get what I needed using the indexOf method to get the index of the file separator. Once I had those parts, I was able to fashion the new name by simple concatenation.</p><pre>var fullName = file.getName();<br>var newName = fullName.slice(0, fullName.indexOf(“.”));<br>var newExt = fullName.slice(fullName.indexOf(“.”) + 1);<br>var newFullName = newName + ‘-’ + width + ‘x’ + height + ‘.’ + newExt;<br></pre><p>Could I have done it more elegantly? Yeah, probably. But I was getting close to the finish line so I let it pass for now.</p><p>We’re not quite finished. We still need to do the actual “renaming”. Mercifully, there is a function to do this: setName(). Once you have a well-formed string (or maybe a poorly formed string…I didn’t really test that part) do this:</p><pre>file.setName(newFullName);</pre><p>Hold everything… What if I had already processed this folder? I would wind up with file names like “SassyCat-400x200–400x200–400x200.jpg”. That wouldn’t do. So, at the end of processing a folder, I just create a little “processed.txt” file that tells the function we have no work to do here (“These aren’t the files you’re looking for…you can go about your business…move along…”).</p><pre>while (folders.hasNext()) {<br> var folder = folders.next();<br> Logger.log(“ folder: %s”, folder);<br> if (folder.getFilesByName(“processed.txt”).hasNext() == false) {<br> .<br> .<br> .<br>}</pre><p>Here’s my full script, in complete order:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cfd7b44bdf57c6a4483b3beb7e4ea6f/href">https://medium.com/media/3cfd7b44bdf57c6a4483b3beb7e4ea6f/href</a></iframe><p>Oops…one other little thing.</p><p>When you go to run this script, it’s going to complain that “Drive.Files….” is not a valid object. It is important that you enable the necessary API’s in your project.</p><p>From your script editor at script.google.com, look for the “Resources” menu item, and click on “Advanced Google services…”. Scroll down the list until you find “Drive API” and click on the slider to set it to “on” and click OK. That will give you the necessary services to allow you to run this script.</p><p>Second “one other little thing”. In my Logger.log function calls and my Utilities.formatDate calls, I use the explicit timezone for formatting. I didn’t do more research to see if I could make this dynamic (as in, the time zone of the user of the script). If you choose to do so, please post a comment. For the rest of us, here’s a handy <a href="http://joda-time.sourceforge.net/timezones.html">reference site</a> containing all the official timezone names.</p><p>Third “one other little thing”. Since this is a batch process, it’s probably reasonable to schedule it. You do this using Triggers. From your script editor at script.google.com, click on the Clock icon in the task bar (or on the “Edit” menu item, and “Current project’s triggers”), then click “Create a trigger”. You can select a host of options which I won’t go into. The most important thing is to select the function to run. I chose the “start” function, event source Time-driven, Day timer, 3am to 4am time of day (GMT-07:00). Your requirements may vary.</p><p>The happy end of my story is that the function runs as my girlfriend wants, once per day. It gives her exactly the result she is looking for, and I’m now a hero. Well, maybe “hero” is a bit of exaggeration. But she’s pleased that I’ve helped save her probably a dozen hours of tedious manual work.</p><p>I hope this article is helpful to someone out there. Happy clouding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e80cd467f334" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>