text:
<?php

namespace Symfony\Component\Console;

class Terminal
{
    private static $width;
    private static $height;

    /**
     * Gets the terminal width.
     *
     * @return int
     */
    public function getWidth()
    {
        $width = getenv('COLUMNS');
        if (false !== $width) {
            return (int) trim($width);
        }

        if (null === self::$width) {
            self::initDimensions();
        }

        return self::$width ?: 80;
    }

    /**
     * Gets the terminal height.
     *
     * @return int
     */
    public function getHeight()
    {
        $height = getenv('LINES');
        if (false !== $height) {
            return (int) trim($height);
        }

        if (null === self::$height) {
            self::initDimensions();
        }

        return self::$height ?: 50;
    }

    private static function initDimensions()
    {
        if ('\\' === \DIRECTORY_SEPARATOR) {
            if (preg_match('/^(\d+)x(\d+)(?: \((\d+)x(\d+)\))?$/', trim(getenv('ANSICON')), $matches)) {
                // extract [w, H] from "wxh (WxH)"
                // or [w, h] from "wxh"
                self::$width = (int) $matches[1];
                self::$height = isset($matches[4]) ? (int) $matches[4] : (int) $matches[2];
            } elseif (null !== $dimensions = self::getConsoleMode()) {
                // extract [w, h] from "wxh"
                self::$width = (int) $dimensions[0];
                self::$height = (int) $dimensions[1];
            }
        } elseif ($sttyString = self::getSttyColumns()) {
            if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
                // extract [w, h] from "rows h; columns w;"
                self::$width = (int) $matches[2];
                self::$height = (int) $matches[1];
            } elseif (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
                // extract [w, h] from "; h rows; w columns"
                self::$width = (int) $matches[2];
                self::$height = (int) $matches[1];
            }
        }
    }

    /**
     * Runs and parses mode CON if it's available, suppressing any error output.
     *
     * @return int[]|null An array composed of the width and the height or null if it could not be parsed
     */
    private static function getConsoleMode(): ?array
    {
        $info = self::readFromProcess('mode CON');

        if (null === $info || !preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
            return null;
        }

        return [(int) $matches[2], (int) $matches[1]];
    }

    /**
     * Runs and parses stty -a if it's available, suppressing any error output.
     */
    private static function getSttyColumns(): ?string
    {
        return self::readFromProcess('stty -a | grep columns');
    }

    private static function readFromProcess(string $command): ?string
    {
        if (!\function_exists('proc_open')) {
            return null;
        }

        $descriptorspec = [
            1 => ['pipe', 'w'],
            2 => ['pipe', 'w'],
        ];

        $process = proc_open($command, $descriptorspec, $pipes, null, null, ['suppress_errors' => true]);
        if (!\is_resource($process)) {
            return null;
        }

        $info = stream_get_contents($pipes[1]);
        fclose($pipes[1]);
        fclose($pipes[2]);
        proc_close($process);

        return $info;
    }
}


text:
<?php
/**
 * The template for displaying full width pages.
 *
 * Template Name: Full width, no title (SiteOrigin Page builder Template)
 *
 */

get_header(); ?>

					<?php
					/**
					 * @hooked woocommerce_breadcrumb - 10
					 */
					do_action( 'shop_isle_content_top' ); ?>

					<?php while ( have_posts() ) : the_post(); ?>

						<?php
						do_action( 'shop_isle_page_before' );
						?>

						<?php get_template_part( 'content', 'page' ); ?>

						<?php
						/**
						 * @hooked shop_isle_display_comments - 10
						 */
						do_action( 'shop_isle_page_after' );
						?>

					<?php endwhile; // end of the loop. ?>

<?php get_footer(); ?>

redpajama_set_name: RedPajamaGithub


text:
import {assert, test} from 'j0';
export default function tests(LOG10E, title) {

    test(title, (test) => {

        test('should be approximately equal to 0.4342944819032518', () => {
            const expected = 0.4342944819032518;
            assert.approxEqual(LOG10E, expected);
        });

    });

}


text:
const path = require('path');
const _ = require('lodash');
const stripBanner = require('rollup-plugin-strip-banner');
const license = require('rollup-plugin-license');
const conf = require('../conf');

module.exports = {
  input: path.join(conf.src, 'index.js'),
  external: _.keys(conf.globals),

  output: {
    file: path.join(conf.dist, conf.bundle),
    format: 'es',
    globals: conf.globals,
  },

  plugins: [
    stripBanner(),
    license({
      banner: {
        content: {
          file: conf.license,
        },
      },
    }),
  ],
};


text:
package com.madebyatomicrobot.vinyl.samples.multipleparent;

import com.madebyatomicrobot.vinyl.annotations.Record;

@Record
public interface Child extends Dad, Mom {
    String child();
}


text:
// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_CROSS_THREAD_SIGNAL_HPP_
#define CONCURRENCY_CROSS_THREAD_SIGNAL_HPP_

#include "concurrency/signal.hpp"
#include "concurrency/auto_drainer.hpp"

class cross_thread_signal_t;

class cross_thread_signal_subscription_t : public signal_t::subscription_t {
public:
    cross_thread_signal_subscription_t(cross_thread_signal_t *parent,
                                       auto_drainer_t::lock_t keepalive)
        : parent_(parent), keepalive_(keepalive) { }

    virtual void run();

private:
    cross_thread_signal_t *parent_;
    auto_drainer_t::lock_t keepalive_;
    DISABLE_COPYING(cross_thread_signal_subscription_t);
};

/* `cross_thread_signal_t` is useful when you have a `signal_t` on some
thread, but you wish you had the same `signal_t` on a different thread.
Construct a `cross_thread_signal_t` on the original thread, and pass the new
thread to its constructor. It will deliver a notification to the specified
thread when the original signal is pulsed. */

class cross_thread_signal_t :
    public signal_t
{
public:
    cross_thread_signal_t(signal_t *source, threadnum_t dest_thread);

private:
    friend class cross_thread_signal_subscription_t;
    void on_signal_pulsed(auto_drainer_t::lock_t);
    void deliver(auto_drainer_t::lock_t);

    threadnum_t source_thread;
    threadnum_t dest_thread;

    /* This object's constructor rethreads our internal `signal_t` to our other
    thread, and then reverses it in the destructor. It must be a separate object
    instead of logic in the constructor/destructor because its destructor must
    be run after `drainer`'s destructor. */
    class rethreader_t {
    public:
        rethreader_t(signal_t *s, threadnum_t dest) :
            signal(s), original(signal->home_thread())
        {
            signal->rethread(dest);
        }
        ~rethreader_t() {
            signal->rethread(original);
        }
    private:
        signal_t *const signal;
        const threadnum_t original;
    } rethreader;

    /* `drainer` makes sure we don't shut down with a signal still in flight */
    auto_drainer_t drainer;

    /* The destructor for `subs` must be run before the destructor for `drainer`
    because `drainer`'s destructor will block until all the
    `auto_drainer_t::lock_t` objects are gone, and `subs`'s callback holds an
    `auto_drainer_t::lock_t`. */
    cross_thread_signal_subscription_t subs;
};

#endif /* CONCURRENCY_CROSS_THREAD_SIGNAL_HPP_ */


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <billNumber>599</billNumber>
    <calendarNumbers />
    <billType>S</billType>
    <laws />
    <policyArea>
      <name>Public Lands and Natural Resources</name>
    </policyArea>
    <titles>
      <item>
        <title>Indiana Dunes National Park Designation Act</title>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <parentTitleType />
        <chamberName />
        <chamberCode />
      </item>
      <item>
        <title>Indiana Dunes National Park Designation Act</title>
        <titleType>Short Titles as Introduced</titleType>
        <parentTitleType />
        <chamberName />
        <chamberCode />
      </item>
      <item>
        <title>A bill to redesignate the Indiana Dunes National Lakeshore as the "Indiana Dunes National Park", and for other purposes.</title>
        <titleType>Official Title as Introduced</titleType>
        <parentTitleType />
        <chamberName />
        <chamberCode />
      </item>
      <item>
        <title>Indiana Dunes National Park Designation Act</title>
        <titleType>Display Title</titleType>
        <parentTitleType />
        <chamberName />
        <chamberCode />
      </item>
    </titles>
    <version>1.0.0</version>
    <sponsors>
      <item>
        <firstName>Joe</firstName>
        <state>IN</state>
        <lastName>Donnelly</lastName>
        <fullName>Sen. Donnelly, Joe [D-IN]</fullName>
        <middleName />
        <byRequestType />
        <identifiers>
          <gpoId>7941</gpoId>
          <bioguideId>D000607</bioguideId>
          <lisID>1850</lisID>
        </identifiers>
        <bioguideId>D000607</bioguideId>
        <party>D</party>
      </item>
    </sponsors>
    <actions>
      <item>
        <actionDate>2017-03-09</actionDate>
        <committee>
          <name>Energy and Natural Resources Committee</name>
          <systemCode>sseg00</systemCode>
        </committee>
        <links />
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Read twice and referred to the Committee on Energy and Natural Resources.</text>
        <type>IntroReferral</type>
      </item>
      <item>
        <links />
        <text>Introduced in Senate</text>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <committee />
        <actionDate>2017-03-09</actionDate>
        <type>IntroReferral</type>
        <actionCode>10000</actionCode>
      </item>
      <actionTypeCounts>
        <referredToCommittee>1</referredToCommittee>
        <introducedInSenate>1</introducedInSenate>
      </actionTypeCounts>
      <actionByCounts>
        <senate>2</senate>
      </actionByCounts>
    </actions>
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Great Lakes</name>
          </item>
          <item>
            <name>Indiana</name>
          </item>
          <item>
            <name>Parks, recreation areas, trails</name>
          </item>
          <item>
            <name>Seashores and lakeshores</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Public Lands and Natural Resources</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <committeeReports />
    <recordedVotes />
    <relatedBills>
      <item>
        <type>HR</type>
        <latestAction>
          <text>Referred to the Subcommittee on Federal Lands.</text>
          <actionDate>2017-03-20</actionDate>
        </latestAction>
        <number>1488</number>
        <congress>115</congress>
        <latestTitle>Indiana Dunes National Park Act</latestTitle>
        <relationshipDetails>
          <item>
            <type>Related bill</type>
            <identifiedBy>CRS</identifiedBy>
          </item>
        </relationshipDetails>
      </item>
    </relatedBills>
    <notes />
    <createDate>2017-03-10T05:16:41Z</createDate>
    <title>Indiana Dunes National Park Designation Act</title>
    <cosponsors>
      <item>
        <state>IN</state>
        <middleName>C.</middleName>
        <lastName>Young</lastName>
        <firstName>Todd</firstName>
        <sponsorshipWithdrawnDate />
        <fullName>Sen. Young, Todd C. [R-IN]</fullName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>Y000064</bioguideId>
        <party>R</party>
        <identifiers>
          <bioguideId>Y000064</bioguideId>
          <lisID>2019</lisID>
          <gpoId>7948</gpoId>
        </identifiers>
        <sponsorshipDate>2017-03-09</sponsorshipDate>
      </item>
    </cosponsors>
    <committees>
      <billCommittees>
        <item>
          <subcommittees />
          <systemCode>sseg00</systemCode>
          <name>Energy and Natural Resources Committee</name>
          <type>Standing</type>
          <chamber>Senate</chamber>
          <activities>
            <item>
              <date>2017-03-09T20:04:45Z</date>
              <name>Referred to</name>
            </item>
          </activities>
        </item>
      </billCommittees>
    </committees>
    <amendments />
    <cboCostEstimates />
    <summaries>
      <billSummaries>
        <item>
          <text><![CDATA[
Indiana Dunes National Park Designation Act

This bill renames the Indiana Dunes National Lakeshore as the Indiana Dunes National Park.
]]></text>
          <versionCode>00</versionCode>
          <actionDate>2017-03-09</actionDate>
          <actionDesc>Introduced in Senate</actionDesc>
          <lastSummaryUpdateDate>2017-08-19T12:42:57Z</lastSummaryUpdateDate>
          <updateDate>2017-03-09T05:00:00Z</updateDate>
          <name>Introduced in Senate</name>
        </item>
      </billSummaries>
    </summaries>
    <congress>115</congress>
    <updateDate>2017-09-11T02:39:42Z</updateDate>
    <latestAction>
      <text>Read twice and referred to the Committee on Energy and Natural Resources.</text>
      <links />
      <actionDate>2017-03-09</actionDate>
    </latestAction>
    <originChamber>Senate</originChamber>
    <introducedDate>2017-03-09</introducedDate>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
