<?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[Spring Engineering - Medium]]></title>
        <description><![CDATA[Tales from the team that builds @Spring - Medium]]></description>
        <link>https://medium.com/spring-engineering?source=rss----531ed8344feb---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Spring Engineering - Medium</title>
            <link>https://medium.com/spring-engineering?source=rss----531ed8344feb---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:51:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/spring-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Manipulating Dates and Time Zones in iOS Development]]></title>
            <link>https://medium.com/spring-engineering/manipulating-dates-and-time-zones-in-ios-development-2f0e0d0e93be?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/2f0e0d0e93be</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[date]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[time]]></category>
            <dc:creator><![CDATA[Alan Wang]]></dc:creator>
            <pubDate>Mon, 01 Oct 2018 20:54:06 GMT</pubDate>
            <atom:updated>2018-10-01T20:52:08.983Z</atom:updated>
            <content:encoded><![CDATA[<p>There are two kinds of developers in the world: those whose eyes twitch at the mention of time zones, and those who still think <a href="http://falsehoodsabouttime.com/">there are always 24 hours in a day</a>.</p><p>Time and time zones is perhaps one of the most deceptively simple, yet infuriatingly complex things you will have to deal with as a developer. Case in point, check out this lovely history lesson from Apple’s <a href="https://developer.apple.com/documentation/foundation/nscalendar">documentation</a> of their NSCalendar class.</p><blockquote>The Gregorian calendar was first introduced in 1582, as a replacement for the Julian Calendar. According to the Julian calendar, a leap day is added to February for any year with a number divisible by 4, which results in an annual disparity of 11 minutes, or 1 day every 128 years. The Gregorian calendar revised the rules for leap day calculation, by skipping the leap day for any year with a number divisible by 100, unless that year number is also divisible by 400, resulting in an annual disparity of only 26 seconds, or 1 day every 3323 years.</blockquote><blockquote>To transition from the Julian calendar to the Gregorian calendar, 10 days were dropped from the Gregorian calendar (October 5–14).</blockquote><blockquote>After the Gregorian calendar was introduced, many countries continued to use the Julian calendar, with Turkey being the last country to adopt the Gregorian calendar, in 1926. As a result of the staggered adoption, the transition period for countries at the time of adoption have different start dates and a different number of skipped days to account for the additional disparity from leap day calculations.</blockquote><p>In this post, we will cover:</p><ul><li>An introduction of Apple’s Date and Calendar classes, and how the two work together to model time.</li><li>How to manipulate dates and time zones using DateComponents (with a brief aside about DateFormatter).</li><li>How and why you might use these classes.</li><li>Some problems you might run in to.</li></ul><p><strong>Note:</strong> The Date, Calendar, and DateComponents classes are Swift classes that bridge to the Objective-C classes NSDate, NSCalendar, and NSDateComponents respectively. This post will use the Swift classes, however at the time of writing, the Objective-C documentation is richer in detail, so links to Apple documentation will be to the Objective-C classes.</p><h3>How Apple Models Time</h3><p>Apple’s framework uses two classes to deal with the concept of time: Date and Calendar.</p><h4><a href="https://developer.apple.com/reference/foundation/nsdate">Date</a></h4><p>The Date class is terribly named — it doesn’t actually correspond to a “date” such as August 8th, 2014. Instead, it represents a <strong>point in time</strong>, defined by the time interval from an absolute reference point. You can think of it as the number of seconds that have elapsed since (or before) that reference point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0-lTqDJCV3_YoEjwaIVwg.png" /><figcaption>Figure 1: A Date object represents a point on a timeline. It is defined by its distance from an absolute reference point.</figcaption></figure><p>Date is independent of calendar systems or time zones. In order to map a point in time to a particular “datetime” (a combination of a date and a time, i.e. January 28th, 2017, 2:45pm), we need to impose a calendar system.</p><h4><a href="https://developer.apple.com/documentation/foundation/nscalendar">Calendar</a></h4><p>A <strong>calendar</strong> places milestones onto the timeline, defining something like “the year 1982” to be the interval between two specific points in time. Datetimes only make sense in the context of a calendar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHBgSRryZKYaJidyHK1Iew.png" /><figcaption>Figure 2: A calendar places milestones on the timeline.</figcaption></figure><p>Apple represents calendars with the Calendar class. Calendar instances are created using predefined identifiers that declare the calendar system to use. For instance, Calendar(identifier: .gregorian) will give you a Gregorian calendar.</p><p>To complicate matters further, a specific calendar system can also be shifted forwards or backwards in time based on the <strong>time zone</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghHc6pTH2LrMB_Fe9zy8CQ.png" /><figcaption>Figure 3: A calendar system can be shifted forwards or backwards in time depending on the time zone.</figcaption></figure><p>In order to anchor a calendar system in place, we must specify the time zone. Per Apple <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtTimeZones.html">documentation</a>:</p><blockquote>By default, NSCalendar uses the default time zone for the application—or process—when the calendar object is created. Unless the default time zone has been otherwise set, it is the time zone set in System Preferences.</blockquote><p>In other words, Calendar objects are automatically initialized with a default time zone, and that default time zone is likely the time zone in the user’s System Preferences.</p><p>However, you may wish to override this default by explicitly setting the Calendar&#39;s .timeZone property yourself. Apple represents time zones using the TimeZone class. Similar to Calendar, these are initialized with identifiers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c32fa309cd221c773068f945e2558f3d/href">https://medium.com/media/c32fa309cd221c773068f945e2558f3d/href</a></iframe><p><strong>Protip: </strong>You can use Calendar.current to get the user’s current calendar. Per Apple <a href="https://developer.apple.com/documentation/foundation/nscalendar/1408501-currentcalendar">documentation</a>:</p><blockquote>The returned calendar is formed from the settings for the current user’s chosen system locale overlaid with any custom settings the user has specified in System Preferences.</blockquote><p><strong>Protip 2: </strong>You can see a list of all TimeZone identifiers by iterating through TimeZone.knownTimeZoneIdentifiers. Why this isn’t listed somewhere in the documentation is beyond me.</p><h3>Manipulating Dates and Times</h3><p>Manipulating a Date is ostensibly as simple as adding or subtracting a number of seconds (aka a TimeInterval) to one point in time in order to get another point in time.</p><p>However, this capability is often insufficient for our purposes. For instance, we might want to advance from the first day of one month, to the first day of the next month. Depending on the month and year, the number of seconds we add will differ. This is where Calendar comes in. Calendar will know the number seconds necessary to move from one calendar datetime to another.</p><p>With a Date, and Calendar (set with TimeZone), we have the tools necessary to manipulate dates with respect to calendrical time units (such as months or years). We perform these tasks by translating calendar-independent Date objects to and from calendar-specific DateComponents objects.</p><h4><a href="https://developer.apple.com/documentation/foundation/nsdatecomponents">DateComponents</a></h4><p>Unlike Date, DateComponents represents exactly what one might expect. It encapsulates the component pieces of a date, such as year, month, day, hour, minute, and second, with respect to a Calendar.</p><p>We can translate between Date and DateComponents with the use of a Calendar. Once a Date has been broken down into its components, we can manipulate those components before reassembling them into a new Date.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c57cd05256d791a94b5e6cfc36a75d4/href">https://medium.com/media/9c57cd05256d791a94b5e6cfc36a75d4/href</a></iframe><p>In the above example (Code 2), we start with an arbitrary Date (line 2), and a Gregorian Calendar object set to a New York TimeZone (lines 5 through 7). In line 10, we create DateComponents by interpreting the Date in the context of the Calendar. If we inspect these components, we will see that the components describe the datetime September 27th, 2018, 3:34:53pm. In line 13, we take those components and turn them back into a Date.</p><p>DateComponents can also be used to represent an interval of time with calendrical units. For example, you may want to know how many calendar days are between two points in time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90ed108c0e7805c911b34a993d9f0de7/href">https://medium.com/media/90ed108c0e7805c911b34a993d9f0de7/href</a></iframe><p>In the above example (Code 3), we start with two Dates and a Calendar (lines 2 through 4). We then compute the difference between those two dates in calendar days (i.e. the number of days in our Calendar between our two Dates). Inspection of differenceInCalendarUnits reveals that differenceInCalendarUnits.days is 1157, meaning there are 1157 days in our calendar between date1 and date2.</p><h4>Side Note: <a href="https://developer.apple.com/documentation/foundation/dateformatter">DateFormatter</a></h4><p>In general, DateComponents allow you to perform computations and mutations on Date objects. If you find that you have a singleDate that never changes, and your goal is simply to display that Date with respect to a different time zone, then the DateFormatter class may suit your needs. DateFormatter converts a Date object into a String representation (and vice versa), and allows you to set both a Calendar and a TimeZone to it (with the properties .calendar and .timeZone respectively). You can use DateFormatter to display your Date in whatever TimeZone you wish.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4954678845709f58fda388c529b18433/href">https://medium.com/media/4954678845709f58fda388c529b18433/href</a></iframe><h3>Example Usages</h3><p>Here are some ways you might use Date, Calendar, and DateComponents.</p><h4>2pm today in California</h4><p>Let’s say you want to create a Date corresponding to 2pm today in California time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e07a5f472135c1d68c0413c4c744800/href">https://medium.com/media/4e07a5f472135c1d68c0413c4c744800/href</a></iframe><h4>What day/time is it now in Taipei?</h4><p>Let’s say you want to know what the current date and time is in Taipei, Taiwan.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9e1389b61e4174e3d548925ec7c87e2/href">https://medium.com/media/b9e1389b61e4174e3d548925ec7c87e2/href</a></iframe><p>Alternatively</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86bc37b53c4b94353abc67a90378472f/href">https://medium.com/media/86bc37b53c4b94353abc67a90378472f/href</a></iframe><p>Note that <a href="https://developer.apple.com/documentation/foundation/calendar/2293477-datecomponents">.dateComponents(in:, from:)</a> ignores the time zone of the calendar the method is called on and uses the passed in time zone instead. It returns all components.</p><h4>What day/time is 2pm today in California in Taipei time?</h4><p>Just combine the above two examples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8d082e5e1d0ece31584820cec08abfd/href">https://medium.com/media/f8d082e5e1d0ece31584820cec08abfd/href</a></iframe><h4>This time next week</h4><p>Let’s say you want to create a Date representing “this time next week” (i.e. a week from now).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/713941065707d8c59772720857666268/href">https://medium.com/media/713941065707d8c59772720857666268/href</a></iframe><p>Alternatively</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/923db670f0905b1464825b4edb184e6a/href">https://medium.com/media/923db670f0905b1464825b4edb184e6a/href</a></iframe><h4>This time next Monday</h4><p>Let’s say you want to create a Date representing “this time next Monday” (i.e. same time as now, but on next Monday).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eefa1cc293ab50f8efbbc14bcbc3959d/href">https://medium.com/media/eefa1cc293ab50f8efbbc14bcbc3959d/href</a></iframe><p>Note that Monday is represented with the number 2. Per Apple <a href="https://developer.apple.com/documentation/foundation/nsdatecomponents/1410442-weekday">documentation</a>:</p><blockquote>Weekday units are the numbers 1 through <em>n</em>, where <em>n</em> is the number of days in the week. For example, in the Gregorian calendar, <em>n</em> is 7 and Sunday is represented by 1.</blockquote><h4>Countdown to the new year</h4><p>Let’s say you want to know how many months, days, hours, minutes, and seconds are left until the ball drops in Times Square (NYC).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ee40b8d737fc8ba0dcb98ad0baf4ed1/href">https://medium.com/media/1ee40b8d737fc8ba0dcb98ad0baf4ed1/href</a></iframe><h4>And more!</h4><p>The Calendar class has a ton of other useful functions. I recommend either checking out the <a href="https://developer.apple.com/documentation/foundation/calendar">documentation</a>, or just typing a . after your calendar instance and letting autocomplete show you all the fun things you can do.</p><h3>Troubleshooting</h3><h4>Translating from Date to DateComponents and back results in a different Date</h4><p>If you try to instantiate a Date from an incomplete DateComponents object, Apple will try to fill in the blanks. For example, if your DateComponents only specifies the hour and minute, then Apple will default the month and day to January 1st.</p><p>It’s possible that when you decomposed your Date into DateComponents you only specified certain components to return (i.e. .hour and .minute). If there is not enough information in those components, when you try to turn those DateComponents back into a Date, Apple fills in the missing information with its defaults, resulting in a different Date.</p><p>When decomposing a Date into DateComponents, try specifying at least the .year, .month, .day, .hour, .minute, .second, and .nanosecond components. This should give you enough information to recompose your original Date.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4517dfd35535ed71357c7968557be908/href">https://medium.com/media/4517dfd35535ed71357c7968557be908/href</a></iframe><h3>Closing</h3><p>In summary:</p><ul><li>A Date represents an absolute point in time.</li><li>A Calendar defines milestones (such as year, month, and day) in the timeline. It is anchored in place on the timeline with a TimeZone.</li><li>Using a Calendar, you can decompose a Date into DateComponents and recompose DateComponents into a Date.</li><li>DateComponents allow you to manipulate Date objects using calendrical units (i.e. months, days).</li></ul><p>Hopefully you are now equipped to manipulate dates and times as you see fit! The next time someone mentions time zones, your eyes can twitch just a little bit less.</p><h3>References</h3><h4>Apple’s Documentation</h4><ul><li><a href="https://developer.apple.com/documentation/foundation/date">Date</a> / <a href="https://developer.apple.com/documentation/foundation/nsdate">NSDate</a></li><li><a href="https://developer.apple.com/documentation/foundation/calendar">Calendar</a> / <a href="https://developer.apple.com/documentation/foundation/nscalendar">NSCalendar</a></li><li><a href="https://developer.apple.com/documentation/foundation/datecomponents">DateComponents</a> / <a href="https://developer.apple.com/documentation/foundation/nsdatecomponents">NSDateComponents</a></li><li><a href="https://developer.apple.com/documentation/foundation/timezone">TimeZone</a> / <a href="https://developer.apple.com/documentation/foundation/nstimezone">NSTimeZone</a></li><li><a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple_ref/doc/uid/10000039i">Date and Time Programming Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f0e0d0e93be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/manipulating-dates-and-time-zones-in-ios-development-2f0e0d0e93be">Manipulating Dates and Time Zones in iOS Development</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Collection View Layout — A Simple Template]]></title>
            <link>https://medium.com/spring-engineering/custom-collection-view-layout-a-simple-template-8a076f73537a?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/8a076f73537a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[layout]]></category>
            <dc:creator><![CDATA[Alan Wang]]></dc:creator>
            <pubDate>Thu, 03 May 2018 17:31:42 GMT</pubDate>
            <atom:updated>2018-05-04T20:41:38.462Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>UICollectionView is one of the most powerful tools in the iOS developer’s arsenal. With it, you can create complex UIs with built in support for scrolling, tap recognition, layout changes, and great performance. In fact, it would not be surprising if almost every screen in your app could/should be backed by a UICollectionView.</p><p>Unlike UITableView, UICollectionView gives you the freedom to define your own layout. That’s right<strong>, you can put things wherever you want</strong>. To take advantage of this feature, you will need to create your own <strong>custom layout</strong>.</p><p>There is great documentation about custom layouts available from both <a href="https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/CreatingCustomLayouts/CreatingCustomLayouts.html">Apple</a>, and various <a href="https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2">other</a> <a href="https://www.objc.io/issues/3-views/collection-view-layouts">articles</a>, but it’s easy to get lost in the details. In this article, we will provide a <strong>simple template</strong> for implementing custom layouts. Along the way, we will discuss what a layout does, what methods you need to implement, and what you should be doing in those methods.</p><p><strong>Note</strong>: Before embarking on this quest, it’s worth seeing whether Apple’s default layout (<a href="https://developer.apple.com/documentation/uikit/uicollectionviewflowlayout">UICollectionViewFlowLayout</a>) is enough to serve your purposes. This class has a large degree of customizability, and will probably work for the majority of cases.</p><h3>What would you say… you do here?</h3><p>What exactly does the layout do and how does it work with UICollectionView? You can think of UICollectionView as a rendering engine. It is responsible for creating views, putting them on screen, and handling events. However, in order to maximize its reusability, UICollectionView makes heavy use of delegation to achieve custom results. For instance, it delegates responsibility over the creation of cells to its data source. Similarly, it delegates responsibility over where those cells go to its layout.</p><p>Ultimately, the layout is responsible for returning two pieces of information:</p><ol><li>How big is the content area? (i.e. What is the size of the scrollable area of the collection view?)</li><li>Where and how big are the cells and supplementary/decoration views?</li></ol><p>The first is returned via the readonly property collectionViewContentSize (more on this later). The second is returned via <a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayoutattributes">UICollectionViewLayoutAttributes</a> objects. UICollectionViewLayoutAttributes are differentiated by their type (cell, supplementary view, or decoration view) and index path. Layout attributes encapsulate layout information (i.e. frame) about their corresponding cells/views and inform the collection view where to place those visual elements. Your custom layout object returns these attributes via the methods described below, and your collection view uses these attributes to place its visual elements in the desired locations.</p><h3>Creating a Custom Layout</h3><p>In order to create a custom layout, you must <strong>create a subclass of </strong><strong>UICollectionViewLayout</strong>. At minimum, your subclass should override the following methods:</p><h4>Core Layout</h4><ul><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617752-prepare">prepare</a> (aka prepareLayout in Objective-C) — Not strictly required, but highly recommended.</li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617796-collectionviewcontentsize">collectionViewContentSize</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617769-layoutattributesforelements">layoutAttributesForElements(in:)</a></li></ul><h4>Attribues On Demand</h4><ul><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617797-layoutattributesforitem">layoutAttributesForItem(at:)</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617792-layoutattributesforsupplementary">layoutAttributesForSupplementaryView(ofKind:at:)</a> (if your layout supports supplementary views)</li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617809-layoutattributesfordecorationvie">layoutAttributesForDecorationView(ofKind:at:)</a>(if your layout supports decoration views)</li></ul><p>There are many ways to architect the implementation of these methods. At the end of the day, you just need to return the appropriate content size and layout attributes. Below, we provide one implementation — a <strong>simple template</strong> that can be customized by altering only the prepare() method.</p><h3>Override Core Layout Methods</h3><p>When laying out your collection view, Apple will call the following methods in the following order:</p><ul><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617752-prepare">prepare()</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617796-collectionviewcontentsize">collectionViewContentSize</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617769-layoutattributesforelements">layoutAttributesForElements(in:)</a></li></ul><p>This constitutes the <a href="https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/CreatingCustomLayouts/CreatingCustomLayouts.html#//apple_ref/doc/uid/TP40012334-CH5-SW3">Core Layout Process</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIsjDmVsavmo8uHEuoIHtA.png" /><figcaption>The Core Layout process, as illustrated by <a href="https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/CreatingCustomLayouts/CreatingCustomLayouts.html#//apple_ref/doc/uid/TP40012334-CH5-SW3">Apple</a></figcaption></figure><h4>prepare( )</h4><p>(aka prepareLayout in Objective-C)</p><p>This method is called at the beginning of the Core Layout Process and is an opportunity to perform preprocessing.</p><p>For our implementation, this is the <strong>single most important method</strong> because this is where the magic (aka math) happens. In this method we will:</p><ul><li>Determine the <strong>size</strong> and <strong>position</strong> of every cell, supplementary view, and decoration view.</li><li>Compute the <strong>size</strong> of the collection view’s scrollable content area.</li><li>Instantiate layout attributes and store them.</li></ul><p>Basically, this method is where we decide <strong>what the layout is</strong>.</p><p>Your subclass has access to a property called <a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617751-collectionview?language=objc">collectionView</a> that (unsurprisingly) points to the collection view this layout belongs to. Use it to get information about your sections, cells, and views, and combine that information with other model data to decide what goes where (this other data could be set directly to the layout, or provided via a delegate).</p><p>Keep in mind that you won’t be able to use the frame property of your cells or views. They haven’t been positioned yet. We’re literally doing that. Right now.</p><p>After you finish doing your math, store the results for access by other methods. I suggest:</p><ul><li>For <strong>content size</strong>, define a privateCGSize property and set it to the computed size.</li><li>For the <strong>layout attributes</strong>, define one to three private dictionaries to store these results — one for cells, one for supplementary views (if needed), and one for decoration views (if needed). Create a UICollectionViewLayoutAttributes object for each of your cells/views, set its frame based on your math, and add it to your dictionary with the <strong>index path</strong> as the key.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3de958b90a6c1d403aca961e9cd67acc/href">https://medium.com/media/3de958b90a6c1d403aca961e9cd67acc/href</a></iframe><p>In short, for our implementation, your prepare() method should:</p><ol><li>Use self.collectionView to figure out what you need to lay out.</li><li>Figure out where everything goes and how much space you need.</li><li>Instantiate the appropriate UICollectionViewLayoutAttributes objects.</li><li>Store the layout attributes, and computed content size for use by other methods.</li></ol><h4>collectionViewContentSize</h4><p>This value determines the size of the scrollable area in your collection view. It is actually a readonly property of the collection view layout. Override its getter to return the desired size.</p><p>For our implementation, return the the content size you computed and stored in prepare().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f3274b088baa3dc985bfcc6964d5b66/href">https://medium.com/media/6f3274b088baa3dc985bfcc6964d5b66/href</a></iframe><h4>layoutAttributesForElements(in:)</h4><p>(aka layoutAttributesForElementsInRect: in Objective C)</p><p>This method gives you a CGRect and wants you to return an array of UICollectionViewLayoutAttributes objects that correspond to the cells/views that lie (partially and wholly) within that rectangle. (<strong>Fun fact</strong>: The rectangle it gives you is not necessarily the view rectangle).</p><p>For our implementation, iterate through the layout attributes you created in prepare() and check their frames to see if any of them intersect the provided rect. Use the intersects(_:) method of CGRect to easily determine this.</p><p>For any layout attributes whose frame intersects the given rect, throw the attributes into an array. Return the array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc212436d83de9485c9953b55d8b38c1/href">https://medium.com/media/cc212436d83de9485c9953b55d8b38c1/href</a></iframe><h3>Layout Attributes — Now On Demand</h3><p>As if that wasn’t enough, outside of the Core Layout Process, your collection view may also ask for layout attributes at specific index paths. So needy! The following methods meet this demand:</p><ul><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617797-layoutattributesforitem">layoutAttributesForItem(at:)</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617792-layoutattributesforsupplementary">layoutAttributesForSupplementaryView(ofKind:at:)</a> (if your layout supports supplementary views)</li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617809-layoutattributesfordecorationvie">layoutAttributesForDecorationView(ofKind:at:)</a>(if your layout supports decoration views)</li></ul><p>Each of these methods takes in an index path and returns the layout attributes for the cell/view at that path.</p><p>For our implementation, simply use the provided index path to access the appropriate dictionary, and return the result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2003a09166c73f74208ffd2583054cf/href">https://medium.com/media/e2003a09166c73f74208ffd2583054cf/href</a></iframe><p>If your collection view doesn’t use supplementary/decoration views, return nil from those two methods.</p><h3>That’s All Folks</h3><p>And that’s it! In summary, all you need to do to create a custom layout is:</p><ul><li>Return the size of the scrollable area in collectionViewContentSize</li><li>Return UICollectionViewLayoutAttributes with their frame set in layoutAttributesForElements(in:), layoutAttributesForItem(at:), layoutAttributesForSupplementaryView(ofKind:at:), and layoutAttributesForDecorationView(ofKind:at:)</li></ul><p>Below is the template for our implementation. To customize it, all you have to do is change prepare() to compute the desired size and positions for your layout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7d661c9ebfddac6973dfc179e212a49/href">https://medium.com/media/f7d661c9ebfddac6973dfc179e212a49/href</a></iframe><p>Now just instantiate your custom layout and set it to your collection view’s layout property to watch it go!</p><h3>Implementation Discussion</h3><p>The implementation we provide here is one of many possible implementations. It presents a simple workflow in which we front-load all of the work into the optional prepare() method and store the results to be quickly returned by the appropriate methods. The benefit of instantiating all of the layout attributes in prepare() is that they are only instantiated once at the beginning of the Core Layout Process. Additionally, other methods (such as layoutAttributesForElements(in:)) are called often, and in time sensitive situations (i.e. when scrolling). Attempting to instantiate layout attributes in these methods could result in degraded performance. The drawback of storing all of these attributes is that it takes up memory. If your collection view has a very large number of elements, this implementation may be inefficient.</p><p>You might consider lazy loading the layout attributes in the methods that return them (i.e. layoutAttributesFor____), and cache the results so that you don’t need to recompute them. If you do so, be sure to override invalidateLayout to clear the cache on layout invalidation.</p><p>The interface that Apple requires you to implement affords you a large degree of flexibility in how you implement your custom layout. Use the implementation that works best for your specific circumstances.</p><h3>Optional Methods</h3><h4><strong>shouldInvalidateLayout(forBoundsChange:)</strong></h4><p>Override this method to return YES if you want your layout to automatically recalculate when your collection view’s bounds change.</p><h4><strong>initialLayoutAttributesForAppearing_____(at:)</strong></h4><p>Includes:</p><ul><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617789-initiallayoutattributesforappear">initialLayoutAttributesForAppearingItem(at:)</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617737-initiallayoutattributesforappear">initialLayoutAttributesForAppearingSupplementaryElement(ofKind:at:)</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617726-initiallayoutattributesforappear">initialLayoutAttributesForAppearingDecorationElement(ofKind:at:)</a></li></ul><p>These methods are to help your layout animate insertions. When you perform an animation, iOS will smoothly animate your view from its initial position to its final position. However for insertions, there is no initial position because the view doesn’t exist.</p><p>Use these methods to define the initial position you would like an inserted item to animate in from. As always, do this by instantiating a UICollectionViewLayoutAttributes and setting its frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVJ1FrD9rCelNoATyFUmgQ.png" /><figcaption>Using initialLayoutAttributesForAppearingItem(at:) to animate an inserted cell (source: <a href="https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/CreatingCustomLayouts/CreatingCustomLayouts.html#//apple_ref/doc/uid/TP40012334-CH5-SW13">Apple</a>)</figcaption></figure><h4>finalLayoutAttributesForDisappearing_____(at:)</h4><p>Includes:</p><ul><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617740-finallayoutattributesfordisappea">finalLayoutAttributesForDisappearingItem(at:)</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617742-finallayoutattributesfordisappea">finalLayoutAttributesForDisappearingSupplementaryElement(ofKind:at:)</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617762-finallayoutattributesfordisappea">finalLayoutAttributesForDisappearingDecorationElement(ofKind:at:)</a></li></ul><p>This is the same thing as initialLayoutAttributesForAppearing_____(at:), except it is used to define the final position for animating deletions.</p><h3>Other Resources</h3><ul><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewlayout">Apple’s UICollectionViewLayout documentation</a></li><li><a href="https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/CreatingCustomLayouts/CreatingCustomLayouts.html#//apple_ref/doc/uid/TP40012334-CH5-SW1">Apple’s Collection View Programming Guide</a></li><li><a href="https://www.objc.io/issues/3-views/collection-view-layouts/">objc.io Custom CollectionView Layouts</a></li><li><a href="http://martiancraft.com/blog/2017/05/collection-view-layouts/">Going Without The Flow — Exploring Collection View Layouts</a></li></ul><h3>Acknolwedgements</h3><p>Special thanks to the awesome team at Spring for helping with this blog post, specifically Glen DeBiasa, whose code I stol- borrowed, and Jim Grandpre and Ben Anderman for their suggestions.</p><p>Shameless plug: You too can be part of this team awesome. <a href="https://grnh.se/46phoj1">Spring is hiring</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a076f73537a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/custom-collection-view-layout-a-simple-template-8a076f73537a">Custom Collection View Layout — A Simple Template</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Spring Prepares for the Black Friday Frenzy]]></title>
            <link>https://medium.com/spring-engineering/how-spring-prepares-for-the-black-friday-frenzy-c635054493b0?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/c635054493b0</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[black-friday]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Victor Quinn]]></dc:creator>
            <pubDate>Wed, 25 Apr 2018 20:51:33 GMT</pubDate>
            <atom:updated>2018-04-25T20:51:05.606Z</atom:updated>
            <content:encoded><![CDATA[<p>With the help of <a href="https://uncubed.com/">Uncubed</a> and <a href="http://aws.amazon.com/">Amazon Web Services</a>, we shot this video late last year to share a story about a scalability issue we had during Black Friday 2016 and the work we did to avoid that for Black Friday 2017 using AWS infrastructure.</p><p>It should come as no surprise that <a href="https://en.wikipedia.org/wiki/Black_Friday_(shopping)">Black Friday</a> is one of the busiest days of the year for a marketplace like <a href="https://www.shopspring.com/">Spring</a> as retailers offer deep discounts and shoppers really jump into their holiday shopping.</p><p>Our engineering team generally spends a few months leading up to that day running drills, gathering metrics and tuning systems, prepping, pre-emptively scaling, and just generally ensuring everything is in tip top shape to handle traffic for that one day in which we will often see 20 or 30 times the volume that we’d see on a normal day.</p><p>Without further delay, here’s the video we shot where I told a story about one such optimization:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJWkOI7mOOVY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJWkOI7mOOVY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJWkOI7mOOVY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/92aecaab2718a93fb01eb8b3ca5be3e4/href">https://medium.com/media/92aecaab2718a93fb01eb8b3ca5be3e4/href</a></iframe><p>Happy to report that the scalability work we did ensured that part of our system functioned smooth as silk for this last holiday season!</p><p>Spring is hiring and we try damned hard to make it an awesome place to work. <a href="https://grnh.se/icdh7l1">Come join us!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c635054493b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/how-spring-prepares-for-the-black-friday-frenzy-c635054493b0">How Spring Prepares for the Black Friday Frenzy</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accurate Product Counts With Elasticsearch]]></title>
            <link>https://medium.com/spring-engineering/accurate-product-counts-with-elasticsearch-aa5d2007bda6?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/aa5d2007bda6</guid>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[ecommerce-software]]></category>
            <category><![CDATA[aggregation]]></category>
            <dc:creator><![CDATA[Ben Anderman]]></dc:creator>
            <pubDate>Fri, 30 Mar 2018 17:58:48 GMT</pubDate>
            <atom:updated>2018-03-29T17:59:03.497Z</atom:updated>
            <content:encoded><![CDATA[<p>At Spring, we use Elasticsearch to let users search and browse our 200,000+ products, with the ability to refine by category, size, color, and price. For each of these refinements, we display the number of products that match each possible option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*7jk_Yy-NgiS1kH-4VbnAsg.png" /></figure><p>For most of these refinements, getting product counts was straightforward, using standard <a href="https://www.elastic.co/guide/en/elasticsearch/reference/2.4/search-aggregations-metrics-valuecount-aggregation.html">aggregation queries</a>. But then the bug reports starting coming in. Occasionally, the counts for each option were higher than the number of results returned if you actually refined by that option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*RPbpQbRB7V3BXc40b__JGg.png" /><figcaption><em>Note how </em><strong><em>L</em></strong><em> is selected and shows 226 results, while the button on the bottom shows 162 results. The numbers in the list come from aggregations, while the number at the bottom comes from </em><strong><em>total_hits</em></strong><em>.</em></figcaption></figure><p>At first it was unclear what was happening, since the amount that these counts were off by was inconsistent. Our products have some properties that apply to the whole product, like taxonomy and brand, as well as a set of variants, with properties like size and color. After some investigation, we discovered that all of the broken refinement counts were for fields stored at the variant level, as opposed to product level. Take this example of two t-shirts with three variants each:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b160ff16d301182ad28e16006d168ed0/href">https://medium.com/media/b160ff16d301182ad28e16006d168ed0/href</a></iframe><p>We found that in a case like the above, Elasticsearch would return a count of <strong>1</strong> for <strong>size: XS</strong>, but a count of <strong>4</strong> for <strong>color: black</strong>. We were getting counts of matching <em>variants</em>, not products <em>with</em> one or more matching variant! The solution:<strong> </strong><a href="https://www.elastic.co/guide/en/elasticsearch/reference/2.4/search-aggregations-bucket-reverse-nested-aggregation.html"><strong>reverse nested aggregations</strong></a><strong>.</strong></p><h3>Reverse Nested Aggregations</h3><p>Because variants are nested documents within product documents, we use a nested aggregation to get those initial incorrect counts for color. The query for this looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/729133422f382ee8f353ac2df0d958d9/href">https://medium.com/media/729133422f382ee8f353ac2df0d958d9/href</a></iframe><p>And the result of that looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23cc932d20b0b352645fbf0fcbe74c49/href">https://medium.com/media/23cc932d20b0b352645fbf0fcbe74c49/href</a></iframe><p>A reverse nested aggregation is like a nested aggregation, except that instead of going down the document hierarchy to aggregate child documents, it goes in reverse to aggregate the parent documents of the nested aggregation it’s within. When we add the reverse nested aggregation, the query looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f77b073b77aebd50b38e0187bd9d1888/href">https://medium.com/media/f77b073b77aebd50b38e0187bd9d1888/href</a></iframe><p>And the result of that looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08278f44ea11dcb696b3e3ad87daaa5f/href">https://medium.com/media/08278f44ea11dcb696b3e3ad87daaa5f/href</a></iframe><p>And now, using the doc_counts in reverse_nested_colors, the counts are correct!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*IfIeC67q9PWW3VtLEMz8cA.png" /></figure><p><a href="https://grnh.se/kx1ofq1">We’re hiring!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa5d2007bda6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/accurate-product-counts-with-elasticsearch-aa5d2007bda6">Accurate Product Counts With Elasticsearch</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple way to optimize email domain query performance in PostgreSQL]]></title>
            <link>https://medium.com/spring-engineering/a-simple-way-to-optimize-email-domain-query-performance-in-postgresql-bace790e6a74?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/bace790e6a74</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Jason Walker-Yung]]></dc:creator>
            <pubDate>Wed, 14 Feb 2018 19:50:47 GMT</pubDate>
            <atom:updated>2018-02-14T19:39:10.779Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>tl;dr:</strong> A prefixed pattern query will run faster than a suffixed one, because the former can take advantage of an index. In PostgreSQL, we can create a functional index using reverse() to make a suffixed pattern query performant. Additionally, you may need to invoke specific options to make the index work with pattern queries.</p><h3>A less than optimal query</h3><p>We had a query that searched for users whose email belonged to a certain domain. (Without loss of generality, the domain name has been changed to protect the innocent.)</p><pre>select distinct users.id, users.name, users.email from users where users.email like &#39;%example%&#39;;</pre><p>The email column already has an index on it, so we wouldn’t expect the performance to be so slow. We ran <a href="https://www.postgresql.org/docs/9.6/static/using-explain.html">EXPLAIN ANALYZE</a> to understand how PostgreSQL executed the query. It had a sad story to tell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a58e22c17f742e923dbd9a084c87969/href">https://medium.com/media/5a58e22c17f742e923dbd9a084c87969/href</a></iframe><p>Postgres isn’t using the index at all; that Seq Scan indicates that it’s scanning <em>every row in the table</em> to check if each row matches the pattern. Surely we can do better!</p><p>According to the <a href="https://www.postgresql.org/docs/9.6/static/indexes-types.html">PostgreSQL documentation</a>:</p><blockquote>The optimizer can also use a B-tree index for queries involving the pattern matching operators LIKE and ~ <strong>if</strong> the pattern is a constant and is anchored to the beginning of the string — for example, col LIKE ‘foo%’ or col ~ ‘^foo’, but not col LIKE ‘%bar’. However, if your database does not use the C locale you will need to create the index with a special operator class to support indexing of pattern-matching queries; see <a href="https://www.postgresql.org/docs/9.6/static/indexes-opclass.html">Section 11.9</a> below. It is also possible to use B-tree indexes for ILIKE and ~*, but only if the pattern starts with non-alphabetic characters, i.e., characters that are not affected by upper/lower case conversion.</blockquote><p>Imagine we had a list of Presidents of the United States in alphabetical order:</p><pre>Abraham Lincoln<br>Andrew Jackson<br>Andrew Johnson<br>...<br>Zachary Taylor</pre><p>You could look up all the Presidents named William quickly — just skip to the W’s — but this list isn’t optimized to find last names, say, Presidents whose last name is Roosevelt.</p><h3>Put it down, flip it, and reverse it</h3><p>Our strategy is build a separate index that allows us to access the end of the string. In PostgreSQL, you can define a functional index to look up a value from a virtual column. This allows for a few different approaches:</p><ul><li><a href="https://gist.github.com/jelder/a25ba892f269f324a535">Write a function to parse out the domain and index on that function</a>.</li><li><a href="https://niallburkley.com/blog/index-columns-for-like-in-postgres/">Use a trigram index</a></li><li><a href="https://wiki.postgresql.org/wiki/Reverse_string">Index the reverse of the string</a></li></ul><p>We took the third option, as it seemed the simplest to implement and least prone to error.</p><pre>CREATE INDEX CONCURRENTLY idx_users_email_reverse on USERS (reverse(email))</pre><p>Our new query will be:</p><pre>select distinct users.id, users.name, users.email from users where reverse(users.email) like reverse(&#39;%example.com&#39;);</pre><p>But alas, this did not yield any change in the EXPLAIN plan. Our query was still doing a scan of the entire table.</p><p>Let’s re-read that documentation excerpt above. The second half of that graf has a whole disclaimer about locales, so let’s ask: <a href="http://`/">a</a><a href="https://stackoverflow.com/questions/1665726/how-do-i-know-if-my-postgresql-server-is-using-the-c-locale">re we using the C locale</a>?</p><pre>psql=&gt; SHOW LC_COLLATE;</pre><pre>lc_collate</pre><pre>-------------</pre><pre>en_US.UTF-8</pre><pre>(1 row)</pre><p>D’oh.</p><h3>Hello, Operator</h3><p>As the documentation states, we “will need create the index with a special operator class to support indexing of pattern-matching queries”. In other words, PostgreSQL needs to create an index with a data structure that supports operations such as &gt;= and &lt;= with patterns. The EXPLAIN plan above suggested that we’re casting the pattern to a text type, so we opted for the <a href="https://www.postgresql.org/docs/10/static/indexes-opclass.html">text_pattern_ops</a> qualifier:</p><pre>CREATE INDEX CONCURRENTLY idx_users_email_reverse on USERS (reverse(email) <strong>text_pattern_ops</strong>)</pre><p>Let’s run EXPLAIN again to see if this works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18156145942c307a9b706cb7486c07c3/href">https://medium.com/media/18156145942c307a9b706cb7486c07c3/href</a></iframe><p><strong>Staggering! Almost 20,000x performance improvement!</strong> We went from running over 5 seconds (in a best case; we had data points in double digits) to reliably under a millisecond.</p><p>You’ll note that we also had to switch from case-insensitiveILIKE to the case-sensitiveLIKE to make this work. This in itself provides substantial (3-4x) performance improvements. In this particular case, we can assume emails are all in lower case, but if we really had to, we could probably index on reverse(lower(email)).</p><p><a href="http://grnh.se/ap240r1">We’re hiring</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bace790e6a74" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/a-simple-way-to-optimize-email-domain-query-performance-in-postgresql-bace790e6a74">A simple way to optimize email domain query performance in PostgreSQL</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed up with eager loading in SQLAlchemy]]></title>
            <link>https://medium.com/spring-engineering/speed-up-with-eager-loading-in-sqlalchemy-87a176cfd7ad?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/87a176cfd7ad</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jason Walker-Yung]]></dc:creator>
            <pubDate>Mon, 11 Dec 2017 17:32:19 GMT</pubDate>
            <atom:updated>2017-12-11T17:32:18.614Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://engineering.shopspring.com/multi-table-filters-in-sqlalchemy-d64e2166199f">our previous post about SQLAlchemy</a>, we fixed our order search query to get the right rows, but the endpoint was still slower than we expected. Why?</p><p>We hit the<a href="http://docs.sqlalchemy.org/en/rel_1_1/glossary.html#term-n-plus-one-problem"> <strong>“N+1” problem</strong></a> that comes with lazy loading relationships in any Object Relational Model framework. Let’s say we query for N orders, and we also want the line items for each order. In a lazy loading scenario, we would have to issue an additional query for the line items for each order, so N+1 in total. Now let’s say we want the product info for each line item, and the brand info for each product, and all of a sudden we’re making a lot of trips to the database.</p><p>Instead of doing a lazy load for each relationship, we could do a second query to get the children for all parent objects, so instead of N+1 queries, we do 2. This will be familiar if you’ve worked with Rails, and in SQLAlchemy, this is known as <a href="http://docs.sqlalchemy.org/en/rel_1_1/orm/loading_relationships.html#subquery-eager-loading"><strong>subquery loading</strong></a>. But we can do even better than that! With <a href="http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html#joined-eager-loading"><strong>joined eager loads</strong></a>, we can ask SQLAlchemy to fetch everything we need in a massive JOIN query and deserialize the rows into objects.</p><h3>Lightening the load / the burdens of “easy”</h3><p>Before we get into the particulars of eager loading, let’s take a step back and ask if we actually need to load all of these related objects. To answer this question, we have to talk about <a href="https://marshmallow.readthedocs.io/en/latest/">marshmallow</a> and <a href="https://marshmallow-sqlalchemy.readthedocs.io/en/latest/">marshamallow-sqlalchemy</a>. The former provides an easy way to serialize a Python object into a JSON object, and the latter extends this functionality to our SQLAlchemy models. This is convenient because we can add a column or a relationship to the model, and it will show up in the serialized JSON without additional coding. On the other hand, this creates an obligation to do a lot of sub-loads, which we established above as being potentially burdensome.</p><p>The solution here is easy. In a <a href="https://marshmallow.readthedocs.io/en/latest/quickstart.html#declaring-schemas">marshmallow schema</a> — a class that controls what gets serialized by marshmallow— <a href="https://marshmallow.readthedocs.io/en/latest/quickstart.html#filtering-output">you can control which fields are serialized</a> by whitelisting only the fields we want using only or by blacklisting the ones we don’t want using exclude. In our case, as our model got more and more complex, maintaining a blacklist became hard to manage, so we switched to a whitelist.</p><p>This reduces the number of objects that we need to retrieve, but it doesn’t address the N+1 problem.</p><h3>Don’t get mad, get eager!</h3><p>Here is an abridged version of our base order query. Let’s say an Order has many Supplier Fragments which represent the various vendors that partner with Spring; each Supplier Fragment has Line Items, which represent what is being bought; each Line Item has a Variant, which represents the exact variation of the product being sold (e.g., a specific color and size); each Variant belongs to a Product, which represents the common attributes shared all variants (e.g., name, brand, description, country of origin).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/691611643e9d7d936867e26183be5a66/href">https://medium.com/media/691611643e9d7d936867e26183be5a66/href</a></iframe><p>For good measure, we add a raiseload to throw an exception if we try to load anything that we didn’t load here. This is helpful for discovering relationships that might throw an exception later when the object becomes detached from the session. More on this in a bit.</p><p>The query that gets emitted is pretty gnarly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69dff97b2f2e1e34c4805f6ba7adddfc/href">https://medium.com/media/69dff97b2f2e1e34c4805f6ba7adddfc/href</a></iframe><p>This may seem counterintuitive, because we’re now blowing up the number of rows retrieved to the total number of variants, but <strong>in practice, it can be more efficient to make one round trip to a remote service and assemble it in the client</strong>. The database is a limited resource, while your application instances can be scaled out. We wouldn’t want to code something like this by hand, but SQLAlchemy is able to do this reliably.</p><h3>Results</h3><p>Here’s a graph from New Relic of the deploy (the green line just after the 1:00 PM mark).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TC7MshyPHMCaZCoq7gCbKg.png" /></figure><p>Before the change, requests <em>averaged</em> close to a full second. Today, that average is around 350ms. Not great, but acceptable for an internal tool, and we got to learn about eager loading.</p><h3>Post-script: eager loading one-to-many relationships</h3><p>Remember when I said we would talk a little more aboutraiseload? A funny thing happened when we used it as part of a joined load on one of our product queries. Here’s an abridged version of our product model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d86091100a91f4e9dce1f9da106041c8/href">https://medium.com/media/d86091100a91f4e9dce1f9da106041c8/href</a></iframe><p>To reiterate, a product has many variants (a.k.a. SKUs) to represent all the permutations of the different sizes, colors, and other attributes of a particular product unit. A product contains attributes common to all of its variants, so it’s not uncommon to refer back to the parent product when processing a variant. Not a bad candidate for eager loading! We’ll do a joined load on the variants, and the variant can refer back to its parent product.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e11261a109c9db45df79d2ed0eb21661/href">https://medium.com/media/e11261a109c9db45df79d2ed0eb21661/href</a></iframe><p>Let’s say we call that variant_names function after the session is done. We found that when we tried to access variant.product for any given variant for this product, an InvalidRequestError was raised. If we remove the raiseload , we would get a different error complaining about how we’re in a detached session and we can’t no longer load more fields. What the fudge?!? Didn’t we just say that products and variants are connected to each other?</p><p>We did, but we didn’t. When we define a backref, we’re actually defining two one-way relationships, product-to-variants and variant-to-product, and technically, the joined load only implies the product-to-variant relationship. Without any additional context, the variant-to-product relationship loads it like it would any other relationship — i.e., the session loads this as product.variant[0].product the same way it would load, say, product.variant[0].inventory. I.e., lazily.</p><p>Let’s go to the documentation! After a few readings of <a href="http://docs.sqlalchemy.org/en/rel_1_1/orm/loading_relationships.html#routing-explicit-joins-statements-into-eagerly-loaded-collections">Routing Explicit Joins/Statements into Eagerly Loaded Collections</a>, I figured out we can use <a href="http://docs.sqlalchemy.org/en/rel_1_1/orm/loading_relationships.html#sqlalchemy.orm.contains_eager">contains_eager()</a> to tell SQLAlchemy that there is indeed a there there, and it will “eager load” the variant-to-product relationship from the existing data instead of going back to the db.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1146b6316e1257b0bf8d0ec1f03b202f/href">https://medium.com/media/1146b6316e1257b0bf8d0ec1f03b202f/href</a></iframe><h3>Conclusions</h3><p><strong>Eager loading improves object retrieval performance for large collections of related objects by reducing the number of queries.</strong> Counterintuitively, it can be more performant to join everything into one query and let SQLAlchemy generate the relationships from that.</p><p>If you are using an automated serializer like marshmallow, review the fields that are actually being serialized and <strong>make sure you’re not incurring unnecessary subloads for objects you are not using</strong>.</p><p><strong>Use </strong><strong>contains_eager() to load back references proactively</strong>. This prevents a lazy load to refer back to the parent object, which in turn prevents exceptions when you try to do this when the object is detached from its session.</p><p><a href="http://grnh.se/ap240r1">We are hiring</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a176cfd7ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/speed-up-with-eager-loading-in-sqlalchemy-87a176cfd7ad">Speed up with eager loading in SQLAlchemy</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Misplaced Views and Choppy Scrolling with Dynamically Sized UICollectionViewCells]]></title>
            <link>https://medium.com/spring-engineering/misplaced-views-and-choppy-scrolling-with-dynamically-sized-collection-view-cells-4010c02fbaae?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/4010c02fbaae</guid>
            <category><![CDATA[autolayout]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Alan Wang]]></dc:creator>
            <pubDate>Fri, 01 Dec 2017 22:15:44 GMT</pubDate>
            <atom:updated>2017-12-11T15:54:18.786Z</atom:updated>
            <content:encoded><![CDATA[<p>Here at Spring, we recently embraced Auto Layout in all of its glory to create dynamically sized cells for our collection views. (We then wrote a blog post that I will shamelessly promote <a href="https://engineering.shopspring.com/dynamic-cell-sizing-in-uicollectionview-fd95f614ef80">here</a>.) However, after the honeymoon period was over, we began to notice a few problems:</p><ol><li>Scrolling was occasionally choppy.</li><li>Supplementary views were sometimes misplaced.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*aU5lPsdZqzjCNENeHvg3Fw.gif" /><figcaption>Ew.</figcaption></figure><p>In this article, we will talk about the results of our investigation into these issues, and the solution we employed to solve them. Our solution uses Apple’s traditional non-self-sizing layout framework and incorporates dynamically sized cells into its delegate methods.</p><h3>Choppy Scrolling</h3><p>We were able to reproduce the choppy scrolling with the following steps:</p><ol><li>Scroll down in the collection view.</li><li>Push another view controller onto the navigation stack.</li><li>Pop the view controller so we are back on our collection view.</li><li>Scroll up. The scrolling will be choppy.</li></ol><h4><strong>The Cause</strong></h4><p>Somewhere between the calls to viewWillAppear: and viewDidAppear: on the collection view’s view controller, the collection view is throwing away the sizes it had previously computed for any cells not on screen. The collection view replaces those sizes with the estimatedItemSize and adjusts the contentOffset and contentSize of the collection view so that it appears as if nothing has changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHRRPW6YzpTRM2nlrkOdwg.jpeg" /><figcaption>Visualization of our collection view’s content at viewWillAppear: and viewDidAppear:. Off screen cells get resized to their estimatedItemSize.</figcaption></figure><p>However, when scrolling up, Auto Layout calculates the <em>actual size</em> for cells that are about to appear on screen, and replaces the estimated size with the actual size. This sudden change results in the collection view appearing to “jump” as you scroll up the screen.</p><h4><strong>What about UICollectionViewFlowLayoutEstimatedSize?</strong></h4><p>In iOS 10, Apple introduced an analog to UITableViewAutomaticDimension. The new constant is called UICollectionViewFlowLayoutEstimatedSize and you can return it from UICollectionViewFlowLayoutDelegate&#39;s -[collectionView: layout: sizeForItemAtIndexPath:] method. If you return this constant, the system will dynamically update the estimatedItemSize as cell sizes are calculated. Check out <a href="https://developer.apple.com/videos/play/wwdc2016/219/">WWDC 2016 Session 219</a> for more information and a cool visualization of how estimatedItemSize gets used.</p><p><a href="https://developer.apple.com/videos/play/wwdc2016/219/">What&#39;s New in UICollectionView in iOS 10 - WWDC 2016 - Videos - Apple Developer</a></p><p>Unfortunately, dynamically changing estimatedItemSize does not solve our problem, it only makes it less obvious. Every off-screen item is still using estimatedItemSize, and when that size has to be replaced by the actual size, the same choppy behavior will occur.</p><h3>Misplaced Supplementary Views</h3><p>We didn’t investigate this issue much ourselves, but according to this <a href="https://stackoverflow.com/questions/40129245/ios-10-11-uicollectionviewflowlayout-using-uicollectionviewflowlayoutautomaticsi">post</a> from Stack Overflow:</p><blockquote>Each time when auto layout code updates cell’s frame it does nothing with headers and footers.</blockquote><p>The post suggests overriding a method on UICollectionViewFlowLayout to invalidate supplementary view layouts. This solution did not work for us, so we developed our own solution.</p><h3>The Solution: Do It Yourself</h3><p>Since Apple’s out-of-the-box implementation of self-sizing collection view cells was not working for us, we decided to do it ourselves (don’t worry, it is not as scary as it sounds). We basically use the old, “traditional” way of laying out collection views and simply incorporate self-sizing cells into it. I imagine this is how developers implemented self-sizing cells in UICollectionView prior to the introduction of estimatedItemSize in 2014.</p><p>At a high level, our implementation is as follows:</p><ol><li>Use a sizing cell to compute the required size of a cell using Auto Layout.</li><li>Cache that size in memory, and return it in UICollectionViewDelegateFlowLayout&#39;s -[collectionView: layout: sizeForItemAtIndexPath:] method.</li></ol><h4>Step 1: Create a Sizing Cell</h4><p>In order to save on instantiation costs, we recommend creating a singleton instance of your cell class to use as a <strong>sizing cell</strong>. This can be easily accomplished by adding the following method to your cell class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4959fbf6103ca94a437335a76361a38/href">https://medium.com/media/a4959fbf6103ca94a437335a76361a38/href</a></iframe><p><strong>Pro-Tip:</strong> If your cell uses a XIB, then you should replace sizingCell = [self new] with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1e0c62e41c25cdbe1a17567ee570942/href">https://medium.com/media/d1e0c62e41c25cdbe1a17567ee570942/href</a></iframe><h4>Step 2: Share Your Cell Configuration Logic</h4><p>Usually we keep our cell configuration logic in -[collectionView: cellForItemAtIndexPath:]. Since this is where we are dequeuing the cell, it is a natural place for us to configure the cell prior to returning it.</p><p>However, in order to utilize our new <strong>sizing cell</strong>, we will need our cell configuration logic to be in a place that is accessible to both -[collectionView: cellForItemAtIndexPath:] and -[collectionView: layout: sizeForItemAtIndexPath:].</p><p>In this example, we will assume all configuration is done in a view controller method called -[configureCell: atIndexPath:].</p><p><strong>Pro-Tip:</strong> If you call -[collectionView: cellForItemAtIndexPath:] from inside-[collectionView: layout: sizeForItemAtIndexPath:], you’re gonna have a bad time. Like, infinite loop bad time.</p><h4>Step 3: Compute the Required Size</h4><p>Once the configuration logic is accessible, you can use your <strong>sizing cell</strong> to compute the size of your cell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/313c65adf840147d8254240d157c3e7a/href">https://medium.com/media/313c65adf840147d8254240d157c3e7a/href</a></iframe><p>Be sure to use the same configuration logic when vending cells to the collection view, so that your computed size is consistent with what you’re showing on screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aba30575e8bf3973d572117a7f6d479/href">https://medium.com/media/8aba30575e8bf3973d572117a7f6d479/href</a></iframe><h4>Step 4: Cache the Computed Size</h4><p>Technically, Step 3 is as far as you need to go to solve the choppy scrolling and supplementary view problems we described. However, it is pretty bad for performance if your app has to recompute the size of your cells every time they are about to appear on screen.</p><p>To solve that performance issue, we go one step further and cache the computed sizes in memory. Simply create a dictionary, make a key that uniquely identifies your cell <strong>with respect to its size</strong>, and add your computed size to the dictionary. Then, return the cached value instead of re-computing the size of your cell again.</p><p><strong>Pro-Tip: </strong>You can store a CGSize in a dictionary with +[NSValue valueWithCGSize:]. You can turn the NSValue object back into a CGSize with .CGSizeValue.</p><p><strong>Pro-Tip:</strong> If the order and contents of your cells never change, indexPath will uniquely describe your cell, and you can use it as your key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7f9fb95a2c41fe0ebd96aaef965568b/href">https://medium.com/media/c7f9fb95a2c41fe0ebd96aaef965568b/href</a></iframe><h4>Step 5: ???</h4><p>Drink some coffee.</p><h4>Step 6: Profit</h4><p>Go treat yourself to something nice and enjoy the buttery smooth scrolling of your dynamically sized collection view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*KiBNmiRrARxEQcaQFzie8g.gif" /><figcaption>mmm…butter…</figcaption></figure><h3>Shameless Plug</h3><p>Spring is <a href="http://grnh.se/7ofi14">hiring</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4010c02fbaae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/misplaced-views-and-choppy-scrolling-with-dynamically-sized-collection-view-cells-4010c02fbaae">Misplaced Views and Choppy Scrolling with Dynamically Sized UICollectionViewCells</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Cell Sizing in UICollectionView]]></title>
            <link>https://medium.com/spring-engineering/dynamic-cell-sizing-in-uicollectionview-fd95f614ef80?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/fd95f614ef80</guid>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[autolayout]]></category>
            <dc:creator><![CDATA[Alan Wang]]></dc:creator>
            <pubDate>Tue, 09 May 2017 01:03:35 GMT</pubDate>
            <atom:updated>2018-10-03T12:12:49.705Z</atom:updated>
            <content:encoded><![CDATA[<p>Often times when using a UITableView or UICollectionView, we want to give our cells the ability to adjust their sizes based on their content. For example, if one cell has three words, and another cell contains the unabridged text of A Song of Ice And Fire, it doesn’t really make sense for both of these cells to be the same size.</p><p>For UITableView, allowing a cell to size itself via Auto Layout is fairly straightforward and well documented in Stack Overflow and various tutorials. More or less, just set the table view’s row height to UITableViewAutomaticDimension.</p><p>For UICollectionView however, the solution is a little less obvious. When I was trying to figure it out, a Google search turned up several different solutions, some of which seemed hackier than others. It wasn’t clear to me what the “right” or cleanest way to accomplish dynamically sized cells was, or whether this was even a thing supported by Apple (spoiler alert: it is.)</p><p>In 2014, Apple released iOS 8, which included support for dynamically sized table and collection view cells (they called it “self sizing cells,” which explains why my Google search for “dynamically sized cells” didn’t go so well). You can check it out in <a href="https://developer.apple.com/videos/play/wwdc2014/226/">What’s New in Table and Collection Views (WWDC 2014, Session 226)</a>.</p><p><a href="https://developer.apple.com/videos/play/wwdc2014/226/">What&#39;s New in Table and Collection Views - WWDC 2014 - Videos - Apple Developer</a></p><p>In this article, we’ll talk about how to create self sizing collection view cells, how to set one or both dimensions of a self sizing cell, and some common pitfalls when creating self sizing cells.</p><h3>How To Make A Collection View With Self Sizing Cells</h3><p>So how do you make this lovely feature your own? Apple provides several ways to do it (as outlined in the above video), but we’ll be specifically exploring the common case of using <strong>Auto Layout</strong> with a <strong>UICollectionViewFlowLayout</strong>.</p><p>There are two things you need to create a self sizing cell:</p><ol><li>Set estimatedItemSize on your layout.</li><li>A cell whose width and height are fully determined by its constraints and content.</li></ol><h4>Set estimatedItemSize on your layout to a non-zero CGSize.</h4><pre>layout.estimatedItemSize = CGSizeMake(1.f, 1.f);</pre><p>If your collection view is created by a XIB, you will need to create a property with an IBOutlet and connect it to your collection view’s layout in order to set estimatedItemSize. There should be a Layout placeholder available in Interface Builder for you to control+drag to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evHJCgMSw0XZhkDUys32xw.png" /></figure><p>If your collection view is created programmatically, you would have had to instantiate a UICollectionViewFlowLayout so you can just set the property on that.</p><p>Setting estimatedItemSize indicates to your flow layout that it should ask the collection view and its cells for updated layout attributes before returning the final layout attributes to your collection view.</p><p>It’s unclear to me what the best thing to set estimatedItemSize to is, but I haven’t run into any problems yet with just making it tiny. This <a href="https://possiblemobile.com/2016/02/sizing-uicollectionviewcell-fit-multiline-uilabel/">article by Jeremiah Gage</a> suggests setting it low, so that’s what I’ve done.</p><h4>Create constraints such that cell width and height can be determined</h4><p>Remember that a constraint is simply a mathematical equation relating one dimension to another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zj00w14KL5e5zq7syPcGYg.png" /><figcaption><a href="https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/AnatomyofaConstraint.html#//apple_ref/doc/uid/TP40010853-CH9-SW1">Anatomy of a Constraint</a></figcaption></figure><p>Let’s say you have a constraint that says the width of your UILabel should be equal to 2/3 the width of your cell’s contentView. This means that you have to know the width of one in order to know the width of the other. Either you can:</p><ol><li>Define the cell width and have the label width follow (i.e. the traditional way), or</li><li>Define the label width and have the cell width follow (i.e. the self sizing way).</li></ol><p>In a self sizing cell, Auto Layout will use your views’ intrinsicContentSize to define the size of those views. intrinsicContentSize is a property of UIView that represents how large the view needs to be to show the contents of that view. For example, the intrinsicContentSize of a UILabel is the size of the label’s text.</p><p>Auto Layout will use the size of those views to calculate the size of your cell based on your constraints. It is your responsibility to ensure that you can math your way from the size of your cell’s subviews to the size of your cell. If you can do it, then so can Auto Layout.</p><h3>Setting Cell Dimensions From Outside the Cell</h3><p>So self sizing cells are great and all, but what if we <strong>want</strong> to set the width and/or height of the cell? For example, maybe we want our cell’s width to be equal to the collection view’s width, or maybe we want some cells to be self-sizing, but others to not be.</p><p>The solution is pretty simple — create a width and/or height constraint on your cell’s contentView and create setters to set their value from outside the cell.</p><p><strong>Important:</strong> Make sure your constraints are on the cell’s contentView and not the cell itself, or else you’re gonna have a bad time. Also, don’t forget to set self.contentView.translatesAutoresizingMaskIntoConstraints = NO;, otherwise you’ll end up with conflicting constraints.</p><p>Here’s some sample code. In the .h:</p><pre>@interface MYAwesomeCell : UICollectionViewCell</pre><pre>- (void)setCellWidth:(CGFloat) width;</pre><pre>@end</pre><p>And in the .m:</p><pre>@interface MYAwesomeCell()</pre><pre>@property (nonatomic, strong) NSLayoutConstraint *cellWidthConstraint;</pre><pre>@end</pre><pre>@implementation MYAwesomeCell</pre><pre>- (void)awakeFromNib {<br>    [super awakeFromNib];</pre><pre>    // Cell dimension constraints code<br>    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;<br>    self.cellWidthConstraint = [self.contentView.widthAnchor constraintEqualToConstant:0.f];<br>}</pre><pre>- (void)setCellWidth:(CGFloat) width {<br>    self.cellWidthConstraint.constant = width;<br>    self.cellWidthConstraint.active = YES;<br>}</pre><pre>@end</pre><p>If you’re not using a NIB, put the constraint logic into your cell&#39;s initWithFrame: rather than awakeFromNib.</p><p>Now, you can set your cell’s width from anywhere that has access to the cell!</p><h3>Troubleshooting</h3><h4>My cells all appear as little squares</h4><p>If Auto Layout isn’t able to determine the size of your cell from your content and constraints, it will fall back to the traditional approach and assign your cell a size from either the layout’s itemSize property or collectionView:layout:sizeForItemAtIndexPath: delegate method.</p><p>The default itemSize is 50x50 so that’s why your cells are all little squares. See the <a href="https://developer.apple.com/reference/uikit/uicollectionviewflowlayout/1617711-itemsize">Apple documentation</a> for reference.</p><h4>Check for multiline UILabels</h4><p>If your constraints look like they should be able to fully determine the size of the cell, but your cell isn’t getting sized properly, check to see if you have any multiline UILabels in your cell (i.e. UILabels with their numberOfLines set to anything but 1).</p><p>In a multiline UILabel, you can’t know the the height of the label unless you know the width of the label and vice versa — the label doesn’t know how many times it needs to wrap your lines unless it knows what its maximum width is. This means that the intrinsicContentSize of a multiline UILabel cannot be determined from its content alone. If your cell size depends on that intrinsicContentSize, then your cell size also cannot be determined.</p><p>In order to solve this issue, you must define one dimension of the label. Usually you’ll want to define the width and let the height grow. There are a couple ways to do this:</p><ol><li>Add a width constraint to the label.</li><li>Set the label’s preferredMaxLayoutWidth property.</li></ol><h4>Interface Builder is unhappy and keeps yelling at me =(</h4><p>That will happen. Haters gonna hate.</p><p>No but really, Interface Builder looks at the size of the cell in Interface Builder and tries to calculate the frames of your subviews based on that. In a self sizing cell, there should be one and only one size for your cell that satisfies all of your constraints. If your cell in Interface Builder isn’t that size, then it’s going to complain.</p><p>This can sometimes be solved by clicking on the Resolve Auto Layout Issues button. If Interface Builder has enough information to determine the size of the cell, it may resize the cell to the correct size.</p><p>However, sometimes Interface Builder doesn’t have enough information because you may be adding or modifying constraints and properties from your code. In these cases, Interface Builder will just have to be unhappy.</p><h4>I get an error that my cell’s width has to be less than my collection view width</h4><p>Yea, I got that too and I think it’s probably a bug where someone at Apple put a &lt; when they should have put a &lt;=. Just make it 1 point less or something.</p><h4>My cells don’t change size when I reload data</h4><p>Call invalidateLayout on your collection view’s layout. Your data may have changed, but you need to indicate that the layout attributes need to be changed as well, in order to recalculate the correct sizes for your cells.</p><h4>Auto Layout works in strange and mysterious ways</h4><p>Check out these two sessions from WWDC 2015 that might help you understand it better.</p><ul><li><a href="https://developer.apple.com/videos/play/wwdc2015/218/">Mysteries of Auto Layout, Part 1 - WWDC 2015 - Videos - Apple Developer</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2015/219/">Mysteries of Auto Layout, Part 2 - WWDC 2015 - Videos - Apple Developer</a></li></ul><h4>My supplementary views are misaligned and my scrolling is choppy</h4><p>We also encountered these issues soon after implementing the methods described in this blog post. In the end, this appears to be a problem with the way the system framework uses estimatedItemSize for collection views. I’ve detailed our workaround in this <a href="https://medium.com/@alan.wang_54993/misplaced-views-and-choppy-scrolling-with-dynamically-sized-collection-view-cells-4010c02fbaae">followup blog post</a>:</p><p><a href="https://medium.com/@alan.wang_54993/misplaced-views-and-choppy-scrolling-with-dynamically-sized-collection-view-cells-4010c02fbaae">Misplaced Views and Choppy Scrolling with Dynamically Sized Collection View Cells</a></p><h3>Closing</h3><p>Hope this post helps you guys create some awesome, dynamically sized collection view cells! Now go freshen up on that Auto Layout-fu.</p><p>P.S. Shameless plug: <a href="http://grnh.se/7ofi14">Spring is hiring</a>.</p><h3>Resources</h3><ul><li><a href="https://developer.apple.com/videos/play/wwdc2014/226/">What’s New in Table and Collection Views (WWDC 2014, Session 226)</a></li><li><a href="https://possiblemobile.com/2016/02/sizing-uicollectionviewcell-fit-multiline-uilabel/">Sizing a UICollectionViewCell To Fit A Multiline UILabel</a></li><li><a href="https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/index.html#//apple_ref/doc/uid/TP40010853-CH7-SW1">Auto Layout Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd95f614ef80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/dynamic-cell-sizing-in-uicollectionview-fd95f614ef80">Dynamic Cell Sizing in UICollectionView</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decimal: an arbitrary-precision fixed-point decimal library for Go]]></title>
            <link>https://medium.com/spring-engineering/decimal-an-arbitrary-precision-fixed-point-decimal-library-for-go-ff8b31ca7a5f?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/ff8b31ca7a5f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Victor Quinn]]></dc:creator>
            <pubDate>Fri, 24 Feb 2017 17:13:49 GMT</pubDate>
            <atom:updated>2017-02-24T17:13:38.652Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, we’re releasing our <a href="https://github.com/shopspring/decimal">arbitrary-precision decimal library for Go</a>.</p><p>You can get it by running: go get github.com/shopspring/decimal</p><h3>Motivation</h3><p>When dealing with money, rounding errors are undesirable. Unfortunately, <a href="http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/">floating point numbers can’t represent fractional decimals (ex: 0.1) precisely</a>, so adding and subtracting them repeatedly will cause rounding errors. For example, consider this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb197855602dd1a8cab8a21575f10627/href">https://medium.com/media/fb197855602dd1a8cab8a21575f10627/href</a></iframe><p>You might expect it to print 10, but in fact it prints 9.999999999999831. Over time, these errors can accumulate, and eventually you might be missing a few dollars with no idea where it went. That’s why most accounting systems use decimal numbers when dealing with money.</p><h3>Why we had to write our own</h3><p>Unfortunately, Go doesn’t have a built-in decimal library. The best option we found was <a href="https://github.com/oguzbilgic/fpd">fpd.Decimal</a>. However, we quickly ran into many issues:</p><ul><li>Lack of features — fpd.Decimal didn’t support creating a Decimal by parsing a string.</li><li>Bugs — Decimal.Add isn’t commutative, and sometimes loses precision.</li><li>Strange API — Decimal.String() returns the string representation of the decimal, but without the decimal point.</li><li>Dangerous — operating on an uninitialized Decimal causes a nil pointer panic. When you have many Decimals as part of a struct, making sure they’re always initialized is a pain.</li></ul><p>We had to rewrite most of fpd.Decimal and change its API significantly to make it usable for our purposes. Because the API changes broke backwards compatibility, we decided to release it as a separate open source library.</p><h3>How our library works</h3><p>A decimal number is represented by an integer coefficient and an integer exponent, with the number = coefficient * 10 ^ exponent.</p><ul><li>Addition/Subtraction converts the decimal with the higher exponent to an equivalent decimal with an exponent equal to the other decimal, then adds the coefficients together.</li><li>Multiplication multiplies the coefficients and adds the exponents: (a1 * 10 ^ e1) * (a2 * 10 ^ e2) = (a1 * a2) * 10 ^ (e1 + e2)</li><li>Division is sometimes impossible without a loss of precision. For example, 1 / 3 cannot be represented with a finite number of decimal digits. Decimal libraries typically allow you to specify a precision for division to handle cases like this. Division is tricky to implement so we sacrificed execution speed for correctness and used Go’s big.Rat library. We convert the decimals to big.Rat, convert the result of the division to a string and parse it to get the resultant decimal.</li><li>Before each operation, we ensure the decimal is initialized, thus decimal’s zero-value is 0 as you’d expect.</li></ul><h3>Final thoughts</h3><p>We believe our decimal library offers a clean API that’s consistent with other Go packages such as big.Int. The mathematical operations are implemented correctly and are tested thoroughly. The zero-value of a Decimal is 0, just like a regular int or float64, which makes it easy to use within structs. You can serialize/deserialize to JSON, XML, or your SQL database without writing any additional code. And, it’s been used in production at <a href="https://www.shopspring.com/">Spring</a> for over 6 months with no issues.</p><p>We are committed to using this open-sourced version internally, and we’ll release all fixes and improvements publicly. We hope that you’ll find this library useful, and we welcome pull requests!</p><p><em>Originally published by Vadim Graboys at </em><a href="http://engineering.shopspring.com/2015/03/03/decimal/"><em>engineering.shopspring.com</em></a><em> on March 3, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff8b31ca7a5f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/decimal-an-arbitrary-precision-fixed-point-decimal-library-for-go-ff8b31ca7a5f">Decimal: an arbitrary-precision fixed-point decimal library for Go</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated iOS Integration Testing in a real world consumer app — at Spring]]></title>
            <link>https://medium.com/spring-engineering/automated-ios-integration-testing-in-a-real-world-consumer-app-at-spring-4a2b758b47cc?source=rss----531ed8344feb---4</link>
            <guid isPermaLink="false">https://medium.com/p/4a2b758b47cc</guid>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Victor Quinn]]></dc:creator>
            <pubDate>Fri, 24 Feb 2017 16:50:16 GMT</pubDate>
            <atom:updated>2017-02-24T16:49:10.906Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever since we started <a href="https://www.shopspring.com/">Spring</a> we’ve set up a <a href="http://jenkins-ci.org/">continuous build</a> and integration tests. We decided to start testing when our team was two engineers and we knew what we were building.</p><p>Testing an app and its backends manually is very time-consuming, and when we did find critical issues we wanted to guard ourselves against breaking them a second time. We believe that having tests allowed us to move more predictably and faster over time.</p><p>Writing and maintaining tests can sometimes feel like a distraction, but if you integrate them into your development process we believe that the benefits are worth it.</p><p>Before going further, wanted to share a video of how our tests look like when they are running. Our whole suite of tests takes about 10 minutes, so I’ve cut the video down to only a minute.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-UVkVXbX8zw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-UVkVXbX8zw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-UVkVXbX8zw%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/446ef69fcf9856684df8bd2da53de9b9/href">https://medium.com/media/446ef69fcf9856684df8bd2da53de9b9/href</a></iframe><p>Early on we decided to focus on <strong>end-to-end tests</strong> as opposed to unit tests. This choice was a natural one for us:</p><ul><li>as a pragmatic engineering team we wanted to get as much code coverage with as little work as possible.</li><li>we knew what we wanted to build product-wise, but our backends were under heavy development and prone to frequent refactorings.</li></ul><h3>Broad level overview of our testing infrastructure</h3><p>In order to run end-to-end tests, from early on, we created a setup that would us to run our entire stack locally.</p><p>We run each binary in “test” mode, on top of a local test database (separate from the dev database), with binaries exposing paths like /tests/setup and /tests/teardown to be called by the app.</p><h3>Setting up the app</h3><p>We picked <a href="https://github.com/kif-framework/KIF">KIF</a> as a framework for a few reasons. It’s <a href="https://github.com/kif-framework/KIF#installation-from-github">easy enough to integrate</a>, supports the core actions we needed (waiting for views, tapping on views) and it’s easy to extend to other actions. KIF gives us access to resetting the app in between tests easily, and because of its excellent integration with Xcode it allows the developer to debug code as part of a test run.</p><p>KIF tests run as part of the app, on the main run thread, and with access to the entire app as it is running. Because of that we can control the /setup and /teardown of tests - we can log the user out, clean up app state, clean up the singletons we have and the data they store (like our event tracking).</p><p>Because the tests are ObjectiveC we can also extend the test primitives with custom expectations — for example we’ve written a waitForGetHttpRequest method, and a waitForNotification method.</p><p>It integrates nicely with Xcode and allows you to run tests individually, or test suites individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*WrKIiO-njWV7g2Pd.png" /></figure><p>KIF works by using the iOS accessibility framework to run a set of gestures and expect a set of outcomes for each test.</p><p>After giving your views accessibility labels, you use the KIF APIs to describe a set of gestures that the test should perform, and then an expected outcome. Contrary to popular claims, this does not make your app accessible.</p><p>The most common actions that we use are tapping on views and entering text in text fields, and the two most common outcomes are verifying that a view is on the screen, or verifying that a view is no longer on the screen.</p><p>For advanced test scenarios, KIF also allows you to scroll views programmatically, tap the status bar, and enter text.</p><p>(While there might be other frameworks that are also good choices, it isn’t the goal of the blog post to compare them — other frameworks may have some of these properties too.)</p><p>Here’s what a test at Spring looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa5353e14c76266d65dd87e886d5896c/href">https://medium.com/media/fa5353e14c76266d65dd87e886d5896c/href</a></iframe><p>Here’s what the SetUp method looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/370834744e29c458777c729cd99c88a7/href">https://medium.com/media/370834744e29c458777c729cd99c88a7/href</a></iframe><p>Notice how at the beginning of every test we take the following steps:</p><ul><li><strong>make a request to </strong><strong>localhost:3000/tests/reset</strong> which truncates the entire database. The server is set up in such a way that it only allows this to happen in test mode, and against a DB who’s name ends in _test.</li><li><strong>the app then does some client side cleanup</strong> — for us that means deleting our cache, clearing up our custom event tracking, creating a user and logging them in from the app.</li><li><strong>make a request to </strong><strong>localhost:3000/tests/setup?test=testBrandPageFollowing</strong> which knows how to create the right data that this test expects (see next section)</li><li><strong>initialize the app to the home state</strong> — for us a feed of products with the user being logged in.</li></ul><p>Server-side, we’re running the entire stack that the app depends on in “test” mode. What this means in practice is that we have a “-run_mode=test” flag on our binaries that, when set, will expose the three paths that we need - /tests/reset, /tests/setup and /tests/teardown.</p><ul><li><strong>The reset is simple</strong>: it truncates our DB. This code is well guarded and there are multiple checks in every function call — we really don’t want this code to make it to production.</li><li><strong>The </strong><strong>/tests/setup path takes a parameter </strong><strong>?name=testNameHere</strong> and, through some magic, calls a function with the same name on our backends that’s part of the SetUps singleton. That method inserts the right expected setup data in the database, and once that’s done, the KIF test can initialize the app and expect that the data that we’ve just created shows up in the right places.</li><li><strong>The </strong><strong>/tests/teardown?name=testNameHere is used to make assertions about server-side effects</strong> that we expect from the app - most importantly, our data tracking.<br>When run in Test Mode our backends use a mock SpringEventLog that records all the data that we send down from the app — and the teardown method can have expectations for the number of events that we expect to be sent, and some of the contents of those events (if that content is important to the test).<br>We consider this an amazing benefit of this piece of infrastructure — having to make sure manually that the app you’re about to release tracks the right data is something very time consuming and difficult to get right.</li></ul><h3>How our setup ties everything together</h3><p>Tests become a burden on a team unless they are tied and embedded into your team’s development process.</p><p>Having the tests run as part of your code review process, and having a continuous build that the team is always willing to fix, is important; otherwise, tests go easily out of date and easily become failing tests that nobody wants to fix.</p><p>We use <a href="http://phabricator.org/">Phabricator</a> for code reviews — our tests run whenever a <a href="http://phabricator.org/applications/differential/">diff is sent for review</a>, and reviewers sees all of the results.</p><p>Phabricator is not difficult to extend into doing this, though it does take a little bit of tinkering around to get it right. Let us know if you are interested in that <a href="/service/mailto:engineering@shopspring.com">over email</a>, and we can share what we’ve learned — but this is outside the scope of this blog post.</p><h3>Always room for improvement</h3><p>Right now our tests take about 10 minutes to run. This is somewhat slow and is causing some unhappiness on our engineering team — and will only increase as we add more tests.</p><p>The tests are not easily parallelizable, both due to the stateful way we Set Up and Tear Down the DB — but also due to the way KIF is set up. We might consider in the future sending separate test files to separate build machines — but we’re not there just yet.</p><p>But even so, after two years it seems like we’re not feeling huge pains and this is holding up pretty well.</p><h3>Closing thoughts</h3><p>These tests have been incredibly useful for us in allowing us to move fast and with confidence, and we’re excited to share what we’ve done with the world in the hope that it will inspire other people to do the same.</p><p>We’re looking forward to watching our testing process evolve, and seeing what it will look like a year from now. Until then, I hope this blog post was useful.</p><p>If you want to learn more we’d love to <a href="/service/mailto:engineering@shopspring.com">hear from you</a> and if you’d want to work on one of Apple’s Best Apps of 2014 as a full-time job —<a href="http://grnh.se/icdh7l1"> we’re hiring</a>.</p><p><em>Thanks to Bryan Irace, Brian Bonczek, Anoop Ranganath and Adam Ernst for reading drafts of this.</em></p><p><em>Originally published by Octavian Costache at </em><a href="http://engineering.shopspring.com/2015/03/02/ios-integration-tests/"><em>engineering.shopspring.com</em></a><em> on March 2, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a2b758b47cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-engineering/automated-ios-integration-testing-in-a-real-world-consumer-app-at-spring-4a2b758b47cc">Automated iOS Integration Testing in a real world consumer app — at Spring</a> was originally published in <a href="https://medium.com/spring-engineering">Spring Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>