<?xml version="1.0" encoding="utf-8"?>
<geo:GeodesyML gml:id="ASPA00USA" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:geo="urn:xml-gov-au:icsm:egeodesy:0.5" xmlns:gmd="http://www.isotc211.org/2005/gmd" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <geo:siteLog gml:id="aspa_20141125.log">
        <geo:formInformation>
    <geo:FormInformation gml:id="form-information">
            <geo:preparedBy>cors-adm</geo:preparedBy>
            <geo:datePrepared>2014-11-25</geo:datePrepared>
            <geo:reportType>Updated</geo:reportType>
            </geo:FormInformation>
        </geo:formInformation>
        <geo:siteIdentification>
            <geo:SiteIdentification gml:id="site-identification">
            <geo:siteName>American Samoa Power Authority</geo:siteName>
            <geo:fourCharacterID>ASPA</geo:fourCharacterID>
            <geo:monumentInscription></geo:monumentInscription>
            <geo:iersDOMESNumber>50503S006</geo:iersDOMESNumber>
            <geo:cdpNumber></geo:cdpNumber>
            <geo:monumentDescription codeSpace="urn:ga-gov-au:monument-description-type">CONCRETE PILLAR</geo:monumentDescription>
            <geo:heightOfTheMonument>6.0</geo:heightOfTheMonument>
            <geo:monumentFoundation></geo:monumentFoundation>
            <geo:foundationDepth>2.5</geo:foundationDepth>
            <geo:markerDescription>none</geo:markerDescription>
            <geo:dateInstalled>2001-08-12T00:00:00Z</geo:dateInstalled>
            <geo:geologicCharacteristic codeSpace="urn:ga-gov-au:geologic-characteristic-type">BEDROCK</geo:geologicCharacteristic>
            <geo:bedrockType>IGNEOUS/METAMORPHIC</geo:bedrockType>
            <geo:bedrockCondition>FRESH</geo:bedrockCondition>
            <geo:fractureSpacing></geo:fractureSpacing>
            <geo:faultZonesNearby codeSpace="urn:ga-gov-au:fault-zones-type">NO</geo:faultZonesNearby>
            <geo:notes>The antenna is attached to a pillar via a tribrach adaptor. The pillar is of reinforced concrete and is 6m tall and ~0.75m wide with an additional 2.5m deep base. The base was dug out with a backhoe and has ~2x2x2 frame using 1 cm thick rebar was built with rebar attached to bedrock. Concrete was poured to fill the entire frame.</geo:notes>
            </geo:SiteIdentification>
        </geo:siteIdentification>
        <geo:siteLocation>
            <geo:SiteLocation gml:id="site-location">
            <geo:city>Pago Pago</geo:city>
            <geo:state>American Samoa</geo:state>
            <geo:countryCodeISO codeList="http://xml.gov.au/icsm/geodesyml/codelists/country-codes-codelist.xml#GeodesyML_CountryCode" codeListValue="United States" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">USA</geo:countryCodeISO>
            <geo:tectonicPlate codeSpace="urn:ga-gov-au:plate-type">PACIFIC</geo:tectonicPlate>
            <geo:approximatePositionITRF>
                <geo:cartesianPosition>
                    <gml:Point gml:id="itrf_cartesian" srsName="EPSG:7789">
                        <gml:pos>-6100260.096 -996503.51 -1567977.812</gml:pos>
                    </gml:Point>
                </geo:cartesianPosition>
                <geo:geodeticPosition>
                    <gml:Point gml:id="itrf_geodetic" srsName="EPSG:7912">
                        <gml:pos>-14.3260944444 -170.722433333 53.7</gml:pos>
                    </gml:Point>
                </geo:geodeticPosition>
            </geo:approximatePositionITRF>
            <geo:notes>ARP IGS08 POSITION (EPOCH 2005.00)</geo:notes>
            </geo:SiteLocation>
        </geo:siteLocation>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-1">
                <geo:manufacturerSerialNumber>0220227236</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE 4700" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRIMBLE 4700</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:firmwareVersion>7.29</geo:firmwareVersion>
                <geo:elevationCutoffSetting>5.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2001-08-12T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved>2008-10-01T00:00:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2001-08-12T00:00:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-2">
                <geo:manufacturerSerialNumber>4733K06635</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRIMBLE NETR5</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:firmwareVersion>NP 3.50 / SP 0.00</geo:firmwareVersion>
                <geo:elevationCutoffSetting>5.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2008-10-01T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved>2009-06-19T00:00:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2008-10-01T00:00:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-3">
                <geo:notes>Switched on GLONASS tracking Switched off Everest Multipath</geo:notes>
                <geo:manufacturerSerialNumber>4733K06635</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRIMBLE NETR5</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:firmwareVersion>NP 3.50 / SP 0.00</geo:firmwareVersion>
                <geo:elevationCutoffSetting>5.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2009-06-19T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved>2009-08-25T19:31:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2009-06-19T00:00:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-4">
                <geo:manufacturerSerialNumber>4733K06635</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRIMBLE NETR5</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:firmwareVersion>4.03</geo:firmwareVersion>
                <geo:elevationCutoffSetting>5.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2009-08-25T19:31:00Z</geo:dateInstalled>
                <geo:dateRemoved>2011-01-10T18:31:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2009-08-25T19:31:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-5">
                <geo:manufacturerSerialNumber>4733K06635</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRIMBLE NETR5</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:firmwareVersion>4.19</geo:firmwareVersion>
                <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2011-01-10T18:31:00Z</geo:dateInstalled>
                <geo:dateRemoved>2012-10-16T18:46:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2011-01-10T18:31:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-6">
                <geo:manufacturerSerialNumber>4733K06635</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRIMBLE NETR5</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:firmwareVersion>4.22</geo:firmwareVersion>
                <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2012-10-16T18:46:00Z</geo:dateInstalled>
                <geo:dateRemoved>2014-04-11T15:15:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2012-10-16T18:46:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-7">
                <geo:notes>Corrected FW from 4.42 to 4.41 on 2014-apr-22</geo:notes>
                <geo:manufacturerSerialNumber>4733K06635</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRIMBLE NETR5</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:firmwareVersion>4.41</geo:firmwareVersion>
                <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2014-04-11T15:15:00Z</geo:dateInstalled>
                <geo:dateRemoved>2014-10-21T13:03:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2014-04-11T15:15:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-8">
                <geo:manufacturerSerialNumber>4733K06635</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRIMBLE NETR5</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:firmwareVersion>4.85</geo:firmwareVersion>
                <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2014-10-21T13:03:00Z</geo:dateInstalled>
                <geo:dateRemoved></geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2014-10-21T13:03:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssAntenna>
            <geo:GnssAntenna gml:id="gnss-antenna-1">
                <geo:notes>radome is 15-inch clear hemispherical plastic</geo:notes>
                <geo:manufacturerSerialNumber>0220238085</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSAntennaTypeCode" codeListValue="TRM33429.20+GP UNAV" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRM33429.20+GP  UNAV</geo:igsModelCode>
                <geo:antennaReferencePoint codeSpace="urn:ga-gov-au:antenna-reference-point-type">BPA</geo:antennaReferencePoint>
                <geo:marker-arpUpEcc.>0.0</geo:marker-arpUpEcc.>
                <geo:marker-arpNorthEcc.>0.0</geo:marker-arpNorthEcc.>
                <geo:marker-arpEastEcc.>0.0</geo:marker-arpEastEcc.>
                <geo:alignmentFromTrueNorth xsi:nil="true"></geo:alignmentFromTrueNorth>
                <geo:antennaRadomeType codeSpace="urn:igs-org:gnss-radome-model-code">UNAV</geo:antennaRadomeType>
                <geo:radomeSerialNumber></geo:radomeSerialNumber>
                <geo:antennaCableType></geo:antennaCableType>
                <geo:antennaCableLength xsi:nil="true"></geo:antennaCableLength>
                <geo:dateInstalled>2001-08-12T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved>2008-10-01T00:00:00Z</geo:dateRemoved>
            </geo:GnssAntenna>
            <geo:dateInserted>2001-08-12T00:00:00Z</geo:dateInserted>
        </geo:gnssAntenna>
        <geo:gnssAntenna>
            <geo:GnssAntenna gml:id="gnss-antenna-2">
                <geo:manufacturerSerialNumber>30517456</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSAntennaTypeCode" codeListValue="TRM55971.00 NONE" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRM55971.00     NONE</geo:igsModelCode>
                <geo:antennaReferencePoint codeSpace="urn:ga-gov-au:antenna-reference-point-type">BAM</geo:antennaReferencePoint>
                <geo:marker-arpUpEcc.>0.0</geo:marker-arpUpEcc.>
                <geo:marker-arpNorthEcc.>0.0</geo:marker-arpNorthEcc.>
                <geo:marker-arpEastEcc.>0.0</geo:marker-arpEastEcc.>
                <geo:alignmentFromTrueNorth>0.0</geo:alignmentFromTrueNorth>
                <geo:antennaRadomeType codeSpace="urn:igs-org:gnss-radome-model-code">NONE</geo:antennaRadomeType>
                <geo:radomeSerialNumber></geo:radomeSerialNumber>
                <geo:antennaCableType>Trimble thick yellow cable</geo:antennaCableType>
                <geo:antennaCableLength>30.0</geo:antennaCableLength>
                <geo:dateInstalled>2008-10-01T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved></geo:dateRemoved>
            </geo:GnssAntenna>
            <geo:dateInserted>2008-10-01T00:00:00Z</geo:dateInserted>
        </geo:gnssAntenna>
        <geo:surveyedLocalTie>
            <geo:SurveyedLocalTie gml:id="local-tie-1">
                <geo:tiedMarkerName>FSF 1 AS 65 ASPA 2002</geo:tiedMarkerName>
                <geo:tiedMarkerUsage>LOCAL CONTROL</geo:tiedMarkerUsage>
                <geo:tiedMarkerCDPNumber></geo:tiedMarkerCDPNumber>
                <geo:tiedMarkerDOMESNumber></geo:tiedMarkerDOMESNumber>
                <geo:differentialComponentsGNSSMarkerToTiedMonumentITRS>
                    <geo:dx>-1.5782</geo:dx>
                    <geo:dy>-27.3256</geo:dy>
                    <geo:dz>46.1267</geo:dz>
                </geo:differentialComponentsGNSSMarkerToTiedMonumentITRS>
                <geo:localSiteTiesAccuracy>4.3</geo:localSiteTiesAccuracy>
                <geo:surveyMethod>GPS CAMPAIGN</geo:surveyMethod>
                <geo:dateMeasured>2002-08-01T00:00:00Z</geo:dateMeasured>
                <geo:notes>Marker is an NGS disk set in rock outcrop in Tafuna Village on Tutuila Island at the American Samoa Power Authority Wastewater Division offices.  Vector is weighted average of three 8-hr measurement sessions during 2002-07-30 thru 2002-08-02.</geo:notes>
            </geo:SurveyedLocalTie>
            <geo:dateInserted>2002-08-01T00:00:00Z</geo:dateInserted>
        </geo:surveyedLocalTie>
        <geo:surveyedLocalTie>
            <geo:SurveyedLocalTie gml:id="local-tie-2">
                <geo:tiedMarkerName>SATELLITE TRIANG STATION 022 1966</geo:tiedMarkerName>
                <geo:tiedMarkerUsage>LOCAL CONTROL</geo:tiedMarkerUsage>
                <geo:tiedMarkerCDPNumber></geo:tiedMarkerCDPNumber>
                <geo:tiedMarkerDOMESNumber></geo:tiedMarkerDOMESNumber>
                <geo:differentialComponentsGNSSMarkerToTiedMonumentITRS>
                    <geo:dx>311.2465</geo:dx>
                    <geo:dy>-845.8187</geo:dy>
                    <geo:dz>-603.4822</geo:dz>
                </geo:differentialComponentsGNSSMarkerToTiedMonumentITRS>
                <geo:localSiteTiesAccuracy>9.0</geo:localSiteTiesAccuracy>
                <geo:surveyMethod>GPS CAMPAIGN</geo:surveyMethod>
                <geo:dateMeasured>2002-08-01T00:00:00Z</geo:dateMeasured>
                <geo:notes>Benchmark disk set in top of concrete monument in the SW corner of the Weather Bureau Station grounds in Tafuna Village, about 0.2 mile SW of the Tafuna Airport Terminal Bldg.  Tie vector from same sessions as FSF 1 AS 65 ASPA.</geo:notes>
            </geo:SurveyedLocalTie>
            <geo:dateInserted>2002-08-01T00:00:00Z</geo:dateInserted>
        </geo:surveyedLocalTie>
        <geo:frequencyStandard>
            <geo:FrequencyStandard gml:id="frequency-standard-1">
                <geo:standardType codeSpace="urn:ga-gov-au:frequency-standard-type">INTERNAL</geo:standardType>
                <geo:inputFrequency xsi:nil="true"></geo:inputFrequency>
                <gml:validTime>
                    <gml:TimePeriod gml:id="frequency-standard-1--time-period-1">
                        <gml:beginPosition>2001-08-12</gml:beginPosition>
                        <gml:endPosition></gml:endPosition>
                    </gml:TimePeriod>
                </gml:validTime>
                <geo:notes></geo:notes>
            </geo:FrequencyStandard>
            <geo:dateInserted>2001-08-12</geo:dateInserted>
        </geo:frequencyStandard>
        <geo:siteContact gml:id="agency-1">
            <gmd:MD_SecurityConstraints>
                <gmd:classification gco:nilReason="missing"/>
            </gmd:MD_SecurityConstraints>
            <gmd:CI_ResponsibleParty>
                <gmd:individualName>
                    <gco:CharacterString>Connie Shimisaki</gco:CharacterString>
                </gmd:individualName>
                <gmd:organisationName>
                    <gco:CharacterString>American Samoa Power Authority</gco:CharacterString>
                </gmd:organisationName>
                <gmd:contactInfo>
                    <gmd:CI_Contact>
                        <gmd:phone>
                            <gmd:CI_Telephone>
                                <gmd:voice>
                                    <gco:CharacterString>684-699-8924</gco:CharacterString>
                                </gmd:voice>
                                <gmd:voice>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:voice>
                                <gmd:facsimile>
                                    <gco:CharacterString>684-699-8070</gco:CharacterString>
                                </gmd:facsimile>
                            </gmd:CI_Telephone>
                        </gmd:phone>
                        <gmd:address>
                            <gmd:CI_Address>
                                <gmd:deliveryPoint>
                                    <gco:CharacterString>Tafuna Power Plant Pago Pago, AS  96799</gco:CharacterString>
                                </gmd:deliveryPoint>
                                <gmd:city>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:city>
                                <gmd:postalCode>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:postalCode>
                                <gmd:country>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:country>
                                <gmd:electronicMailAddress>
                                    <gco:CharacterString>connies@aspower.com</gco:CharacterString>
                                </gmd:electronicMailAddress>
                            </gmd:CI_Address>
                        </gmd:address>
                    </gmd:CI_Contact>
                </gmd:contactInfo>
                <gmd:role>
                    <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue="pointOfContact"></gmd:CI_RoleCode>
                </gmd:role>
            </gmd:CI_ResponsibleParty>
        </geo:siteContact>
        <geo:siteContact gml:id="agency-2">
            <gmd:MD_SecurityConstraints>
                <gmd:classification gco:nilReason="missing"/>
            </gmd:MD_SecurityConstraints>
            <gmd:CI_ResponsibleParty>
                <gmd:individualName>
                    <gco:CharacterString>Momotu Laie-Togia</gco:CharacterString>
                </gmd:individualName>
                <gmd:organisationName>
                    <gco:CharacterString>American Samoa Power Authority</gco:CharacterString>
                </gmd:organisationName>
                <gmd:contactInfo>
                    <gmd:CI_Contact>
                        <gmd:phone>
                            <gmd:CI_Telephone>
                                <gmd:voice>
                                    <gco:CharacterString>684-699-8924</gco:CharacterString>
                                </gmd:voice>
                                <gmd:voice>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:voice>
                                <gmd:facsimile>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:facsimile>
                            </gmd:CI_Telephone>
                        </gmd:phone>
                        <gmd:address>
                            <gmd:CI_Address>
                                <gmd:deliveryPoint>
                                    <gco:CharacterString>Tafuna Power Plant Pago Pago, AS  96799</gco:CharacterString>
                                </gmd:deliveryPoint>
                                <gmd:city>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:city>
                                <gmd:postalCode>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:postalCode>
                                <gmd:country>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:country>
                                <gmd:electronicMailAddress>
                                    <gco:CharacterString>momotu@aspower.com</gco:CharacterString>
                                </gmd:electronicMailAddress>
                            </gmd:CI_Address>
                        </gmd:address>
                    </gmd:CI_Contact>
                </gmd:contactInfo>
                <gmd:role>
                    <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue="pointOfContact"></gmd:CI_RoleCode>
                </gmd:role>
            </gmd:CI_ResponsibleParty>
        </geo:siteContact>
        <geo:siteMetadataCustodian gml:id="agency-3">
            <gmd:MD_SecurityConstraints>
                <gmd:classification gco:nilReason="missing"/>
            </gmd:MD_SecurityConstraints>
            <gmd:CI_ResponsibleParty>
                <gmd:individualName>
                    <gco:CharacterString>Giovanni Sella NOAA-NGS</gco:CharacterString>
                </gmd:individualName>
                <gmd:organisationName>
                    <gco:CharacterString>NOAA-National Geodetic Survey</gco:CharacterString>
                </gmd:organisationName>
                <gmd:contactInfo>
                    <gmd:CI_Contact>
                        <gmd:phone>
                            <gmd:CI_Telephone>
                                <gmd:voice>
                                    <gco:CharacterString>301-713-3198x126</gco:CharacterString>
                                </gmd:voice>
                                <gmd:voice>
                                    <gco:CharacterString>301-713-2845</gco:CharacterString>
                                </gmd:voice>
                                <gmd:facsimile>
                                    <gco:CharacterString>301-713-4475</gco:CharacterString>
                                </gmd:facsimile>
                            </gmd:CI_Telephone>
                        </gmd:phone>
                        <gmd:address>
                            <gmd:CI_Address>
                                <gmd:deliveryPoint>
                                    <gco:CharacterString>NOAA, N/NGS6, SSMC3-9111 1315 East-West Hwy. Silver Spring, MD 20896, USA</gco:CharacterString>
                                </gmd:deliveryPoint>
                                <gmd:city>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:city>
                                <gmd:postalCode>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:postalCode>
                                <gmd:country>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:country>
                                <gmd:electronicMailAddress>
                                    <gco:CharacterString>ngs.corscollector@noaa.gov</gco:CharacterString>
                                </gmd:electronicMailAddress>
                            </gmd:CI_Address>
                        </gmd:address>
                    </gmd:CI_Contact>
                </gmd:contactInfo>
                <gmd:role>
                    <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue="pointOfContact"></gmd:CI_RoleCode>
                </gmd:role>
            </gmd:CI_ResponsibleParty>
        </geo:siteMetadataCustodian>
        <geo:moreInformation>
            <geo:MoreInformation gml:id="more-information">
            <geo:dataCenter>NOAA-NGS</geo:dataCenter>
            <geo:dataCenter>CDDIS</geo:dataCenter>
            <geo:urlForMoreInformation>http://geodesy.noaa.gov/CORS</geo:urlForMoreInformation>
            <geo:siteMap></geo:siteMap>
            <geo:siteDiagram></geo:siteDiagram>
            <geo:horizonMask></geo:horizonMask>
            <geo:monumentDescription></geo:monumentDescription>
            <geo:sitePictures></geo:sitePictures>
            <geo:notes></geo:notes>
            <geo:antennaGraphicsWithDimensions></geo:antennaGraphicsWithDimensions>
            <geo:insertTextGraphicFromAntenna></geo:insertTextGraphicFromAntenna>
            <geo:DOI codeSpace="urn:ga-gov-au:self.moreInformation-type">TODO</geo:DOI>
            </geo:MoreInformation>
        </geo:moreInformation>
    </geo:siteLog>
</geo:GeodesyML>


text:
var fs = require('fs');
var xml2js = require('xml2js');

exports = module.exports = function($) {
	var api = {};
	api.testMethod = function testMethod(testData) {
		return $.get('test');
	};
	/*EVENTS*/
	api.findEvents = function(callback) {
		var eventController = $.get('controllers/fuzzy');
		eventController.findAll(function(err, data) {
			callback(err, data);
		});
	};
	api.removeEvents = function(callback) {
		var eventController = $.get('controllers/fuzzy');
		eventController.removeAll(function(err) {
			callback(err);
		});
	};
	return api;
}


text:
layout: post-no-feature
title: "The Secret Lifetimes of C++ Objects"
description: "Understanding object lifetimes and avoiding the proliferation of the shared_ptr"
category: articles
tags: [c++, shared_ptr, lifetimes, objects, OOP, object-oriented, unique_ptr, smart pointers, pointers, memory management, memory leaks, cpp, c++11, c++14, c++17, modern c++, programming, software engineering]
---

Back in the Spring of 1793, the French Revolution was in full swing, and the French National Convention published a decree that, in its original French, went like this, “Ils doivent envisager qu'une grande responsabilité est la suite inséparable d'un grand pouvoir.” This admonition, translated and transformed, wove its way through political and religious history: echoing in the House of Commons by the early 19th century, called out from the pulpit 40 years later, intoned in 1906 by no less a figure than Churchill. Until, at last, it arrived to the American pop conscious in 1964 via the auspicious vehicle of the Spiderman comic books: “With great power comes great responsibility.”

This adage could be the motto for C++. Here you have a language that lets you do many things, to micro-optimize and to waste cycles for no reason, to under-think and to over-complicate, to write a lot of code to do very little. This strange mix of the positives and negatives, the unchecked power, and the difficulty of wielding it to good result, continues to birth new languages three decades on. The success of Ruby, Python, Java, and Go may all be attributed to where C++ (and C before it) failed. But what's often glossed over is that C++, too, has evolved and is evolving. The clean and idiomatic code you once wrote is now quite bad by modern standards: we have begun to take on the responsibility that follows inseparably from great power.

Consider the following classical C++ code:

```cpp
class Emulator
{
public:
    Emulator()
    : m_cpu(new CPU())
    , m_fpu(new FPU())
    , m_gpu(new GPU())
    , m_dma(new Memory())
    { }

    ~Emulator()
    {
        delete m_cpu;
        delete m_fpu;
        delete m_gpu;
    }

    void raiseInterrupt(IRQ irq)
    {
        m_cpu->raiseInterrupt(irq);
    }

    // ...

private:
    CPU* m_cpu;
    FPU* m_fpu;
    GPU* m_gpu;
    Memory* m_dma;  // for Direct Memory Access, obviously
};
```

At one point in time, this is uncontroversial and just obviously how you do things (save the memory leak; did you catch it?). Today, it immediately fails code review as soon as the word `new` shows up. The prohibition here is not really against that particular keyword but against the fact that we have procedurally implemented a contract that we can declaratively enforce:

```cpp
class Emulator
{
public:
    Emulator()
    : m_cpu(std::make_unique<CPU>())
    , m_fpu(std::make_unique<FPU>())
    , m_gpu(std::make_unique<GPU>())
    , m_dma(std::make_unique<Memory>())
    { }

    // No need for ~Emulator() any more

    void raiseInterrupt(IRQ irq)
    {
        m_cpu->raiseInterrupt(irq);  // this code is the same
    }

private:
    std::unique_ptr<CPU> m_cpu;
    std::unique_ptr<FPU> m_fpu;
    std::unique_ptr<GPU> m_gpu;
    std::unique_ptr<Memory> m_dma;
};
```

The contract here has to do with lifetimes, and it's one of the major responsibilities we have long shirked in C++. When are objects born? When do they die? What object (or objects) dictate their existence? In the world of manual memory management, we `new` them up when the code dictates they must exist, and we find some place to `delete` them that seems like it won't crash or leak memory, and we pass around references and pointers without considering the union of different lifetimes. In any medium-sized, classical C++ codebase, you can spend countless hours analyzing whether objects will all be alive when they're needed and fixing the inevitable crashes that occur when they aren't. The lifetimes of our C++ objects are secrets even from the people that wrote the code.

In modern C++, we write the contract more explicitly. In both versions, the emulator is the owner of the CPU, FPU, GPU, and Memory objects, and it dictates their lifetimes. But in our modern version, by making these instance variables of type `std::unique_ptr<T>`, we have declared within the code that the instances do not outlive the emulator (unless their ownership is transferred--more on that later). We still must choose the moment of creation and deal with nullability, but we no longer need to explicit `delete` the objects. They will go away when the unique pointers that own them go away.

### Sharing is not caring

Here's a nasty surprise: opting into smart pointers does not relieve you of your responsibility to understand your objects' lifetimes. Objects need to be passed to each other, and the question often becomes, when we're using a smart pointer, how do we pass them around? What do we do with this classical C++ code?

```cpp
class CPU
{
public:
    // ...

private:
    Memory* m_dma;
};
```

To get to the somewhat surprising answer, let's consider our options. The first option that we can readily eliminate is to make this also a `std::unique_ptr<T>`:

```cpp
class CPU
{
public:
    // ...

private:
    std::unique_ptr<Memory> m_dma;
};
```

The problem here is that we then need to transfer ownership of the memory from the emulator to the CPU:

```cpp
Emulator()
: m_cpu(std::make_unique<CPU>())
, m_fpu(std::make_unique<FPU>())
, m_gpu(std::make_unique<GPU>())
, m_dma(std::make_unique<Memory>())
{
    m_cpu->memory(std::move(m_dma));

    // But now this->m_dma is invalidated!
}
```

When we move the unqiue pointer, we lose our own reference. That is the whole point of the unique pointer: that there is exactly one owner of the object. Faced with this, you might reach for the other smart pointer that C++11 gives you, the `std::shared_ptr<T>`:

```cpp
class Emulator
{
public:
    Emulator()
    : m_cpu(std::make_shared<CPU>())
    , m_fpu(std::make_shared<FPU>())
    , m_gpu(std::make_shared<GPU>())
    , m_dma(std::make_shared<Memory>())
    {
        // The CPU and Emulator can share ownership of m_dma
        m_cpu->memory(m_dma);
    }

    // No need for ~Emulator() any more
    // ...

private:
    std::shared_ptr<CPU> m_cpu;
    std::shared_ptr<FPU> m_fpu;
    std::shared_ptr<GPU> m_gpu;
    std::shared_ptr<Memory> m_dma;
};
```

I often find myself wishing that shared pointers didn't exist. They were added to the language because objects can sometimes have complex lifetimes that are not statically knowable. They are a niche tool, but now they litter many modern C++ codebases because, by using them, it seems like you can ignore your responsibility to understand your objects' lifetimes. The shared pointer has it handled for you. The objects will all be cleaned up when their references go out of scope. Except that, aside from the semantics here being completely wrong, and you possibly incurring atomic reference count operations for no reason at all, it's a dangerous lie:

```cpp
class Memory
{
public:
    Memory(const std::shared_ptr<CPU>& cpu)
    : m_cpu(cpu)
    {
        // ...
    }

    // ...

private:
    std::shared_ptr<CPU> m_cpu;
    // ...
};

class Emulator
{
public:
    Emulator()
    : m_cpu(std::make_shared<CPU>())
    , m_fpu(std::make_shared<FPU>())
    , m_gpu(std::make_shared<GPU>())
    , m_dma(std::make_shared<Memory>(m_cpu))
    {
        m_cpu->memory(m_dma);
    }

    // ...
};
```

You have now very concisely implemented a memory leak. The CPU has two owners: the emulator and the memory. The memory has two owners: the emulator and the CPU. When the emulator is destructed, the reference counts are decremented. Now there is one owner of the CPU: the memory. And there is one owner of the memory: the CPU. Neither are reachable from your code at this point, but both sit there in memory. The destructors won't be called. You've created a reference cycle.

The advice I give around `std::shared_ptr<T>` is that it's the surest sign you need to think *more* about what you're doing. You have more responsibility with shared pointers to understand what's going on, not less. In many cases, the existence of shared ownership is a good indication that your design can be improved. The moment you reach for a `std::weak_ptr<T>` to avoid cycles is the moment you should really stop to contemplate what you're doing with your life and the lives of your objects. It's not that these tools are never needed; it's that they're far more rarely the right choice than common practice makes it seem.

### Pointing the right way

What then do we do to pass around our references? All we have arrived at is that our code can perhaps work with shared pointers if we follow the edict to better understand our lifetimes and avoid circular references. But what's odd here is that we do understand our lifetime. We were able to succinctly state it earlier:

the emulator is the owner of the CPU, FPU, GPU, and Memory objects, and it dictates their lifetimes

The `std::unique_ptr<T>` remains the right choice to express that contract. The solution to our impasse is simply to rely on the fact that the CPU isn't an owner of the Memory: it has access to it, but it has nothing to say about the lifetime of that object. The only part of the contract that is not expressed within the implementation of the CPU class--that the Memory exists as long as the CPU exists--is enforced by the emulator itself because it is an owner. Therefore, our correct solution for our existing design is just this:

```cpp
class CPU
{
public:
    // ...

    void memory(Memory* dma) { m_dma = dma; }

private:
    Memory* m_dma;
};

class Emulator
{
public:
    : m_cpu(std::make_unique<CPU>())
    , m_fpu(std::make_unique<FPU>())
    , m_gpu(std::make_unique<GPU>())
    , m_dma(std::make_unique<Memory>())
    {
        m_cpu->memory(m_dma.get());
    }

    // ...

private:
    std::unique_ptr<CPU> m_cpu;
    std::unique_ptr<FPU> m_fpu;
    std::unique_ptr<GPU> m_gpu;
    std::unique_ptr<Memory> m_dma;
};
```

That is, the classical C++ remains the right way to do what we want with the `CPU` class. The `CPU` has its lifetime externally managed, and it does not manage the lifetime of the `Memory` it is given.

We might feel queasy about handing out raw pointers like this, but it is actually more correct to do so than the abuse of smart pointers we'd earlier contemplated. We simply need to adjust our expectations about what raw pointers mean. In classical C++, a raw pointer communicated that you may or may not have to worry about ownership and lifetime. In modern C++, a raw pointer communicates that wherever you got the reference from has specified (or, transitively, inherited) a lifetime policy. The raw pointer concisely communicates the idea that the guarantees are written elsewhere: they are the caller's responsibility. Your class needs to be aware of how that policy's enforcement might impact your implementation, but it does not need to do any enforcement on its own. Somewhat sensibly, the raw pointer serves as a pointer to the human reader: look elsewhere.

### Writing better contracts

We have cause to still be unhappy with this code. It's not that we have handed out a raw pointer, it's not even much about lifetimes because we have our contract written. What we have done is handed the `CPU` access to the `Memory` at any point in time. It can do whatever it wants, including modifying its internal state.

The contract we have here is wide open: the lifetime is guaranteed for you, now do whatever you want. In the presence of threads, we have the possibility of synchronization issues. Even without concurrency or parallelism to concern ourselves over, we are left with the inevitability of more and more methods using more and more functionality of the instances they reference. And, yes, we have allowed for programmer error to cause problems around the misuse of the object's lifetime. And for what? Just to do a bit less typing, we have opened Pandora's box.

So let's fix this. In one of our iterations, we played with the idea of giving the `Memory` a reference to the `CPU`. This might be needed to deliver an interrupt:

```cpp
void Memory::page_fault()
{
    // ...
    m_cpu->raiseInterrupt(IRQ::PAGE_FAULT);
}

void Emulator::run()
{
    while (1)
    {
        // ...
        if (page_not_found)
        {
            m_dma->page_fault();
        }
    }
}
```

When we dismissed `std::shared_ptr<CPU>` as the type for `Memory`'s `m_cpu`, it was both because this introduced a circular reference and because the semantics--the idea that `Memory` owns the `CPU`--was wrong. We can fix both (and also obviate our original motiviation for considering shared pointers) by observing that we can simply pass the `CPU` to the methods that need it. This makes tight coupling harder on us and avoids dire programmer errors.

Moreover, since these methods assume that the CPU exists (is not null, is valid), we can also use a non-nullable reference instead of a pointer:

```cpp
void Memory::page_fault(CPU& cpu)
{
    cpu.raiseInterrupt(IRQ::PAGE_FAULT);
}

void Emulator::run()
{
    while (1)
    {
        // ...
        if (page_not_found)
        {
            m_dma->page_fault(*m_cpu);
        }
    }
}
```

The emulator is calling `page_fault` and passing in its `CPU` that it has created in its constructor and that, by the contract enforced with `std::unique_ptr<T>` (in the absence of `reset` or `std::move`) will live until the emulator is destructed. Therefore, if `page_fault` does not start a thread that holds the `CPU` reference, the implicit contract around a synchronous function call resolves our worries about us screwing up the lifetimes: `CPU` is alive when we pass it to `page_fault`, therefore it's alive during `page_fault`'s execution.

The exercise is to understand lifetimes and ownership, so that we may write them out clearly and coherently. In our fictional emulator, ownership is entirely dictated by the top-level class, and all lifetimes are neatly dictated from there. Since C++ lacks Rust's tools for static verification of lifetimes, we need instead to expose the secret lifetimes of our objects through the simple concepts of unique ownership, "look elsewhere" raw pointers, and, if we really can't properly scope the lifetime up-front, shared ownership. When you are writing C++, this is your responsibility to the people that will use your software, and to your coworkers and your future self that will inherit your codebase. Use your powers wisely.


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.directory;

/**
 * Available OAuth 2.0 scopes for use with the Admin Directory API.
 *
 * @since 1.4
 */
public class DirectoryScopes {

  /** View and manage customer related information. */
  public static final String ADMIN_DIRECTORY_CUSTOMER = "https://www.googleapis.com/auth/admin.directory.customer";

  /** View customer related information. */
  public static final String ADMIN_DIRECTORY_CUSTOMER_READONLY = "https://www.googleapis.com/auth/admin.directory.customer.readonly";

  /** View and manage your Chrome OS devices' metadata. */
  public static final String ADMIN_DIRECTORY_DEVICE_CHROMEOS = "https://www.googleapis.com/auth/admin.directory.device.chromeos";

  /** View your Chrome OS devices' metadata. */
  public static final String ADMIN_DIRECTORY_DEVICE_CHROMEOS_READONLY = "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly";

  /** View and manage your mobile devices' metadata. */
  public static final String ADMIN_DIRECTORY_DEVICE_MOBILE = "https://www.googleapis.com/auth/admin.directory.device.mobile";

  /** Manage your mobile devices by performing administrative tasks. */
  public static final String ADMIN_DIRECTORY_DEVICE_MOBILE_ACTION = "https://www.googleapis.com/auth/admin.directory.device.mobile.action";

  /** View your mobile devices' metadata. */
  public static final String ADMIN_DIRECTORY_DEVICE_MOBILE_READONLY = "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly";

  /** View and manage the provisioning of domains for your customers. */
  public static final String ADMIN_DIRECTORY_DOMAIN = "https://www.googleapis.com/auth/admin.directory.domain";

  /** View domains related to your customers. */
  public static final String ADMIN_DIRECTORY_DOMAIN_READONLY = "https://www.googleapis.com/auth/admin.directory.domain.readonly";

  /** View and manage the provisioning of groups on your domain. */
  public static final String ADMIN_DIRECTORY_GROUP = "https://www.googleapis.com/auth/admin.directory.group";

  /** View and manage group subscriptions on your domain. */
  public static final String ADMIN_DIRECTORY_GROUP_MEMBER = "https://www.googleapis.com/auth/admin.directory.group.member";

  /** View group subscriptions on your domain. */
  public static final String ADMIN_DIRECTORY_GROUP_MEMBER_READONLY = "https://www.googleapis.com/auth/admin.directory.group.member.readonly";

  /** View groups on your domain. */
  public static final String ADMIN_DIRECTORY_GROUP_READONLY = "https://www.googleapis.com/auth/admin.directory.group.readonly";

  /** View and manage notifications received on your domain. */
  public static final String ADMIN_DIRECTORY_NOTIFICATIONS = "https://www.googleapis.com/auth/admin.directory.notifications";

  /** View and manage organization units on your domain. */
  public static final String ADMIN_DIRECTORY_ORGUNIT = "https://www.googleapis.com/auth/admin.directory.orgunit";

  /** View organization units on your domain. */
  public static final String ADMIN_DIRECTORY_ORGUNIT_READONLY = "https://www.googleapis.com/auth/admin.directory.orgunit.readonly";

  /** View and manage the provisioning of calendar resources on your domain. */
  public static final String ADMIN_DIRECTORY_RESOURCE_CALENDAR = "https://www.googleapis.com/auth/admin.directory.resource.calendar";

  /** View calendar resources on your domain. */
  public static final String ADMIN_DIRECTORY_RESOURCE_CALENDAR_READONLY = "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly";

  /** Manage delegated admin roles for your domain. */
  public static final String ADMIN_DIRECTORY_ROLEMANAGEMENT = "https://www.googleapis.com/auth/admin.directory.rolemanagement";

  /** View delegated admin roles for your domain. */
  public static final String ADMIN_DIRECTORY_ROLEMANAGEMENT_READONLY = "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly";

  /** View and manage the provisioning of users on your domain. */
  public static final String ADMIN_DIRECTORY_USER = "https://www.googleapis.com/auth/admin.directory.user";

  /** View and manage user aliases on your domain. */
  public static final String ADMIN_DIRECTORY_USER_ALIAS = "https://www.googleapis.com/auth/admin.directory.user.alias";

  /** View user aliases on your domain. */
  public static final String ADMIN_DIRECTORY_USER_ALIAS_READONLY = "https://www.googleapis.com/auth/admin.directory.user.alias.readonly";

  /** View users on your domain. */
  public static final String ADMIN_DIRECTORY_USER_READONLY = "https://www.googleapis.com/auth/admin.directory.user.readonly";

  /** Manage data access permissions for users on your domain. */
  public static final String ADMIN_DIRECTORY_USER_SECURITY = "https://www.googleapis.com/auth/admin.directory.user.security";

  /** View and manage the provisioning of user schemas on your domain. */
  public static final String ADMIN_DIRECTORY_USERSCHEMA = "https://www.googleapis.com/auth/admin.directory.userschema";

  /** View user schemas on your domain. */
  public static final String ADMIN_DIRECTORY_USERSCHEMA_READONLY = "https://www.googleapis.com/auth/admin.directory.userschema.readonly";

  /**
   * Returns an unmodifiable set that contains all scopes declared by this class.
   *
   * @since 1.16
   */
  public static java.util.Set<String> all() {
    java.util.Set<String> set = new java.util.HashSet<String>();
    set.add(ADMIN_DIRECTORY_CUSTOMER);
    set.add(ADMIN_DIRECTORY_CUSTOMER_READONLY);
    set.add(ADMIN_DIRECTORY_DEVICE_CHROMEOS);
    set.add(ADMIN_DIRECTORY_DEVICE_CHROMEOS_READONLY);
    set.add(ADMIN_DIRECTORY_DEVICE_MOBILE);
    set.add(ADMIN_DIRECTORY_DEVICE_MOBILE_ACTION);
    set.add(ADMIN_DIRECTORY_DEVICE_MOBILE_READONLY);
    set.add(ADMIN_DIRECTORY_DOMAIN);
    set.add(ADMIN_DIRECTORY_DOMAIN_READONLY);
    set.add(ADMIN_DIRECTORY_GROUP);
    set.add(ADMIN_DIRECTORY_GROUP_MEMBER);
    set.add(ADMIN_DIRECTORY_GROUP_MEMBER_READONLY);
    set.add(ADMIN_DIRECTORY_GROUP_READONLY);
    set.add(ADMIN_DIRECTORY_NOTIFICATIONS);
    set.add(ADMIN_DIRECTORY_ORGUNIT);
    set.add(ADMIN_DIRECTORY_ORGUNIT_READONLY);
    set.add(ADMIN_DIRECTORY_RESOURCE_CALENDAR);
    set.add(ADMIN_DIRECTORY_RESOURCE_CALENDAR_READONLY);
    set.add(ADMIN_DIRECTORY_ROLEMANAGEMENT);
    set.add(ADMIN_DIRECTORY_ROLEMANAGEMENT_READONLY);
    set.add(ADMIN_DIRECTORY_USER);
    set.add(ADMIN_DIRECTORY_USER_ALIAS);
    set.add(ADMIN_DIRECTORY_USER_ALIAS_READONLY);
    set.add(ADMIN_DIRECTORY_USER_READONLY);
    set.add(ADMIN_DIRECTORY_USER_SECURITY);
    set.add(ADMIN_DIRECTORY_USERSCHEMA);
    set.add(ADMIN_DIRECTORY_USERSCHEMA_READONLY);
    return java.util.Collections.unmodifiableSet(set);
  }

  private DirectoryScopes() {
  }
}


text:
package com.apollographql.apollo.internal.json;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ResponseJsonStreamReader {
  private final JsonReader jsonReader;

  ResponseJsonStreamReader(JsonReader jsonReader) {
    this.jsonReader = jsonReader;
  }

  public boolean hasNext() throws IOException {
    return jsonReader.hasNext();
  }

  public String nextName() throws IOException {
    return jsonReader.nextName();
  }

  public void skipNext() throws IOException {
    jsonReader.skipValue();
  }

  public String nextString(boolean optional) throws IOException {
    checkNextValue(optional);
    if (jsonReader.peek() == JsonReader.Token.NULL) {
      jsonReader.skipValue();
      return null;
    } else {
      return jsonReader.nextString();
    }
  }

  public Integer nextInt(boolean optional) throws IOException {
    checkNextValue(optional);
    if (jsonReader.peek() == JsonReader.Token.NULL) {
      jsonReader.skipValue();
      return null;
    } else {
      return jsonReader.nextInt();
    }
  }

  public Long nextLong(boolean optional) throws IOException {
    checkNextValue(optional);
    if (jsonReader.peek() == JsonReader.Token.NULL) {
      jsonReader.skipValue();
      return null;
    } else {
      return jsonReader.nextLong();
    }
  }

  public Double nextDouble(boolean optional) throws IOException {
    checkNextValue(optional);
    if (jsonReader.peek() == JsonReader.Token.NULL) {
      jsonReader.skipValue();
      return null;
    } else {
      return jsonReader.nextDouble();
    }
  }

  public Boolean nextBoolean(boolean optional) throws IOException {
    checkNextValue(optional);
    if (jsonReader.peek() == JsonReader.Token.NULL) {
      jsonReader.skipValue();
      return null;
    } else {
      return jsonReader.nextBoolean();
    }
  }

  public <T> T nextObject(boolean optional, ObjectReader<T> objectReader) throws IOException {
    checkNextValue(optional);
    if (jsonReader.peek() == JsonReader.Token.NULL) {
      jsonReader.skipValue();
      return null;
    } else {
      jsonReader.beginObject();
      T result = objectReader.read(this);
      jsonReader.endObject();
      return result;
    }
  }

  public <T> List<T> nextList(boolean optional, ListReader<T> listReader) throws IOException {
    checkNextValue(optional);
    if (jsonReader.peek() == JsonReader.Token.NULL) {
      jsonReader.skipValue();
      return null;
    } else {
      List<T> result = new ArrayList<>();
      jsonReader.beginArray();
      while (jsonReader.hasNext()) {
        T item = listReader.read(this);
        result.add(item);
      }
      jsonReader.endArray();
      return result;
    }
  }

  public Object nextScalar(boolean optional) throws IOException {
    checkNextValue(optional);
    if (isNextNull()) {
      skipNext();
      return null;
    } else if (isNextBoolean()) {
      return nextBoolean(false);
    } else if (isNextNumber()) {
      return new BigDecimal(nextString(false));
    } else {
      return nextString(false);
    }
  }

  public Map<String, Object> toMap() throws IOException {
    if (isNextObject()) {
      return readObject(this);
    }

    Map<String, Object> result = new LinkedHashMap<>();
    while (hasNext()) {
      String name = nextName();
      if (isNextNull()) {
        skipNext();
        result.put(name, null);
      } else if (isNextObject()) {
        result.put(name, readObject(this));
      } else if (isNextList()) {
        result.put(name, readScalarList(this));
      } else {
        result.put(name, nextScalar(true));
      }
    }
    return result;
  }

  private boolean isNextObject() throws IOException {
    return jsonReader.peek() == JsonReader.Token.BEGIN_OBJECT;
  }

  private boolean isNextList() throws IOException {
    return jsonReader.peek() == JsonReader.Token.BEGIN_ARRAY;
  }

  private boolean isNextNull() throws IOException {
    return jsonReader.peek() == JsonReader.Token.NULL;
  }

  private boolean isNextBoolean() throws IOException {
    return jsonReader.peek() == JsonReader.Token.BOOLEAN;
  }

  private boolean isNextNumber() throws IOException {
    return jsonReader.peek() == JsonReader.Token.NUMBER;
  }

  private void checkNextValue(boolean optional) throws IOException {
    if (!optional && jsonReader.peek() == JsonReader.Token.NULL) {
      throw new NullPointerException("corrupted response reader, expected non null value");
    }
  }

  private Map<String, Object> readObject(final ResponseJsonStreamReader streamReader) throws IOException {
    return streamReader.nextObject(false, new ObjectReader<Map<String, Object>>() {
      @Override public Map<String, Object> read(ResponseJsonStreamReader streamReader) throws IOException {
        return streamReader.toMap();
      }
    });
  }

  private List<?> readScalarList(final ResponseJsonStreamReader streamReader) throws IOException {
    return streamReader.nextList(false, new ListReader<Object>() {
      @Override public Object read(ResponseJsonStreamReader reader) throws IOException {
        if (streamReader.isNextObject()) {
          return readObject(reader);
        } else {
          return reader.nextScalar(true);
        }
      }
    });
  }

  public interface ObjectReader<T> {
    T read(ResponseJsonStreamReader reader) throws IOException;
  }

  public interface ListReader<T> {
    T read(ResponseJsonStreamReader reader) throws IOException;
  }
}


text:
#ifndef __MICROPY_INCLUDED_MICROBIT_MODMICROBIT_H__
#define __MICROPY_INCLUDED_MICROBIT_MODMICROBIT_H__

#include "py/objtuple.h"

extern const mp_obj_type_t microbit_ad_pin_type;
extern const mp_obj_type_t microbit_dig_pin_type;
extern const mp_obj_type_t microbit_touch_pin_type;

extern const struct _microbit_pin_obj_t microbit_p0_obj;
extern const struct _microbit_pin_obj_t microbit_p1_obj;
extern const struct _microbit_pin_obj_t microbit_p2_obj;
extern const struct _microbit_pin_obj_t microbit_p3_obj;
extern const struct _microbit_pin_obj_t microbit_p4_obj;
extern const struct _microbit_pin_obj_t microbit_p5_obj;
extern const struct _microbit_pin_obj_t microbit_p6_obj;
extern const struct _microbit_pin_obj_t microbit_p7_obj;
extern const struct _microbit_pin_obj_t microbit_p8_obj;
extern const struct _microbit_pin_obj_t microbit_p9_obj;
extern const struct _microbit_pin_obj_t microbit_p10_obj;
extern const struct _microbit_pin_obj_t microbit_p11_obj;
extern const struct _microbit_pin_obj_t microbit_p12_obj;
extern const struct _microbit_pin_obj_t microbit_p13_obj;
extern const struct _microbit_pin_obj_t microbit_p14_obj;
extern const struct _microbit_pin_obj_t microbit_p15_obj;
extern const struct _microbit_pin_obj_t microbit_p16_obj;
extern const struct _microbit_pin_obj_t microbit_p19_obj;
extern const struct _microbit_pin_obj_t microbit_p20_obj;

extern const mp_obj_type_t microbit_const_image_type;
extern const struct _monochrome_5by5_t microbit_const_image_heart_obj;
extern const struct _monochrome_5by5_t microbit_const_image_heart_small_obj;
extern const struct _monochrome_5by5_t microbit_const_image_happy_obj;
extern const struct _monochrome_5by5_t microbit_const_image_smile_obj;
extern const struct _monochrome_5by5_t microbit_const_image_sad_obj;
extern const struct _monochrome_5by5_t microbit_const_image_confused_obj;
extern const struct _monochrome_5by5_t microbit_const_image_angry_obj;
extern const struct _monochrome_5by5_t microbit_const_image_asleep_obj;
extern const struct _monochrome_5by5_t microbit_const_image_surprised_obj;
extern const struct _monochrome_5by5_t microbit_const_image_silly_obj;
extern const struct _monochrome_5by5_t microbit_const_image_fabulous_obj;
extern const struct _monochrome_5by5_t microbit_const_image_meh_obj;
extern const struct _monochrome_5by5_t microbit_const_image_yes_obj;
extern const struct _monochrome_5by5_t microbit_const_image_no_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock12_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock1_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock2_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock3_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock4_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock5_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock6_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock7_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock8_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock9_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock10_obj;
extern const struct _monochrome_5by5_t microbit_const_image_clock11_obj;
extern const struct _monochrome_5by5_t microbit_const_image_arrow_n_obj;
extern const struct _monochrome_5by5_t microbit_const_image_arrow_ne_obj;
extern const struct _monochrome_5by5_t microbit_const_image_arrow_e_obj;
extern const struct _monochrome_5by5_t microbit_const_image_arrow_se_obj;
extern const struct _monochrome_5by5_t microbit_const_image_arrow_s_obj;
extern const struct _monochrome_5by5_t microbit_const_image_arrow_sw_obj;
extern const struct _monochrome_5by5_t microbit_const_image_arrow_w_obj;
extern const struct _monochrome_5by5_t microbit_const_image_arrow_nw_obj;
extern const struct _monochrome_5by5_t microbit_const_image_triangle_obj;
extern const struct _monochrome_5by5_t microbit_const_image_triangle_left_obj;
extern const struct _monochrome_5by5_t microbit_const_image_chessboard_obj;
extern const struct _monochrome_5by5_t microbit_const_image_diamond_obj;
extern const struct _monochrome_5by5_t microbit_const_image_diamond_small_obj;
extern const struct _monochrome_5by5_t microbit_const_image_square_obj;
extern const struct _monochrome_5by5_t microbit_const_image_square_small_obj;
extern const struct _monochrome_5by5_t microbit_const_image_rabbit;
extern const struct _monochrome_5by5_t microbit_const_image_cow;
extern const struct _monochrome_5by5_t microbit_const_image_music_crotchet_obj;
extern const struct _monochrome_5by5_t microbit_const_image_music_quaver_obj;
extern const struct _monochrome_5by5_t microbit_const_image_music_quavers_obj;
extern const struct _monochrome_5by5_t microbit_const_image_pitchfork_obj;
extern const struct _monochrome_5by5_t microbit_const_image_xmas_obj;
extern const struct _monochrome_5by5_t microbit_const_image_pacman_obj;
extern const struct _monochrome_5by5_t microbit_const_image_target_obj;
extern const struct _mp_obj_tuple_t microbit_const_image_all_clocks_tuple_obj;
extern const struct _mp_obj_tuple_t microbit_const_image_all_arrows_tuple_obj;
extern const struct _monochrome_5by5_t microbit_const_image_tshirt_obj;
extern const struct _monochrome_5by5_t microbit_const_image_rollerskate_obj;
extern const struct _monochrome_5by5_t microbit_const_image_duck_obj;
extern const struct _monochrome_5by5_t microbit_const_image_house_obj;
extern const struct _monochrome_5by5_t microbit_const_image_tortoise_obj;
extern const struct _monochrome_5by5_t microbit_const_image_butterfly_obj;
extern const struct _monochrome_5by5_t microbit_const_image_stickfigure_obj;
extern const struct _monochrome_5by5_t microbit_const_image_ghost_obj;
extern const struct _monochrome_5by5_t microbit_const_image_sword_obj;
extern const struct _monochrome_5by5_t microbit_const_image_giraffe_obj;
extern const struct _monochrome_5by5_t microbit_const_image_skull_obj;
extern const struct _monochrome_5by5_t microbit_const_image_umbrella_obj;
extern const struct _monochrome_5by5_t microbit_const_image_snake_obj;

extern const struct _mp_obj_tuple_t microbit_music_tune_dadadadum_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_entertainer_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_prelude_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_ode_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_nyan_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_ringtone_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_funk_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_blues_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_birthday_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_wedding_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_funeral_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_punchline_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_python_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_baddy_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_chase_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_ba_ding_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_wawawawaa_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_jump_up_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_jump_down_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_power_up_obj;
extern const struct _mp_obj_tuple_t microbit_music_tune_power_down_obj;

extern const mp_obj_type_t microbit_image_type;

extern const mp_obj_type_t microbit_accelerometer_type;
extern const struct _microbit_accelerometer_obj_t microbit_accelerometer_obj;

extern struct _microbit_display_obj_t microbit_display_obj;
extern struct _microbit_button_obj_t microbit_button_a_obj;
extern struct _microbit_button_obj_t microbit_button_b_obj;
extern const struct _microbit_compass_obj_t microbit_compass_obj;
extern const struct _microbit_i2c_obj_t microbit_i2c_obj;
extern struct _microbit_uart_obj_t microbit_uart_obj;
extern struct _microbit_spi_obj_t microbit_spi_obj;

MP_DECLARE_CONST_FUN_OBJ(microbit_reset_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_sleep_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_random_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_running_time_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_temperature_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_panic_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_accelerometer_get_x_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_accelerometer_get_y_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_accelerometer_get_z_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_button_is_pressed_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_button_is_long_pressed_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_button_was_pressed_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_button_get_presses_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_compass_is_calibrated_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_compass_heading_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_compass_calibrate_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_compass_is_calibrating_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_compass_clear_calibration_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_compass_get_x_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_compass_get_y_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_compass_get_z_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_compass_get_field_strength_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_display_show_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_display_scroll_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_display_clear_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_display_get_pixel_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_display_set_pixel_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_display_on_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_display_off_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_display_is_on_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_pin_read_digital_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_pin_write_digital_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_pin_read_analog_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_pin_write_analog_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_pin_is_touched_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_pin_set_analog_period_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_pin_set_analog_period_microseconds_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_i2c_read_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_i2c_write_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_width_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_height_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_get_pixel_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_set_pixel_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_shift_left_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_shift_right_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_shift_up_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_shift_down_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_copy_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_crop_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_invert_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_image_slice_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_uart_init_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_uart_any_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_stream_read_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_stream_readall_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_stream_unbuffered_readline_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_stream_readinto_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_stream_write_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_spi_init_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_spi_write_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_spi_read_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_spi_write_readinto_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_music_set_tempo_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_music_pitch_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_music_play_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_music_get_tempo_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_music_stop_obj);
MP_DECLARE_CONST_FUN_OBJ(microbit_music_reset_obj);
MP_DECLARE_CONST_FUN_OBJ(love_badaboom_obj);
MP_DECLARE_CONST_FUN_OBJ(this_authors_obj);

extern const mp_obj_module_t microbit_module;
extern const mp_obj_module_t music_module;
extern const mp_obj_module_t love_module;
extern const mp_obj_module_t antigravity_module;
extern const mp_obj_module_t this_module;

// various defines to enable/disable certain button functions
// NOTE: this has no effect on whether or not the function name strings are
// built into the final image.
#define MICROBIT_BUTTON_INCLUDE_IS_LONG_PRESSED         1
#define MICROBIT_BUTTON_INCLUDE_WAS_CLICKED             1
#define MICROBIT_BUTTON_INCLUDE_WAS_DOUBLE_CLICKED      1
#define MICROBIT_BUTTON_INCLUDE_WAS_LONG_CLICKED        1
#define MICROBIT_BUTTON_INCLUDE_WAS_HOLD                1

#endif // __MICROPY_INCLUDED_MICROBIT_MODMICROBIT_H__


text:
Sidekiq.configure_client do |config|
  config.redis = {
    size: 1,
    host: Settings.redis_host
  }
end


text:
'use strict';

describe('CONFIG', function() {
    var CONFIG;

    beforeEach(angular.mock.module('groceries'));

    beforeEach(inject(function($injector) {
        CONFIG = $injector.get('CONFIG');
    }));

    it('should contain a `api` configuration', function() {
        expect(CONFIG.api).not.toBe(undefined);
    });
});


text:
/*Problem 9. Print a Sequence
• Write a program that prints the first 10 members of the sequence:  2, -3, 4, -5, 6, -7, ...
Print each member on a separate line.
*/

using System;

class NumberSequence
{
    static void Main()
    {
        int currentNumber = 2;
        int nextNumber = 0;

        Console.WriteLine(currentNumber);

        for (int i = 1; i < 10; i++)
        {
            if (i % 2 == 0)
            {
                nextNumber = currentNumber + 1;
            }
            else
            {
                nextNumber = -(currentNumber + 1);
            }

            Console.WriteLine(nextNumber);

            currentNumber = Math.Abs(nextNumber);
        }
    }
}


text:
ES5Harness.registerTest( {
id: "15.4.4.19-4-7",

path: "TestCases/chapter15/15.4/15.4.4/15.4.4.19/15.4.4.19-4-7.js",

description: "Array.prototype.map throws TypeError if callbackfn is Object without Call internal method",

test: function testcase() {

  var arr = new Array(10);
  try {
    arr.map(new Object());
  }
  catch(e) {
    if(e instanceof TypeError)
      return true;
  }

 },

precondition: function prereq() {
  return fnExists(Array.prototype.map);
 }
});


text:
package com.alibaba.asyncload.impl.spring;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.alibaba.asyncload.impl.exceptions.AsyncLoadException;
import com.alibaba.asyncload.impl.template.AsyncLoadCallback;
import com.alibaba.asyncload.impl.template.AsyncLoadTemplate;

/**
 * 开发基于拦截器实现的并行加载,注意依赖{@linkplain AsyncLoadTemplate}
 *
 *

 * 适用于以下情况:
 * 1. 原先的service对象已经被进行cglib代理,并行加载可以做为其中的一个代理进行织入
 * 2. 希望通过BeanNameAutoProxyCreator进行自动代理配置,不想影响原先的bean配置
 *
 * 设计注意:
 * 1. 这里依赖{@linkplain AsyncLoadTemplate}进行代码块的并行加载控制,而不能对原先的service进行代理(会产生死循环)
 * 2. 并不直接提供method match的机制,希望是可以直接利用spring提供的PointCut进行控制
 *

 *
 * 使用示例配置:
 *
 *

 *     <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
 *         <property name="proxyTargetClass" value="true" />
 *         <property name="beanNames">
 *             <list>
 *                 <value>*DataFeeder</value>
 *             </list>
 *         </property>
 *         <property name="interceptorNames">
 *             <list>
 *                 <value>asyncLoadInterceptor</value>
 *             </list>
 *         </property>
 *     </bean>
 *

 *
 * @author jianghang 2011-4-1 下午04:52:51
 */
public class AsyncLoadInterceptor implements MethodInterceptor {

    private AsyncLoadTemplate asyncLoadTemplate;

    public Object invoke(MethodInvocation invocation) throws Throwable {
        final MethodInvocation temp = invocation;
        return asyncLoadTemplate.execute(new AsyncLoadCallback() {

            public Object doAsyncLoad() {
                try {
                    return temp.proceed();
                } catch (Throwable e) {
                    throw new AsyncLoadException("AsyncLoadInterceptor invoke error!", e);
                }
            }
        }, invocation.getMethod().getReturnType()); // 这里指定了返回目标class

    }

    // =============== setter / getter =================

    public void setAsyncLoadTemplate(AsyncLoadTemplate asyncLoadTemplate) {
        this.asyncLoadTemplate = asyncLoadTemplate;
    }

}


text:
require "vagrant"

module VagrantPlugins
  module GuestUbuntu
    class Plugin < Vagrant.plugin("2")
      name "Ubuntu guest"
      description "Ubuntu guest support."

      guest("ubuntu") do
        require File.expand_path("../guest", __FILE__)
        Guest
      end
    end
  end
end


text:
<?php
namespace Acf\AdminBundle\Form\Sale;

use Acf\DataBundle\Entity\Sale;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 *
 * @author sasedev <seif.salah@gmail.com>
 */
class UpdateValidatedTForm extends AbstractType
{

    /**
     * Form builder
     *
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('validated', ChoiceType::class, array(
            'label' => 'Sale.validated.label',
            'choices' => Sale::choiceValidated(),
            'expanded' => true,
            'attr' => array(
                'choice_label_trans' => true
            )
        ));
    }

    /**
     *
     * @return string
     */
    public function getName()
    {
        return 'SaleUpdateValidatedForm';
    }

    /**
     *
     * {@inheritdoc} @see AbstractType::getBlockPrefix()
     */
    public function getBlockPrefix()
    {
        return $this->getName();
    }

    /**
     * get the default options
     *
     * @return multitype:string multitype:string
     */
    public function getDefaultOptions()
    {
        return array(
            'validation_groups' => array(
                'validated'
            )
        );
    }

    /**
     *
     * {@inheritdoc} @see AbstractType::configureOptions()
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults($this->getDefaultOptions());
    }
}


text:
from setuptools import setup, find_packages

setup(
    name="no_mp",
    version="0.1.dev0",
    description="No Mp Test Fixture",
    author="Martijn Faassen",
    author_email="faassen@startifact.com",
    license="BSD",
    packages=find_packages(),
    zip_safe=False,
    install_requires=[],
)


text:
Imports System.Web.Util

Namespace Packers
    Public Class CabArchive
#Region " .New() "
        Public Sub New(ByVal Archive As String)
            Dim cc As New Cabcreator

        End Sub
#End Region

    End Class
End Namespace


text:
use failure::Error;
use std::sync::{Arc, Mutex};
use uuid::Uuid;

use crate::utils::prelude::{FastHashMap, HandleLike, ObjectPool};

use super::state::ResourceState;

pub trait ResourceLoader: Send + Sync {
    type Handle: Send;
    type Intermediate: Send;
    type Resource: Send;

    fn load(&self, _: Self::Handle, _: &[u8]) -> Result<Self::Intermediate, Error>;
    fn create(&self, _: Self::Handle, _: Self::Intermediate) -> Result<Self::Resource, Error>;
    fn delete(&self, _: Self::Handle, _: Self::Resource);
}

// The `ResourcePool` is a standardized resources manager that defines a set of interface for creation,
// destruction, sharing and lifetime management. It is used in all the built-in crayon modules.
pub struct ResourcePool<H, Loader>
where
    H: HandleLike + 'static,
    Loader: ResourceLoader<Handle = H> + Clone + 'static,
{
    items: ObjectPool<H, Item<Loader::Resource>>,
    requests: FastHashMap<H, Arc<Mutex<ResourceAsyncState<Loader::Intermediate>>>>,
    registry: FastHashMap<Uuid, H>,
    loader: Loader,
}

impl<H, Loader> ResourcePool<H, Loader>
where
    H: HandleLike + 'static,
    Loader: ResourceLoader<Handle = H> + Clone + 'static,
{
    /// Create a new and empty `ResourcePool`.
    pub fn new(loader: Loader) -> Self {
        ResourcePool {
            items: ObjectPool::new(),
            registry: FastHashMap::default(),
            requests: FastHashMap::default(),
            loader,
        }
    }

    pub fn advance(&mut self) -> Result<(), Error> {
        let items = &mut self.items;
        let loader = &self.loader;

        self.requests.retain(|&handle, req| {
            let mut req = req.lock().unwrap();
            if let ResourceAsyncState::NotReady = *req {
                return true;
            }

            let mut tmp = ResourceAsyncState::NotReady;
            std::mem::swap(&mut *req, &mut tmp);

            match tmp {
                ResourceAsyncState::Err(err) => {
                    warn!("{:?}", err);
                    if let Some(item) = items.get_mut(handle) {
                        item.error = Some(err);
                    }
                }
                ResourceAsyncState::Ok(intermediate) => {
                    if let Some(item) = items.get_mut(handle) {
                        match loader.create(handle, intermediate) {
                            Ok(resource) => item.resource = Some(resource),
                            Err(err) => {
                                warn!("{:?}", err);
                                item.error = Some(err);
                            }
                        }
                    }
                }
                _ => unreachable!(),
            }

            false
        });

        Ok(())
    }

    /// Create a resource with provided value instance.
    ///
    /// A associated `Handle` is returned.
    #[inline]
    pub fn create(&mut self, params: Loader::Intermediate) -> Result<H, Error> {
        let handle = self.alloc(None);
        match self.loader.create(handle, params) {
            Ok(value) => {
                self.items.get_mut(handle).unwrap().resource = Some(value);
                Ok(handle)
            }
            Err(error) => {
                self.delete(handle);
                Err(error)
            }
        }
    }

    /// Create a resource from file asynchronously.
    #[inline]
    pub fn create_from<T: AsRef<str>>(&mut self, url: T) -> Result<H, Error> {
        let url = url.as_ref();
        let uuid = crate::res::find(url)
            .ok_or_else(|| format_err!("Could not found resource '{}'.", url))?;
        self.create_from_uuid(uuid)
    }

    /// Create a named resource from file asynchronously.
    #[inline]
    pub fn create_from_uuid(&mut self, uuid: Uuid) -> Result<H, Error> {
        if let Some(&handle) = self.registry.get(&uuid) {
            self.items.get_mut(handle).unwrap().rc += 1;
            return Ok(handle);
        }

        let handle = self.alloc(Some(uuid));

        let rx = Arc::new(Mutex::new(ResourceAsyncState::NotReady));
        let tx = rx.clone();
        let loader = self.loader.clone();

        let result = crate::res::load_with_callback(uuid, move |rsp| match rsp {
            Ok(bytes) => {
                let itermediate = loader.load(handle, &bytes);

                match itermediate {
                    Ok(item) => {
                        *tx.lock().unwrap() = ResourceAsyncState::Ok(item);
                    }
                    Err(err) => {
                        *tx.lock().unwrap() = ResourceAsyncState::Err(err);
                    }
                }
            }

            Err(err) => {
                *tx.lock().unwrap() = ResourceAsyncState::Err(err);
            }
        });

        match result {
            Ok(_) => {
                self.requests.insert(handle, rx);
                Ok(handle)
            }
            Err(err) => {
                self.delete(handle);
                Err(err)
            }
        }
    }

    /// Deletes a resource from loadery.
    pub fn delete(&mut self, handle: H) {
        let disposed = self
            .items
            .get_mut(handle)
            .map(|e| {
                e.rc -= 1;
                e.rc == 0
            })
            .unwrap_or(false);

        if disposed {
            let e = self.items.free(handle).unwrap();

            if let Some(uuid) = e.uuid {
                self.registry.remove(&uuid);
            }

            if let Some(resource) = e.resource {
                self.loader.delete(handle, resource);
            }
        }
    }

    /// Get the resource state.
    #[inline]
    pub fn state(&self, handle: H) -> ResourceState {
        self.items
            .get(handle)
            .map(|e| {
                if e.resource.is_some() {
                    ResourceState::Ok
                } else if e.error.is_some() {
                    ResourceState::Err
                } else {
                    ResourceState::NotReady
                }
            })
            .unwrap_or(ResourceState::NotReady)
    }

    /// Checks if the handle is still avaiable in this pool.
    #[inline]
    pub fn contains(&self, handle: H) -> bool {
        self.items.contains(handle)
    }

    /// Return immutable reference to internal value with name `Handle`.
    #[inline]
    pub fn resource(&self, handle: H) -> Option<&Loader::Resource> {
        self.items.get(handle).and_then(|e| e.resource.as_ref())
    }

    /// Return mutable reference to internal value with name `Handle`.
    #[inline]
    pub fn resource_mut(&mut self, handle: H) -> Option<&mut Loader::Resource> {
        self.items.get_mut(handle).and_then(|e| e.resource.as_mut())
    }

    #[inline]
    fn alloc(&mut self, uuid: Option<Uuid>) -> H {
        let entry = Item {
            rc: 1,
            uuid,
            resource: None,
            error: None,
        };

        let handle = self.items.create(entry);

        if let Some(uuid) = uuid {
            self.registry.insert(uuid, handle);
        }

        handle
    }
}

struct Item<T> {
    rc: u32,
    uuid: Option<Uuid>,
    resource: Option<T>,
    error: Option<Error>,
}

enum ResourceAsyncState<T> {
    Ok(T),
    Err(Error),
    NotReady,
}