text:
if (typeof(PhoneNumber) === "undefined") {
    var PhoneNumber = require("../../lib/PhoneNumber.js");
}
if (typeof(ilib) === "undefined") {
    var ilib = require("../../lib/ilib.js");
}

module.exports.phonenum_IE = {
    setUp: function(callback) {
        ilib.clearCache();
        callback();
    },

    testParseIEFull: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("0112345678", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            areaCode: "1",
            subscriberNumber: "12345678"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEFullLongAreaCode: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("040412345", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            areaCode: "404",
            subscriberNumber: "12345"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEIgnoreFormatting: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("(0404) 12-345", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            areaCode: "404",
            subscriberNumber: "12345"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEIgnoreCrap: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("0@11$23%45&678", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            areaCode: "1",
            subscriberNumber: "12345678"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIENoAreaCode: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("82345678", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            subscriberNumber: "82345678"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIELocalInvalidNumber: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("12345678", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            subscriberNumber: "12345678",
            invalid: true
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testVSC: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("14282345678", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            vsc: "142",
            subscriberNumber: "82345678"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEPlusIDDToUS: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("+12028675309", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            iddPrefix: "+",
            countryCode: "1",
            areaCode: "202",
            subscriberNumber: "8675309"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEZerosIDDToUS: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("0012028675309", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            iddPrefix: "00",
            countryCode: "1",
            areaCode: "202",
            subscriberNumber: "8675309"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIELongAreaCodeNoTrunk: function(test) {
        test.expect(2);
        // this number uses an area code to start it, but without the trunk, we should
        // not recognize it as an area code
        var parsed = new PhoneNumber("404123456", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            subscriberNumber: "404123456"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIELocalNumber: function(test) {
        test.expect(2);
        // this number uses an area code to start it, but without the trunk, we should
        // not recognize it as an area code
        var parsed = new PhoneNumber("82345678", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            subscriberNumber: "82345678"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEPlusIDDToGB: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("+442012345678", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            iddPrefix: "+",
            countryCode: "44",
            areaCode: "20",
            subscriberNumber: "12345678"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEPlusIDDToIE: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("+353 86 822 3689", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            iddPrefix: "+",
            countryCode: "353",
            mobilePrefix: "86",
            subscriberNumber: "8223689"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEZerosIDDToGB: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("00442012345678", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            iddPrefix: "00",
            countryCode: "44",
            areaCode: "20",
            subscriberNumber: "12345678"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEService: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("15308765432", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            serviceCode: "1530",
            subscriberNumber: "8765432"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEMobileNumber: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("0871234567", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            mobilePrefix: "87",
            subscriberNumber: "1234567"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEPartial1: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("0", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    testParseIEPartial2: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("04", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            subscriberNumber: "4"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },
    testParseIEPartial3: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("040", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            subscriberNumber: "40"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },
    testParseIEPartial4: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("0404", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            areaCode: "404"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },
    testParseIEPartial5: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("04041", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
                trunkAccess: "0",
                areaCode: "404",
                subscriberNumber: "1"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },
    testParseIEPartial6: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("040412", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            areaCode: "404",
            subscriberNumber: "12"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },
    testParseIEPartial7: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("0404123", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            areaCode: "404",
            subscriberNumber: "123"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },
    testParseIEPartial8: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("04041234", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            trunkAccess: "0",
            areaCode: "404",
            subscriberNumber: "1234"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },
    testParseIEPartial9: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("040412345", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
                trunkAccess: "0",
                areaCode: "404",
                subscriberNumber: "12345"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    },

    // for CFISH-5426
    testParseIEEmergencyNumber: function(test) {
        test.expect(2);
        var parsed = new PhoneNumber("999", {locale: "en-IE"});
        test.ok(typeof(parsed) !== "undefined");

        var expected = new PhoneNumber({
            emergency: "999"
        }, {locale: "en-IE"});

        test.ok(parsed.equals(expected));
        test.done();

    }

};


text:
import asyncio

class EchoServer(asyncio.Protocol):
    clients = {}
    def connection_made(self, transport):
        peername = transport.get_extra_info('peername')
        print('connection from {}'.format(peername))
        self.transport = transport
        self.clients[transport] = None

    def data_received(self, data):
        # print('data received: {}'.format(data.decode()))
        for transport in self.clients:
            if transport == self.transport:
                pass
                #continue
            transport.write(data)

    def connection_lost(self, exc):
        print("connection lost")
        self.transport.close()
        del self.clients[self.transport]

loop = asyncio.get_event_loop()
coro = loop.create_server(EchoServer, "127.0.0.1", 8888)
server = loop.run_until_complete(coro)
print('serving on {}'.format(server.sockets[0].getsockname()))

try:
    loop.run_forever()
except KeyboardInterrupt:
    print("exit")
finally:
    server.close()
    loop.close()

redpajama_set_name: RedPajamaGithub


text:
package mil.emp3.core;

import android.graphics.Point;
import android.graphics.PointF;
import android.util.Log;

import org.cmapi.primitives.IGeoBounds;
import org.cmapi.primitives.IGeoMilSymbol;
import org.cmapi.primitives.IGeoPosition;
import org.cmapi.primitives.IGeoStrokeStyle;

import java.util.List;

import mil.emp3.api.enums.CameraEventEnum;
import mil.emp3.api.enums.EditorMode;
import mil.emp3.api.enums.LookAtEventEnum;
import mil.emp3.api.enums.MapGridTypeEnum;
import mil.emp3.api.enums.MapMotionLockEnum;
import mil.emp3.api.enums.MapStateEnum;
import mil.emp3.api.enums.MilStdLabelSettingEnum;
import mil.emp3.api.exceptions.EMP_Exception;
import mil.emp3.api.interfaces.ICamera;
import mil.emp3.api.interfaces.IFeature;
import mil.emp3.api.interfaces.ILookAt;
import mil.emp3.api.interfaces.IMap;
import mil.emp3.api.interfaces.IOverlay;
import mil.emp3.api.interfaces.core.ICoreManager;
import mil.emp3.api.interfaces.core.IEventManager;
import mil.emp3.api.interfaces.core.IStorageManager;
import mil.emp3.api.interfaces.core.storage.IClientMapRestoreData;
import mil.emp3.api.interfaces.core.storage.IClientMapToMapInstance;
import mil.emp3.api.listeners.IDrawEventListener;
import mil.emp3.api.listeners.IEditEventListener;
import mil.emp3.api.listeners.IFreehandEventListener;
import mil.emp3.core.utils.ZoomToUtils;
import mil.emp3.mapengine.interfaces.IMapInstance;

/**
 * This class implements the EMP V3 core manager. It should never be called by the client nor the map.
 */
public class CoreManager implements ICoreManager {
    private static final String TAG = CoreManager.class.getSimpleName();

    private IStorageManager storageManager;
    private IEventManager eventManager;

    private static java.util.Set<IGeoMilSymbol.Modifier> oRequiredLabels = new java.util.HashSet<>();
    private static java.util.Set<IGeoMilSymbol.Modifier> oCommonLabels = new java.util.HashSet<>();

    @Override
    public void setStorageManager(IStorageManager storageManager) {
        this.storageManager = storageManager;
    }

    @Override
    public void setEventManager(IEventManager eventManager) {
        this.eventManager = eventManager;
    }

    @Override
    public MapStateEnum getState(IMap clientMap) {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            return null;
        }
        return mapMapping.getMapState();
    }

    @Override
    public void setCamera(IMap clientMap, ICamera camera, boolean animate, Object userContext) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_MAP, "Can't setCamera to an invalid map.");
        }

        IMapInstance oMapInstance = mapMapping.getMapInstance();

        oMapInstance.setCamera(camera, animate, userContext);
        mapMapping.setCamera(camera);

        // We will need this when client executes swapMapEngine and it will be reused for activity restart also.
        // This is stored again when activity is destroyed but that doesn't help pure swapMapEngine scenario.
        IClientMapRestoreData cmrd = storageManager.getRestoreData(clientMap);
        if(null != cmrd) {
            cmrd.setCamera(camera);
        }
    }

    @Override
    public ICamera getCamera(IMap clientMap) {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            return null;
        }
        return mapMapping.getCamera();
    }

    @Override
    public void setLookAt(IMap clientMap, ILookAt lookAt, boolean animate, Object userContext) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_MAP, "Can't setLookAt to an invalid map.");
        }

        IMapInstance oMapInstance = mapMapping.getMapInstance();

        oMapInstance.setLookAt(lookAt, animate, userContext);
        mapMapping.setLookAt(lookAt);

        // We will need this when client executes swapMapEngine and it will be reused for activity restart also.
        // This is stored again when activity is destroyed but that doesn't help pure swapMapEngine scenario.
        IClientMapRestoreData cmrd = storageManager.getRestoreData(clientMap);
        if(null != cmrd) {
            cmrd.setLookAt(lookAt);
        }
    }

    public ILookAt getLookAt(IMap clientMap) {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            return null;
        }
        return mapMapping.getLookAt();
    }

    public void processCameraSettingChange(ICamera camera, boolean animate, Object userContext) {
        //storageManager.processCameraSettingChange(camera);
        eventManager.generateCameraEvent(CameraEventEnum.CAMERA_IN_MOTION, camera, animate, userContext);
        List<IClientMapToMapInstance> mappings = storageManager.getMappings(camera);
        if(null != mappings) {
            for(IClientMapToMapInstance mapping : mappings) {
                if(null != mapping.getMapInstance()) {
                    mapping.getMapInstance().applyCameraChange(camera, animate, userContext);
                }
            }
        }
    }

    public void processLookAtSettingChange(ILookAt lookAt, boolean animate, Object userContext) {
        eventManager.generateLookAtEvent(LookAtEventEnum.LOOKAT_IN_MOTION, lookAt, animate, userContext);
        List<IClientMapToMapInstance> mappings = storageManager.getMappings(lookAt);
        if(null != mappings) {
            for(IClientMapToMapInstance mapping : mappings) {
                if(null != mapping.getMapInstance()) {
                    mapping.getMapInstance().applyLookAtChange(lookAt, animate, userContext);
                }
            }
        }
    }

    @Override
    public void setMotionLockMode(IMap clientMap, MapMotionLockEnum mode) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            return;
        }

        mapMapping.setLockMode(mode);
    }

    @Override
    public MapMotionLockEnum getMotionLockMode(IMap clientMap) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);
        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }
        return mapMapping.getLockMode();
    }

    @Override
    public EditorMode getEditorMode(IMap clientMap) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);
        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }
        return mapMapping.getEditorMode();
    }

    @Override
    public void editFeature(IMap clientMap, IFeature oFeature, IEditEventListener listener) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }

        if (!storageManager.isOnMap(clientMap, oFeature)) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.NOT_SUPPORTED, "Not Supported. The feature is not on the map.");
        }

        if (!mapMapping.canEdit(oFeature)) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.NOT_SUPPORTED, "Not Supported. The current map can not display a feature of this type.");
        }

        mapMapping.editFeature(oFeature, listener);
    }

    @Override
    public void editCancel(IMap clientMap) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            return;
        }

        mapMapping.editCancel();
    }

    @Override
    public void editComplete(IMap clientMap) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            return;
        }

        mapMapping.editComplete();
    }

    @Override
    public void drawFeature(IMap clientMap, IFeature oFeature, IDrawEventListener listener) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            return;
        }

        //if (storageManager.isOnMap(clientMap, oFeature)) {
        //    throw new EMP_Exception(EMP_Exception.ErrorDetail.NOT_SUPPORTED, "Not Supported. The feature is on the map.");
        //}

        if (!mapMapping.canEdit(oFeature)) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.NOT_SUPPORTED, "Not Supported. The current map can not display a feature of this type.");
        }

        mapMapping.drawFeature(oFeature, listener, (storageManager.findContainer(oFeature.getGeoId()) == null));
    }

    @Override
    public void drawCancel(IMap clientMap) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            return;
        }

        mapMapping.drawCancel();
    }

    @Override
    public void drawComplete(IMap clientMap) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        if (mapMapping == null) {
            return;
        }

        mapMapping.drawComplete();
    }

    /**
     * Find the center of all the visible features from featureList, find the boundingBox that encloses all the features, then
     *     set Camera tilt, roll, heading to zero
     *     set Camera lat/long to center
     *     set Camera altitude to a distance calculated using bounding box and field of view..
     *
     * @param clientMap
     * @param featureList
     */
    @Override
    public void zoomTo(IMap clientMap, List<IFeature> featureList, boolean animate) {
        ZoomToUtils.getInstance().zoomTo(clientMap, featureList, animate);
    }

    /**
     * Fetch all the features for the overlay and then invoke zoomTo on that feature list.
     * @param clientMap
     * @param overlay
     */
    @Override
    public void zoomTo(IMap clientMap, IOverlay overlay, boolean animate) {
        if((null == clientMap) || (null == overlay)) {
            Log.e(TAG, "clientMap and overlay must be non null");
            return;
        }
        List<IFeature> featureList = overlay.getFeatures();
        zoomTo(clientMap, featureList, animate);
    }

    /**
     * setBounds is similar to zoomIn except user has already specified the bounds. So the procedure is the same:
     *     Using the bounds find the center
     *     set Camera tilt, roll, heading to zero
     *     set Camera lat/long to center
     *     set Camera altitude to a distance calculated using bounding box and field of view..
     *
     *     We will reuse the methods from ZoomInUtils class.
     * @param bounds
     */
    @Override
    public void setBounds(IMap clientMap, IGeoBounds bounds, boolean animate) {
        if((null == bounds) ||
                !((bounds.getSouth() <= 90.0) && (bounds.getSouth() >= -90.0)) ||
                !((bounds.getNorth() <= 90.0) && (bounds.getNorth() >= -90.0)) ||
                !((bounds.getWest() <= 180.0) && (bounds.getWest() >= -180.0)) ||
                !((bounds.getEast() <= 180.0) && (bounds.getEast() >= -180.0))) {
            Log.e(TAG, "setExtents: invalid bounds");
            return;
        }

        ZoomToUtils.getInstance().zoomTo(clientMap, bounds, animate);
    }

    /**
     * getBounds gets the map's viewing area
     *
     * @param clientMap
     * @return
     */
    @Override
    public IGeoBounds getBounds(IMap clientMap) {
        return storageManager.getBounds(clientMap);
    }

    @Override
    public void drawFreehand(IMap clientMap, IGeoStrokeStyle initialStyle, IFreehandEventListener listener) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        // Make sure the map exists.
        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }

        mapMapping.freehandDraw(initialStyle, listener);
    }

    @Override
    public void setFreehandStyle(IMap clientMap, IGeoStrokeStyle style) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        // Make sure the map exists.
        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }

        mapMapping.setFreehandDrawStyle(style);
    }

    @Override
    public void drawFreehandExit(IMap clientMap) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        // Make sure the map exists.
        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }

        mapMapping.freehandComplete();
    }

    @Override
    public Point geoToScreen(IMap clientMap, IGeoPosition pos) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        // Make sure the map exists.
        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }
        IMapInstance oMapInstance = mapMapping.getMapInstance();
        return oMapInstance.geoToScreen(pos);
    }

    @Override
    public IGeoPosition screenToGeo(IMap clientMap, Point point) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        // Make sure the map exists.
        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }
        IMapInstance oMapInstance = mapMapping.getMapInstance();
        return oMapInstance.screenToGeo(point);
    }

    @Override
    public Point geoToContainer(IMap clientMap, IGeoPosition pos) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        // Make sure the map exists.
        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }
        IMapInstance oMapInstance = mapMapping.getMapInstance();
        return oMapInstance.geoToContainer(pos);
    }

    @Deprecated
    @Override
    public IGeoPosition containerToGeo(IMap clientMap, Point point) throws EMP_Exception {
        return this.containerToGeo(clientMap, point == null ? null : new PointF(point.x, point.y));
    }

    @Override
    public IGeoPosition containerToGeo(IMap clientMap, PointF point) throws EMP_Exception {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        // Make sure the map exists.
        if (mapMapping == null) {
            throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_PARAMETER, "Map not found.");
        }
        IMapInstance oMapInstance = mapMapping.getMapInstance();
        return oMapInstance.containerToGeo(point);
    }

    @Override
    public void setMapGridType(IMap clientMap, MapGridTypeEnum gridType) {
        IClientMapToMapInstance mapMapping = storageManager.getMapMapping(clientMap);

        // Make sure the map exists.
        if (mapMapping == null) {
            throw new IllegalArgumentException("Map not found.");
        }
        mapMapping.setMapGridType(gridType);
    }

    private void loadMilStdLabelLists() {
        synchronized (CoreManager.oCommonLabels) {
            if (CoreManager.oCommonLabels.isEmpty()) {
                // These modifiers, if provided in the MilStd feature, must be shown
                // along with the icon. They are the only modifiers displayed when the label setting is REQUIRED.
                CoreManager.oRequiredLabels.add(IGeoMilSymbol.Modifier.EQUIPMENT_TYPE);
                CoreManager.oRequiredLabels.add(IGeoMilSymbol.Modifier.SIGNATURE_EQUIPMENT);
                CoreManager.oRequiredLabels.add(IGeoMilSymbol.Modifier.OFFSET_INDICATOR);
                CoreManager.oRequiredLabels.add(IGeoMilSymbol.Modifier.SPECIAL_C2_HEADQUARTERS);
                CoreManager.oRequiredLabels.add(IGeoMilSymbol.Modifier.FEINT_DUMMY_INDICATOR);
                CoreManager.oRequiredLabels.add(IGeoMilSymbol.Modifier.INSTALLATION);

                // These modifiers, if provided in the MilStd feature, are to be displayed with the icon
                // when the label setting is COMMON.
                CoreManager.oCommonLabels.addAll(CoreManager.oRequiredLabels);

                CoreManager.oCommonLabels.add(IGeoMilSymbol.Modifier.ADDITIONAL_INFO_1);
                CoreManager.oCommonLabels.add(IGeoMilSymbol.Modifier.ADDITIONAL_INFO_2);
                CoreManager.oCommonLabels.add(IGeoMilSymbol.Modifier.ADDITIONAL_INFO_3);
                CoreManager.oCommonLabels.add(IGeoMilSymbol.Modifier.HIGHER_FORMATION);
                CoreManager.oCommonLabels.add(IGeoMilSymbol.Modifier.UNIQUE_DESIGNATOR_1);
                CoreManager.oCommonLabels.add(IGeoMilSymbol.Modifier.UNIQUE_DESIGNATOR_2);
            }
        }
    }

    @Override
    public java.util.Set<IGeoMilSymbol.Modifier> getMilStdModifierLabelList(MilStdLabelSettingEnum eLabelSetting) {
        java.util.Set<IGeoMilSymbol.Modifier> set = null;

        if (null == eLabelSetting) {
            return null;
        }

        if (CoreManager.oCommonLabels.isEmpty()) {
            loadMilStdLabelLists();
        }
        switch (eLabelSetting) {
            case ALL_LABELS:
                break;
            case COMMON_LABELS:
                set = CoreManager.oCommonLabels;
                break;
            case REQUIRED_LABELS:
                set = CoreManager.oRequiredLabels;
                break;
        }

        return set;
    }
}


text:
require "helper"
require "google/cloud/web_risk/version"

class Google::Cloud::WebRisk::VersionMinitest < Minitest::Test
  def test_has_a_version
    refute_nil Google::Cloud::WebRisk::VERSION
  end
end


text:
package org.unitedinternet.cosmo.model.hibernate;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Index;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Target;
import org.unitedinternet.cosmo.model.Attribute;
import org.unitedinternet.cosmo.model.Item;
import org.unitedinternet.cosmo.model.QName;

/**
 * Hibernate persistent Attribute.
 */
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
// Define indexes on discriminator and key fields
@Table(
        name="attribute",
        uniqueConstraints = {
                @UniqueConstraint(columnNames={"itemid", "namespace", "localname"})},
        indexes={@Index(name="idx_attrtype", columnList="attributetype"),
                 @Index(name="idx_attrname", columnList="localname"),
                 @Index(name="idx_attrns", columnList="namespace")})
@DiscriminatorColumn(
        name="attributetype",
        discriminatorType=DiscriminatorType.STRING,
        length=16)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public abstract class HibAttribute extends HibAuditableObject implements Attribute {

    private static final long serialVersionUID = 3927093659569283339L;

    // Fields
    @Embedded
    @Target(HibQName.class)
    @AttributeOverrides( {
            @AttributeOverride(name="namespace", column = @Column(name="namespace", nullable = false, length=255) ),
            @AttributeOverride(name="localName", column = @Column(name="localname", nullable = false, length=255) )
    } )
    private QName qname;

    @ManyToOne(targetEntity=HibItem.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "itemid", nullable = false)
    private Item item;

    // Constructors
    /** default constructor */
    public HibAttribute() {
    }

    /* (non-Javadoc)
     * @see org.unitedinternet.cosmo.model.Attribute#getQName()
     */
    public QName getQName() {
        return qname;
    }

    /* (non-Javadoc)
     * @see org.unitedinternet.cosmo.model.Attribute#setQName(org.unitedinternet.cosmo.model.QName)
     */
    public void setQName(QName qname) {
        this.qname = qname;
    }

    /* (non-Javadoc)
     * @see org.unitedinternet.cosmo.model.Attribute#getName()
     */
    public String getName() {
        if(qname==null) {
            return null;
        }

        return qname.getLocalName();
    }

    /* (non-Javadoc)
     * @see org.unitedinternet.cosmo.model.Attribute#getItem()
     */
    public Item getItem() {
        return item;
    }

    /* (non-Javadoc)
     * @see org.unitedinternet.cosmo.model.Attribute#setItem(org.unitedinternet.cosmo.model.Item)
     */
    public void setItem(Item item) {
        this.item = item;
    }

    /* (non-Javadoc)
     * @see org.unitedinternet.cosmo.model.Attribute#copy()
     */
    public abstract Attribute copy();

    /**
     * Return string representation
     */
    public String toString() {
        Object value = getValue();
        if(value==null) {
            return "null";
        }
        return value.toString();
    }

    public abstract void validate();

}


text:
using namespace BloombergLP;

using bsl::cout;
using bsl::endl;
using bsl::flush;

// ============================================================================
//                                  TEST PLAN
// ----------------------------------------------------------------------------
//                                  Overview
//                                  --------
// The 'balm::IntegerMetric' class and the macros defined in this component
// primarily provide user-friendly access to a 'balm::IntegerCollector' object.
// The classes and macros supply simplified constructors (that lookup the
// appropriate 'balm::IntegerCollector' instance) and manipulator methods that
// respect whether the category of the collector is enabled.  Most of the
// tests can be performed by creating an "oracle" 'balm::IntegerCollector'
// object and verifying that operations performed on a 'balm::IntegerMetric'
// (or with a macro) have the same effect as the same operation performed
// directly on the "oracle" 'balm::IntegerCollector'.
// ----------------------------------------------------------------------------
// CLASS METHODS
// [ 9] balm::IntegerCollector *lookupCollector(const bslstl::StringRef&,
//                                              const bslstl::StringRef&,
//                                              balm::MetricsManager *);
// [ 9] balm::IntegerCollector *lookupCollector(const balm::MetricId&,
//                                              balm::MetricsManager *);
// CREATORS
// [ 2] balm::IntegerMetric(const bslstl::StringRef&  ,
//                  const bslstl::StringRef&  ,
//                  balm::MetricsManager    *);
// [ 2] explicit balm::IntegerMetric(const balm::MetricId&,
//                                  balm::MetricsManager*);
// [ 2] explicit balm::IntegerMetric(balm::IntegerCollector *collector);
// [ 5] balm::IntegerMetric(const balm::IntegerMetric& original);
// [ 2] ~balm::IntegerMetric();
// MANIPULATORS
// [ 6] void increment();
// [ 7] void update(int);
// [ 8] void accumulateCountTotalMinMax(int, int, int, int);
// [ 2] balm::IntegerCollector *collector();
// ACCESSORS
// [ 2] const balm::IntegerCollector *collector() const;
// [ 2] balm::MetricId metricId() const;
// [ 3] bool isActive() const;
// FREE OPERATORS
// [ 4]  bool operator==(const balm::IntegerMetric&,
//                       const balm::IntegerMetric&);
// [ 4]  bool operator!=(const balm::IntegerMetric&,
//                       const balm::IntegerMetric&);
// ----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [10] CONCURRENCY TEST: 'balm::IntegerMetric'
// [11] USAGE EXAMPLE

// ============================================================================
//                      STANDARD BDE ASSERT TEST MACRO
// ----------------------------------------------------------------------------
static int testStatus = 0;

static void aSsErT(int c, const char *s, int i)
{
    if (c) {
        bsl::cout << "Error " << __FILE__ << "(" << i << "): " << s
                  << "    (failed)" << bsl::endl;
        if (0 <= testStatus && testStatus <= 100) ++testStatus;
    }
}

// ============================================================================
//                      STANDARD BDE TEST DRIVER MACROS
// ----------------------------------------------------------------------------

#define ASSERT       BSLIM_TESTUTIL_ASSERT
#define LOOP_ASSERT  BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define ASSERTV      BSLIM_TESTUTIL_ASSERTV

#define Q   BSLIM_TESTUTIL_Q   // Quote identifier literally.
#define P   BSLIM_TESTUTIL_P   // Print identifier and value.
#define P_  BSLIM_TESTUTIL_P_  // P(X) without '\n'.
#define T_  BSLIM_TESTUTIL_T_  // Print a tab (w/o newline).
#define L_  BSLIM_TESTUTIL_L_  // current Line number

// ============================================================================
//                   GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
// ----------------------------------------------------------------------------
typedef balm::DefaultMetricsManager DefaultManager;
typedef balm::MetricRegistry        Registry;
typedef balm::CollectorRepository   Repository;
typedef balm::IntegerCollector      Collector;
typedef balm::MetricId              Id;
typedef balm::Category              Category;
typedef balm::IntegerMetric         Obj;
typedef balm::PublicationType       Type;

typedef bsl::shared_ptr<balm::Collector>         ColSPtr;
typedef bsl::shared_ptr<balm::IntegerCollector>  IColSPtr;
typedef bsl::vector<ColSPtr>                     ColSPtrVector;
typedef bsl::vector<IColSPtr>                    IColSPtrVector;

// ============================================================================
//                     CLASSES FOR AND FUNCTIONS TESTING
// ----------------------------------------------------------------------------

inline
balm::MetricRecord recordVal(const balm::IntegerCollector *collector)
    // Return the current record value of the specified 'collector'.
{
    balm::MetricRecord record;
    collector->load(&record);
    return record;
}

// --------------------- case 14: MetricConcurrencyTest -----------------------

class MetricConcurrencyTest {
    // Invoke a set of operations operations synchronously.

    // DATA
    bdlmt::FixedThreadPool  d_pool;
    balm::IntegerMetric    *d_metric;
    balm::MetricRegistry   *d_registry;
    bslmt::Barrier          d_barrier;
    bslma::Allocator       *d_allocator_p;

    // PRIVATE MANIPULATORS
    void execute();
        // Execute a single test.

  public:

    // CREATORS
    MetricConcurrencyTest(int                  numThreads,
                          balm::IntegerMetric  *metric,
                          balm::MetricRegistry *registry,
                          bslma::Allocator     *basicAllocator)
    : d_pool(numThreads, 1000, basicAllocator)
    , d_metric(metric)
    , d_registry(registry)
    , d_barrier(numThreads)
    , d_allocator_p(basicAllocator)
    {
        d_pool.start();
    }

    ~MetricConcurrencyTest() {}

    //  MANIPULATORS
    void runTest();
        // Run the test.
};

void MetricConcurrencyTest::execute()
{
    // The test is performed in two parts.  The first part of the test invokes
    // the manipulators for the 'balm::Metric' under test for a series of
    // values.  The expected value for the metric can be computed exactly, and
    // the actual value is compared against this expected value.  The second
    // part of the test performs a similar series of operations while enabling
    // and disabling the category of the metric.  The expected value for the
    // metric cannot be computed exactly, but the actual value can be tested
    // to verify that it falls within an expected range of values.

    Obj& mX = *d_metric; const Obj& MX = mX;
    Collector       *collector = mX.collector();
    const Category  *CATEGORY  = collector->metricId().category();
    collector->reset();

    const int NUM_THREADS = d_pool.numThreads();
    const int MAX_VALUE   = 20;
    const int RANGE       = 2 * MAX_VALUE - 1;

    d_barrier.wait();

    for (int i = -MAX_VALUE + 1; i < MAX_VALUE; ++i) {
        mX.increment();
        mX.update(i);
        mX.accumulateCountTotalMinMax(2, 2 * i, i * 2, i * 2);

        ASSERT(MX.isActive());
        ASSERT(collector             == mX.collector());
        ASSERT(collector             == MX.collector());
        ASSERT(collector->metricId() == MX.metricId());
    }

    d_barrier.wait();

    balm::MetricRecord recordValue; collector->load(&recordValue);
    ASSERT(4 * RANGE * NUM_THREADS == recordValue.count());
    ASSERT(RANGE * NUM_THREADS     == recordValue.total());
    ASSERT(-2 * (MAX_VALUE - 1)    == recordValue.min());
    ASSERT(2 * (MAX_VALUE - 1)     == recordValue.max());

    d_barrier.wait();

    collector->reset();

    d_barrier.wait();

    // Perform a test while modifying the whether the category is
    for (int i = -MAX_VALUE + 1; i < MAX_VALUE; ++i) {
        d_registry->setCategoryEnabled(CATEGORY, true);

        mX.increment();
        mX.update(i);
        mX.accumulateCountTotalMinMax(1, i, i, i);

        d_registry->setCategoryEnabled(CATEGORY, false);

        mX.increment();
        mX.update(i);
        mX.accumulateCountTotalMinMax(1, i, i, i);

        MX.isActive();
        ASSERT(collector             == mX.collector());
        ASSERT(collector             == MX.collector());
        ASSERT(collector->metricId() == MX.metricId());
    }

    d_barrier.wait();

    collector->load(&recordValue);
    ASSERT(3 <= recordValue.count() &&
           6 * RANGE * NUM_THREADS >= recordValue.count());
    ASSERT(NUM_THREADS * 6 * -MAX_VALUE <= recordValue.total() &&
           NUM_THREADS * 6 * MAX_VALUE  >= recordValue.total());
    ASSERT(-MAX_VALUE + 1 == recordValue.min());
    ASSERT(MAX_VALUE  - 1 >= recordValue.max() &&
           1              <= recordValue.max());
    ASSERT(!MX.isActive());
    d_barrier.wait();

}

void MetricConcurrencyTest::runTest()
{
    bsl::function<void()> job = bdlf::BindUtil::bind(
                                               &MetricConcurrencyTest::execute,
                                                this);
    for (int i = 0; i < d_pool.numThreads(); ++i) {
        d_pool.enqueueJob(job);
    }
    d_pool.drain();
}

// ============================================================================
//                               USAGE EXAMPLE
// ----------------------------------------------------------------------------

///Usage
///-----
// The following examples demonstrate how to configure, collect, and publish
// metrics.
//
///Example 1 - Metric collection with 'balm::IntegerMetric'
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// We can use 'balm::IntegerMetric' objects to record metric values.  In this
// example we implement a hypothetical event manager object.  We use
// 'balm::IntegerMetric' objects to record metrics for the size of the request,
// the elapsed processing time, and the number of failures.
//..
    class EventManager {

        // DATA
        balm::IntegerMetric d_messageSize;
        balm::IntegerMetric d_elapsedTime;
        balm::IntegerMetric d_failedRequests;

      public:

        // CREATORS
        EventManager()
        : d_messageSize("MyCategory", "EventManager/size")
        , d_elapsedTime("MyCategory", "EventManager/elapsedTime")
        , d_failedRequests("MyCategory", "EventManager/failedRequests")
        {}

        // MANIPULATORS
        int handleEvent(int eventId, const bsl::string& eventMessage)
            // Process the event described by the specified 'eventId' and
            // 'eventMessage' .  Return 0 on success, and a non-zero value
            // if there was an error handling the event.
        {
           int returnCode = 0;

           d_messageSize.update(eventMessage.size());

           bsls::TimeInterval start = bdlt::CurrentTime::now();

           // Process 'data' ('returnCode' may change).

           if (0 != returnCode) {
               d_failedRequests.increment();
           }

           bsls::TimeInterval end = bdlt::CurrentTime::now();
           d_elapsedTime.update((end - start).totalMicroseconds());
           return returnCode;
        }

    // ...
    };
//..

// ============================================================================
//                               MAIN PROGRAM
// ----------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int        test = argc > 1 ? bsl::atoi(argv[1]) : 0;
    int     verbose = argc > 2;
    int veryVerbose = argc > 3;

    bsl::cout << "TEST " << __FILE__ << " CASE " << test << bsl::endl;;

    bslma::TestAllocator testAlloc; bslma::TestAllocator *Z = &testAlloc;
    bslma::TestAllocator defaultAllocator;
    bslma::DefaultAllocatorGuard guard(&defaultAllocator);

    switch (test) { case 0:  // Zero is always the leading case.
      case 11: {
        // --------------------------------------------------------------------
        // TESTING USAGE EXAMPLE
        //
        // Concerns:
        //   The usage example provided in the component header file must
        //   compile, link, and run on all platforms as shown.
        //
        // Plan:
        //   Incorporate usage example from header into driver, remove leading
        //   comment characters, and replace 'assert' with 'ASSERT'.
        //
        // Testing:
        //   USAGE EXAMPLE
        // --------------------------------------------------------------------

        if (verbose) cout << "\nTesting Usage Example"
                          << "\n=====================" << endl;

///Example 2 - Create and access the default 'balm::MetricsManager' instance
///- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// This example demonstrates how to create the default 'balm::MetricManager'
// instance and perform a trivial configuration.
//
// First we create a 'balm::DefaultMetricsManagerScopedGuard', which manages
// the lifetime of the default metrics manager instance.  At construction, we
// provide the scoped guard an output stream ('stdout') that it will publish
// metrics to.  Note that the default metrics manager is intended to be created
// and destroyed by the *owner* of 'main'.  An instance of the manager should
// be created during the initialization of an application (while the task has a
// single thread) and destroyed just prior to termination (when there is
// similarly a single thread).
//..
//  int main(int argc, char *argv[])
    {
        // ...

        balm::DefaultMetricsManagerScopedGuard managerGuard(bsl::cout);
//..
// Once the default instance has been created, it can be accessed using the
// 'instance' operation.
//..
        balm::MetricsManager *manager =
                                       balm::DefaultMetricsManager::instance();
        ASSERT(0 != manager);
//..
// Note that the default metrics manager will be released when 'managerGuard'
// exits this scoped and is destroyed.  Clients that choose to explicitly call
// 'balm::DefaultMetricsManager::create' must also explicitly call
// 'balm::DefaultMetricsManager::release()'.
//
// Now that we have created a 'balm::MetricsManager' instance, we can use the
// instance to publish metrics collected using the event manager described in
// Example 1:
//..
        EventManager eventManager;

        eventManager.handleEvent(0, "ab");
        eventManager.handleEvent(0, "abc");
        eventManager.handleEvent(0, "abc");
        eventManager.handleEvent(0, "abdef");

        manager->publishAll();

        eventManager.handleEvent(0, "ab");
        eventManager.handleEvent(0, "abc");
        eventManager.handleEvent(0, "abc");
        eventManager.handleEvent(0, "abdef");

        eventManager.handleEvent(0, "a");
        eventManager.handleEvent(0, "abc");
        eventManager.handleEvent(0, "abc");
        eventManager.handleEvent(0, "abdefg");

        manager->publishAll();
    }
//..
    } break;
      case 10: {
        // --------------------------------------------------------------------
        // CONCURRENCY TEST: 'balm::IntegerMetric'
        //
        // Testing:
        //     Thread-safety of 'balm::IntegerMetric' methods.
        //
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "TEST CONCURRENCY: 'balm::IntegerMetric'" << endl
                          << "======================================" << endl;

        bslma::TestAllocator defaultAllocator;

        balm::MetricsManager mgr(Z);
        Registry&   registry   = mgr.metricRegistry();
        Repository& repository = mgr.collectorRepository();
        balm::IntegerMetric metric(repository.getDefaultIntegerCollector(
                                                             "Test", "Test"));

        bslma::TestAllocator testAllocator;
        {
            MetricConcurrencyTest tester(10, &metric,
                                         &registry,  &testAllocator);
            tester.runTest();
        }
      } break;
      case 9: {
        // --------------------------------------------------------------------
        // TESTING: 'lookupCollector'
        //
        // Concerns:
        //   That 'lookupCollector' properly looks up a collector from the
        //   supplied metrics manager, or from the default metrics manager, if
        //   none is supplied.
        //
        // Plan:
        //
        //
        // Testing:
        //   balm::IntegerCollector *lookupCollector(const bslstl::StringRef&,
        //                                           const bslstl::StringRef&,
        //                                           balm::MetricsManager *);
        //   balm::IntegerCollector *lookupCollector(const balm::MetricId&,
        //                                           balm::MetricsManager *);
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "TESTING: 'lookupCollector'\n"
                          << "==========================\n";

        const char *IDS[] = {"A", "B", "AB", "TEST"};
        const int NUM_IDS = sizeof IDS / sizeof *IDS;

        if (veryVerbose)
            cout << "\tverify with no default metrics manager\n";
        {
            balm::MetricRegistry registry(Z);
            for (int i = 0; i < NUM_IDS; ++i) {
                balm::MetricId id = registry.getId(IDS[i], IDS[i]);
                ASSERT(0 == Obj::lookupCollector(IDS[i], IDS[i], 0));
                ASSERT(0 == Obj::lookupCollector(IDS[i], IDS[i]));
                ASSERT(0 == Obj::lookupCollector(id, 0));
                ASSERT(0 == Obj::lookupCollector(id));
            }
        }

        if (veryVerbose)
            cout << "\tverify with explicit metrics manager\n";
        {
            balm::MetricsManager mgr;
            Registry&   registry   = mgr.metricRegistry();
            Repository& repository = mgr.collectorRepository();

            for (int i = 0; i < NUM_IDS; ++i) {
                balm::MetricId id = registry.getId(IDS[i], IDS[i]);
                balm::IntegerCollector *col =
                                    repository.getDefaultIntegerCollector(id);
                ASSERT(col == Obj::lookupCollector(IDS[i], IDS[i], &mgr));
                ASSERT(col == Obj::lookupCollector(id, &mgr));
            }
        }

        if (veryVerbose)
            cout << "\tverify with default metrics manager\n";
        {
            balm::DefaultMetricsManagerScopedGuard guard(Z);
            balm::MetricsManager& mgr = *DefaultManager::instance();
            Registry&   registry   = mgr.metricRegistry();
            Repository& repository = mgr.collectorRepository();

            for (int i = 0; i < NUM_IDS; ++i) {
                balm::MetricId id = registry.getId(IDS[i], IDS[i]);
                balm::IntegerCollector *col =
                                    repository.getDefaultIntegerCollector(id);
                ASSERT(col == Obj::lookupCollector(IDS[i], IDS[i]));
                ASSERT(col == Obj::lookupCollector(IDS[i], IDS[i], 0));
                ASSERT(col == Obj::lookupCollector(id));
                ASSERT(col == Obj::lookupCollector(id, 0));
            }
        }

      } break;
      case 8: {
        // --------------------------------------------------------------------
        // TESTING: 'accumulateCountTotalMinMax'
        //
        // Concerns:
        //   That 'accumulateCountTotalMinMax' properly invokes the metric's
        //   collector's 'accumulateCountTotalMinMax' method.
        //
        // Plan:
        //   Specify a set S of unique object values having various minor or
        //   subtle differences.  For each value create an "oracle" collector,
        //   invoke 'accumulateCountTotalMinMax' on the metric and the
        //   "oracle", and verify the collector underlying the metric has the
        //   same value as the "oracle" collector.
        //
        //   Perform the same test again, but enabled or disable the metric's
        //   category on each iteration.
        //
        // Testing:
        //   void accumulateCountTotalMinMax(int, int, int, int);
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "TESTING: 'accumulateCountTotalMinMax'\n"
                          << "=====================================\n";

        const char *IDS[] = {"A", "B", "AB", "TEST"};
        const int NUM_IDS = sizeof IDS / sizeof *IDS;

        struct {
            int d_count;
            int d_total;
            int d_min;
            int d_max;
        } VALUES [] = {
            {         0,         0,               0,                0 },
            {         1,         1,               1,                1 },
            {      1210,   INT_MAX,     INT_MIN + 1,      INT_MAX - 1 },
            {         1,         2,               3,                4 },
            {        10,        -2,              -3,               -4 },
            {      123110, INT_MIN,     INT_MAX - 1,      INT_MIN + 1 },
            {     -12311,   231413,           -1123,           410001 },
         };
        const int NUM_VALUES = sizeof(VALUES)/sizeof(*VALUES);

        if (veryVerbose)
            cout << "\tverify 'accumulateCountTotalMinMax' is applied "
                 << "correctly.\n";
        {
            balm::MetricsManager mgr(Z);
            Registry&   registry   = mgr.metricRegistry();
            Repository& repository = mgr.collectorRepository();

            for (int i = 0; i < NUM_IDS; ++i) {
                balm::IntegerCollector *col =
                         repository.getDefaultIntegerCollector(IDS[i], IDS[i]);
                balm::IntegerCollector  expValue(col->metricId());

                balm::IntegerMetric mX(col);

                for (int j = 0; j < NUM_VALUES; ++j) {
                    ASSERT(recordVal(&expValue) == recordVal(col));
                    mX.accumulateCountTotalMinMax(VALUES[j].d_count,
                                                  VALUES[j].d_total,
                                                  VALUES[j].d_min,
                                                  VALUES[j].d_max);
                    expValue.accumulateCountTotalMinMax(VALUES[j].d_count,
                                                        VALUES[j].d_total,
                                                        VALUES[j].d_min,
                                                        VALUES[j].d_max);

                    ASSERT(recordVal(&expValue) == recordVal(col));
                }
            }
        }
        if (veryVerbose)
            cout << "\tverify 'accumulateCountTotalMinMax' respects "
                 << "'isActive' flag.\n";

        {
            for (int i = 0; i < NUM_IDS; ++i) {
                balm::MetricsManager mgr(Z);
                Registry&   registry   = mgr.metricRegistry();
                Repository& repository = mgr.collectorRepository();

                balm::IntegerCollector *col =
                         repository.getDefaultIntegerCollector(IDS[i], IDS[i]);
                balm::IntegerCollector  expValue(col->metricId());
                const Category *CATEGORY = col->metricId().category();

                balm::IntegerMetric  mX(col);
                const balm::IntegerMetric& MX = mX;

                for (int j = 0; j < NUM_VALUES; ++j) {
                    ASSERT(recordVal(&expValue) == recordVal(col));

                    bool enabled = 0 == j % 2;
                    registry.setCategoryEnabled(CATEGORY, enabled);
                    mX.accumulateCountTotalMinMax(VALUES[j].d_count,
                                                  VALUES[j].d_total,
                                                  VALUES[j].d_min,
                                                  VALUES[j].d_max);
                    if (enabled) {
                        expValue.accumulateCountTotalMinMax(VALUES[j].d_count,
                                                            VALUES[j].d_total,
                                                            VALUES[j].d_min,
                                                            VALUES[j].d_max);
                    }
                    ASSERT(enabled == MX.isActive());
                    ASSERT(recordVal(&expValue) == recordVal(col));
                }
            }
        }

      } break;
      case 7: {
        // --------------------------------------------------------------------
        // TESTING: 'update'
        //
        // Concerns:
        //   That 'update' properly invokes the metric's collector's
        //   'update' method.
        //
        // Plan:
        //   Specify a set S of unique object values having various minor or
        //   subtle differences.  For each value create an "oracle" collector,
        //   update the metric and the "oracle", and verify the collector's
        //   underlying the metric has the same value as the "oracle"
        //   collector.
        //
        //   Perform the same test again, but enabled or disable the metric's
        //   category on each iteration.
        //
        // Testing:
        //    void update(int );
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "TESTING: 'update'\n"
                          << "=================\n";

        const char *IDS[] = {"A", "B", "AB", "TEST"};
        const int NUM_IDS = sizeof IDS / sizeof *IDS;

        int UPDATES[] = { 0, 12, -1321123, 2131241, 1321,
                            43145, 1, -1, INT_MIN + 1, INT_MAX - 1};
        const int NUM_UPDATES = sizeof(UPDATES)/sizeof(*UPDATES);

        if (veryVerbose)
            cout << "\tverify 'update'  applied correctly.\n";

        {
            balm::MetricsManager mgr(Z);
            Registry&   registry   = mgr.metricRegistry();
            Repository& repository = mgr.collectorRepository();

            for (int i = 0; i < NUM_IDS; ++i) {
                balm::IntegerCollector *col =
                         repository.getDefaultIntegerCollector(IDS[i], IDS[i]);
                balm::IntegerCollector  expValue(col->metricId());

                balm::IntegerMetric mX(col);

                for (int j = 0; j < NUM_UPDATES; ++j) {
                    ASSERT(recordVal(&expValue) == recordVal(col));
                    mX.update(UPDATES[j]);
                    expValue.update(UPDATES[j]);
                    ASSERT(recordVal(&expValue) == recordVal(col));
                }
            }
        }

        if (veryVerbose)
            cout << "\tverify 'update' respects 'isActive' flag.\n";

        {
            for (int i = 0; i < NUM_IDS; ++i) {
                balm::MetricsManager mgr(Z);
                Registry&   registry   = mgr.metricRegistry();
                Repository& repository = mgr.collectorRepository();

                balm::IntegerCollector *col =
                         repository.getDefaultIntegerCollector(IDS[i], IDS[i]);
                balm::IntegerCollector  expValue(col->metricId());
                const Category *CATEGORY = col->metricId().category();

                balm::IntegerMetric  mX(col);
                const balm::IntegerMetric& MX = mX;

                for (int j = 0; j < NUM_UPDATES; ++j) {
                    ASSERT(recordVal(&expValue) == recordVal(col));

                    bool enabled = 0 == j % 2;
                    registry.setCategoryEnabled(CATEGORY, enabled);
                    mX.update(UPDATES[j]);
                    if (enabled) {
                        expValue.update(UPDATES[j]);
                    }
                    ASSERT(enabled == MX.isActive());
                    ASSERT(recordVal(&expValue) == recordVal(col));
                }
            }
        }
      } break;
      case 6: {
        // --------------------------------------------------------------------
        // TESTING: 'increment'
        //
        // Concerns:
        //   That 'increment' properly invokes the metric's collector's
        //   'increment' method.  That 'increment' properly observers the
        //   categories 'enabled' status.
        //
        // Plan:
        //   Specify a set S of unique object values having various minor or
        //   subtle differences.  For each value create an "oracle" collector,
        //   increment the metric and the "oracle", and verify the collector's
        //   underlying the metric has the same value as the "oracle"
        //   collector.
        //
        //   Perform the same test again, but enabled or disable the metric's
        //   category on each iteration.
        //
        // Testing:
        //    void increment();
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "TESTING: 'increment()'\n"
                          << "=====================\n";

        const char *IDS[] = {"A", "B", "AB", "TEST"};
        const int NUM_IDS = sizeof IDS / sizeof *IDS;

        if (veryVerbose)
            cout << "\tverify 'increment()' is applied correctly.\n";

        {
            balm::MetricsManager mgr(Z);
            Registry&   registry   = mgr.metricRegistry();
            Repository& repository = mgr.collectorRepository();
            for (int i = 0; i < NUM_IDS; ++i) {
                balm::IntegerCollector *col =
                         repository.getDefaultIntegerCollector(IDS[i], IDS[i]);
                balm::IntegerCollector  expValue(col->metricId());

                balm::IntegerMetric mX(col);

                for (int j = 0; j < 10; ++j) {
                    ASSERT(recordVal(&expValue) == recordVal(col));
                    mX.increment();
                    expValue.update(1);
                    ASSERT(recordVal(&expValue) == recordVal(col));
                }
            }
        }

        if (veryVerbose)
            cout << "\tverify 'increment' respects 'isActive' flag.\n";

        {
            for (int i = 0; i < NUM_IDS; ++i) {
                balm::MetricsManager mgr(Z);
                Registry&   registry   = mgr.metricRegistry();
                Repository& repository = mgr.collectorRepository();

                balm::IntegerCollector *col =
                         repository.getDefaultIntegerCollector(IDS[i], IDS[i]);
                balm::IntegerCollector  expValue(col->metricId());
                const Category *CATEGORY = col->metricId().category();

                balm::IntegerMetric  mX(col);
                const balm::IntegerMetric& MX = mX;

                for (int j = 0; j < 10; ++j) {
                    ASSERT(recordVal(&expValue) == recordVal(col));

                    bool enabled = 0 == j % 2;
                    registry.setCategoryEnabled(CATEGORY, enabled);
                    mX.increment();
                    if (enabled) {
                        expValue.update(1);
                    }
                    ASSERT(enabled == MX.isActive());
                    ASSERT(recordVal(&expValue) == recordVal(col));
                }
            }
        }
      } break;
      case 5: {
        // --------------------------------------------------------------------
        // TESTING COPY CONSTRUCTOR:
        //
        // Concerns:
        //   Any value must be able to be copy constructed without affecting
        //   its argument.
        //
        // Plan:
        //   Specify a set S whose elements have substantial and varied
        //   differences in value.  For each element in S, construct and
        //   initialize identically valued objects w and x using tested
        //   methods.  Then copy construct an object y from x, and use the
        //   equality operator to assert that both x and y have the same value
        //   as w.
        //
        // Testing:
        //   balm::MetricRecord(const balm::MetricRecord& );
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "TESTPING COPY CONSTRUCTOR\n"
                          << "=========================\n";

        const char *VALUES[] = {"A", "B", "AB", "TEST"};
        const int NUM_VALUES = sizeof VALUES / sizeof *VALUES;

        balm::MetricsManager mgr(Z);
        Registry&   registry   = mgr.metricRegistry();
        Repository& repository = mgr.collectorRepository();

        for (int i = 0; i < NUM_VALUES; ++i) {

            Id   id = registry.getId(VALUES[i], VALUES[i]);
            Collector *collector = repository.getDefaultIntegerCollector(id);

            Obj x(collector); const Obj& X = x;
            Obj w(collector); const Obj& W = w;

            Obj y(X); const Obj& Y = y;

            ASSERT(W == Y);
            ASSERT(X == Y);

            // Test that the enabled flag is passed correctly.
            ASSERT(W.isActive());
            ASSERT(X.isActive());
            ASSERT(Y.isActive());

            registry.setCategoryEnabled(id.category(), false);
            ASSERT(!W.isActive());
            ASSERT(!X.isActive());
            ASSERT(!Y.isActive());

            registry.setCategoryEnabled(id.category(), true);
            ASSERT(W.isActive());
            ASSERT(X.isActive());
            ASSERT(Y.isActive());
        }

      } break;
      case 4: {
        // --------------------------------------------------------------------
        // TESTING EQUALITY OPERATOR
        //
        // Concerns:
        //   Any subtle variation in value must be detected by the equality
        //   operators.  The test data have variations in each input parameter,
        //   even though tested methods convert the input before the underlying
        //   equality operators are invoked.
        //
        // Plan:
        //   Specify a set S of unique object values having various minor or
        //   subtle differences.  Verify the correctness of 'operator==' and
        //   'operator!=' using all elements (u, v) of the cross product
        //    S X S.
        //
        // Testing:
        //   bool operator==(const balm::IntegerMetric&,
        //                   const balm::IntegerMetric&);
        //   bool operator!=(const balm::IntegerMetric&,
        //                   const balm::IntegerMetric&);
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "TESTPING EQUALITY OPERATOR\n"
                          << "==========================\n";

        const char *VALUES[] = {"A", "B", "AB", "TEST"};
        const int NUM_VALUES = sizeof VALUES / sizeof *VALUES;

        balm::MetricsManager mgr(Z);
        Registry&   registry   = mgr.metricRegistry();
        Repository& repository = mgr.collectorRepository();

        for (int i = 0; i < NUM_VALUES; ++i) {
            Obj u(repository.getDefaultIntegerCollector(VALUES[i], VALUES[i]));
            const Obj& U = u;

            for (int j = 0; j < NUM_VALUES; ++j) {
            Obj v(repository.getDefaultIntegerCollector(VALUES[j], VALUES[j]));
                const Obj& V = v;

                bool isEqual = i == j;
                LOOP2_ASSERT(i, j, isEqual  == (U == V));
                LOOP2_ASSERT(i, j, !isEqual == (U != V))
            }
        }

      } break;
      case 3: {
        // --------------------------------------------------------------------
        // TESTING: 'isActive'
        //
        // Concerns:
        //   That 'isActive' returns 'true' if the collector's category is
        //   enabled and 'false' if the collector's category is disabled, and
        //   that 'isActive' always returns 'false' if the metric's collector
        //   it is 0.
        //
        // Plan:
        //   Specify a set S of unique object values having various minor or
        //   subtle differences.  For each value, verify that disabling the
        //   'balm::Category' sets the metric's 'isActive' flag to 'false', and
        //   that enabling the category sets the metric's 'isActive' flag to
        //   'true'.  Also verify that a 'balm::IntegerMetric' with a null
        //   collector always returns 'false' for 'isActive'.
        //
        // Testing:
        //   bool isActive() const;
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "TESTING: 'isActive()'\n"
                          << "=====================\n";

        const char *IDS[] = {"A", "B", "AB", "TEST"};
        const int NUM_IDS = sizeof IDS / sizeof *IDS;

        balm::MetricsManager mgr(Z);
        Registry&   registry   = mgr.metricRegistry();
        Repository& repository = mgr.collectorRepository();

        for (int i = 0; i < NUM_IDS; ++i) {
            const Category *CATEGORY = registry.getCategory(IDS[i]);

            Obj mX(IDS[i], IDS[i], &mgr); const Obj& MX = mX;
            Obj mY(IDS[i], IDS[i]); const Obj& MY = mY;

            ASSERT( MX.isActive());
            ASSERT(!MY.isActive());

            registry.setCategoryEnabled(CATEGORY, false);

            ASSERT(!MX.isActive());
            ASSERT(!MY.isActive());

            registry.setCategoryEnabled(CATEGORY, true);

            ASSERT(MX.isActive());
            ASSERT(!MY.isActive());

            registry.setCategoryEnabled(CATEGORY, false);

            ASSERT(!MX.isActive());
            ASSERT(!MY.isActive());
        }

      } break;
      case 2: {
        // --------------------------------------------------------------------
        // TESTING BASIC CONSTRUCTORS & ACCESSORS (BOOTSTRAP):
        //
        //
        // Concerns:
        //   The primary fields must be set by the constructors and correctly
        //   accessible.
        //
        // Plan:
        //   Specify a set S of unique object values having various minor or
        //   subtle differences.
        //
        //   Create a 'balm::IntegerMetric' object for each member of set S
        //   without a metrics manager or default metrics manager and verify
        //   their collector value is 0.
        //
        //   Create a 'balm::IntegerMetric' object for each member of set S and
        //   explicitly specify the metrics manager.  Verify the collector
        //   value is the correct collector from the metrics manager supplied
        //   at construction.
        //
        //   Create a default metrics manager.  Then create a
        //   'balm::IntegerMetric' object for each member of set S without
        //   (explicitly) specifying a metrics manager.  Verify the collector
        //   value is the correct collector from the default metrics manager.
        //
        // Testing:
        //    balm::IntegerMetric(const bslstl::StringRef&  ,
        //                const bslstl::StringRef&  ,
        //                balm::MetricsManager    *);
        //    explicit balm::IntegerMetric(const balm::MetricId&  ,
        //                         balm::MetricsManager  *);
        //    explicit balm::IntegerMetric(balm::IntegerCollector *);
        //    ~balm::IntegerMetric();
        //    balm::IntegerCollector *collector();
        //    const balm::IntegerCollector *collector() const;
        //    balm::MetricId metricId() const;
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "TESTPING PRIMARY ACCESSORS\n"
                          << "==========================\n";

        const char *IDS[] = {"A", "B", "AB", "TEST"};
        const int NUM_IDS = sizeof IDS / sizeof *IDS;

        balm::MetricsManager mgr(Z);
        Registry&   registry   = mgr.metricRegistry();
        Repository& repository = mgr.collectorRepository();

        if (veryVerbose)
            cout << "\tTest construction with no default metrics manager\n";

        for (int i = 0; i < NUM_IDS; ++i) {
            Obj mX(IDS[i], IDS[i]); const Obj& MX = mX;
            Obj mY(registry.getId(IDS[i], IDS[i])); const Obj& MY = mY;

            ASSERT(0 == mX.collector());
            ASSERT(0 == mY.collector());
            ASSERT(0 == MX.collector());
            ASSERT(0 == MY.collector());
        }

        if (veryVerbose)
            cout << "\ttest with an explicit metrics manager\n";

        for (int i = 0; i < NUM_IDS; ++i) {
            const Id   ID = registry.getId(IDS[i], IDS[i]);
            Collector *COL = repository.getDefaultIntegerCollector(ID);
            Obj mX(IDS[i], IDS[i], &mgr); const Obj& MX = mX;
            Obj mY(ID, &mgr); const Obj& MY = mY;
            Obj mZ(COL); const Obj& MZ = mZ;

            ASSERT(COL == mX.collector());
            ASSERT(COL == mY.collector());
            ASSERT(COL == mZ.collector());
            ASSERT(COL == MX.collector());
            ASSERT(COL == MY.collector());
            ASSERT(COL == MZ.collector());

            ASSERT(ID == mX.metricId());
            ASSERT(ID == mY.metricId());
            ASSERT(ID == mZ.metricId());
            ASSERT(ID == MX.metricId());
            ASSERT(ID == MY.metricId());
            ASSERT(ID == MZ.metricId());

            ASSERT(0 == defaultAllocator.numBytesInUse());
        }

        if (veryVerbose)
            cout << "\ttest with the default metrics manager\n";
        {
            balm::DefaultMetricsManagerScopedGuard guard(Z);
            balm::MetricsManager& mgr = *DefaultManager::instance();

            Registry&   registry   = mgr.metricRegistry();
            Repository& repository = mgr.collectorRepository();

            for (int i = 0; i <NUM_IDS; ++i) {
                const Id   ID  = registry.getId(IDS[i], IDS[i]);
                Collector *COL = repository.getDefaultIntegerCollector(ID);
                Obj mX(IDS[i], IDS[i]); const Obj& MX = mX;
                Obj mY(ID); const Obj& MY = mY;

                ASSERT(COL == mX.collector());
                ASSERT(COL == mY.collector());
                ASSERT(COL == MX.collector());
                ASSERT(COL == MY.collector());
                ASSERT(ID == mX.metricId());
                ASSERT(ID == mY.metricId());
                ASSERT(ID == MX.metricId());
                ASSERT(ID == MY.metricId());

                ASSERT(0 == defaultAllocator.numBytesInUse());
            }
        }

      } break;
      case 1: {
        // --------------------------------------------------------------------
        // BREATHING TEST:
        //   Developers' Sandbox.
        //
        // Concerns:
        //
        // Plan:
        //
        // Testing:
        //   This "test" *exercises* basic functionality, but *tests* nothing.
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "BREATHING TEST" << endl
                          << "==============" << endl;

        {
            balm::MetricsManager       manager(Z);
            balm::MetricRegistry&      registry = manager.metricRegistry();
            balm::CollectorRepository& repository =
                                                manager.collectorRepository();

            balm::IntegerCollector *A_COL =
                               repository.getDefaultIntegerCollector("A", "A");
            balm::IntegerCollector *B_COL =
                               repository.getDefaultIntegerCollector("B", "B");

            const Id A_ID = A_COL->metricId();
            const Id B_ID = B_COL->metricId();

            if (veryVerbose) cout << "\tTesting 'bcemt::Metric'" << endl;

            Obj a1("A", "A", &manager);                 const Obj& A1 = a1;
            Obj a2(registry.getId("A", "A"), &manager); const Obj& A2 = a2;
            Obj a3(repository.getDefaultIntegerCollector("A", "A"));
            const Obj& A3 = a3;

            Obj b1("B", "B", &manager);                 const Obj& B1 = b1;
            Obj b2(registry.getId("B", "B"), &manager); const Obj& B2 = b2;
            Obj b3(repository.getDefaultIntegerCollector("B", "B"));
            const Obj& B3 = b3;

            Obj invalid1("A", "A");
            const Obj& INVALID1 = invalid1;
            Obj invalid2(registry.getId("A", "A"));
            const Obj& INVALID2 = invalid2;

            ASSERT(A1 == A2 && A2 == A3);
            ASSERT(B1 == B2 && B2 == B3);
            ASSERT(!(A1 == B1));
            ASSERT(!(A2 == B2));
            ASSERT(!(A3 == B3));

            ASSERT(A_COL == a1.collector());
            ASSERT(A_COL == a2.collector());
            ASSERT(A_COL == a3.collector());
            ASSERT(A_COL == A1.collector());
            ASSERT(A_COL == A2.collector());
            ASSERT(A_COL == A3.collector());

            ASSERT(B_COL == b1.collector());
            ASSERT(B_COL == b2.collector());
            ASSERT(B_COL == b3.collector());
            ASSERT(B_COL == B1.collector());
            ASSERT(B_COL == B2.collector());
            ASSERT(B_COL == B3.collector());

            ASSERT(0     == invalid1.collector());
            ASSERT(0     == invalid2.collector());
            ASSERT(0     == INVALID1.collector());
            ASSERT(0     == INVALID2.collector());

            ASSERT(A1.isActive());
            ASSERT(A2.isActive());
            ASSERT(A3.isActive());
            ASSERT(B1.isActive());
            ASSERT(B2.isActive());
            ASSERT(B3.isActive());
            ASSERT(!INVALID1.isActive());
            ASSERT(!INVALID2.isActive());

            ASSERT(A_ID == A1.metricId());
            ASSERT(A_ID == A2.metricId());
            ASSERT(A_ID == A3.metricId());
            ASSERT(B_ID == B1.metricId());
            ASSERT(B_ID == B2.metricId());
            ASSERT(B_ID == B3.metricId());

            ASSERT(balm::MetricRecord(A_ID) == recordVal(A_COL));
            ASSERT(balm::MetricRecord(B_ID) == recordVal(B_COL));

            a1.increment();
            a2.increment();
            a3.increment();
            b1.increment();
            b2.increment();
            b3.increment();

            ASSERT(balm::MetricRecord(A_ID, 3, 3, 1, 1) == recordVal(A_COL));
            ASSERT(balm::MetricRecord(B_ID, 3, 3, 1, 1) == recordVal(B_COL));

            a1.update(2);
            a2.update(2);
            a3.update(2);
            b1.update(2);
            b2.update(2);
            b3.update(2);

            ASSERT(balm::MetricRecord(A_ID, 6, 9, 1, 2) == recordVal(A_COL));
            ASSERT(balm::MetricRecord(B_ID, 6, 9, 1, 2) == recordVal(B_COL));

            a1.accumulateCountTotalMinMax(2, 3, -1, -1);
            a2.accumulateCountTotalMinMax(2, 3, -1, -1);
            a3.accumulateCountTotalMinMax(2, 3, -1, -1);
            b1.accumulateCountTotalMinMax(2, 3, -1, -1);
            b2.accumulateCountTotalMinMax(2, 3, -1, -1);
            b3.accumulateCountTotalMinMax(2, 3, -1, -1);

            ASSERT(
                  balm::MetricRecord(A_ID, 12, 18, -1, 2) == recordVal(A_COL));
            ASSERT(
                  balm::MetricRecord(B_ID, 12, 18, -1, 2) == recordVal(B_COL));

            ASSERT(0 == defaultAllocator.numBytesInUse());
        }
      } break;
      default: {
        bsl::cerr << "WARNING: CASE `" << test << "' NOT FOUND." << bsl::endl;
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        bsl::cerr << "Error, non-zero test status = " << testStatus << "."
                  << bsl::endl;
    }
    return testStatus;
}

// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------


text:
package main

import (
	"fmt"
	"regexp"

	asp "golang.org/x/exp/aspectgo/aspect"
)

// SAspect won't be woven, because it's not an "execution" pointcut
type SAspect struct {
}

func (a *SAspect) Pointcut() asp.Pointcut {
	s := regexp.QuoteMeta("(*golang.org/x/exp/aspectgo/example/receiver.S).Foo")
	return asp.NewCallPointcutFromRegexp(s)
}
func (a *SAspect) Advice(ctx asp.Context) []interface{} {
	return advice("SAspect", ctx)
}

// IAspect will be woven
type IAspect struct {
}

func (a *IAspect) Pointcut() asp.Pointcut {
	s := regexp.QuoteMeta("(golang.org/x/exp/aspectgo/example/receiver.I).Foo")
	return asp.NewCallPointcutFromRegexp(s)
}
func (a *IAspect) Advice(ctx asp.Context) []interface{} {
	return advice("IAspect", ctx)
}

func advice(name string, ctx asp.Context) []interface{} {
	args, recv := ctx.Args(), ctx.Receiver()
	fmt.Printf("%s BEFORE call (args=%+v, recv=%+v)\n",
		name, args, recv)
	res := ctx.Call(args)
	fmt.Printf("%s AFTER call (res=%+v)\n",
		name, res)
	return res
}


text:
git clone --depth 1 git@github.com:django/django.git &&
cp -R django/django/contrib/postgres . &&
cd postgres &&
rpl -R -x.py "from django.contrib.postgres import" "from postgres import" . &&
rpl -R -x.py "django.contrib.postgres" "postgres" . &&
rm -Rf django


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace COG.LibNoise.Operator
{
    /// <summary>
    /// Provides a noise module that outputs the absolute value of the output value from
    /// a source module. [OPERATOR]
    /// </summary>
    public class Abs : ModuleBase
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of Abs.
        /// </summary>
        public Abs()
            : base(1)
        {
        }

        /// <summary>
        /// Initializes a new instance of Abs.
        /// </summary>
        /// <param name="input">The input module.</param>
        public Abs(ModuleBase input)
            : base(1)
        {
            this.m_modules[0] = input;
        }

        #endregion

        #region ModuleBase Members

        /// <summary>
        /// Returns the output value for the given input coordinates.
        /// </summary>
        /// <param name="x">The input coordinate on the x-axis.</param>
        /// <param name="y">The input coordinate on the y-axis.</param>
        /// <param name="z">The input coordinate on the z-axis.</param>
        /// <returns>The resulting output value.</returns>
        public override double GetValue(double x, double y, double z)
        {
            System.Diagnostics.Debug.Assert(this.m_modules[0] != null);
            return Math.Abs(this.m_modules[0].GetValue(x, y, z));
        }

        #endregion
    }
}


text:
namespace Csla.Analyzers.Tests.Targets.FindGetOrReadInvocationsWalkerTests
{
  public class WalkWhenContainingTypeIsBusinessBaseAndInvocationIsLazyReadProperty
    : BusinessBase<WalkWhenContainingTypeIsBusinessBaseAndInvocationIsLazyReadProperty>
  {
    public void Go()
    {
      this.LazyReadProperty<int>(null, null);
    }
  }
}


text:
import {Entity} from "../../../../src/decorator/entity/Entity";
import {Column} from "../../../../src/decorator/columns/Column";
import {PrimaryColumn} from "../../../../src/decorator/columns/PrimaryColumn";

@Entity({ synchronize: false })
export class Photo {

    @PrimaryColumn()
    id: number;

    @Column()
    name: string;

    @Column()
    albumId: number;

}


text:
package org.opensharingtoolkit.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.opensharingtoolkit.chooser.Service;

import android.util.Log;

/**
 * @author cmg
 *
 */
public class HttpListener extends Thread {
	private static final String TAG = "kiosk-http";
	private Service service;
	private int port;
	private ServerSocket socket = null;
	private boolean stopped;
	/** cons */
	public HttpListener(Service service, int port) {
		this.service = service;
		this.port = port;
	}
	/** stop */
	public synchronized void close() {
		stopped = true;
		this.interrupt();
		closeInternal();
	}
	/** set port */
	public synchronized void setPort(int port) {
		this.port = port;
		this.interrupt();
		closeInternal();
	}
	/** run */
	public void run() {
		Log.d(TAG,"Started thread");
		while (!stopped) {
			// may interrupt...
			try {
				ServerSocket ss = null;
				synchronized (this) {
					if (socket!=null && socket.getLocalPort()!=port)
						closeInternal();
					if (socket==null) {
						try {
							socket = new ServerSocket(port);
							Log.d(TAG,"Opened server socket on port "+socket.getLocalPort());
						}
						catch (IOException e) {
							Log.e(TAG,"Unable to open server socket on port "+port+": "+e.getMessage());
							// TODO notification
							// delay to avoid racing...
							// NB holding lock!
							wait(1000);
						}
					}
					// clone reference in critical section!
					ss = socket;
				}
				if (ss!=null)
					try {
						// may have been closed concurrently, so don't worry too much
						Socket s = ss.accept();
						handleClient(s);
					} catch (IOException e) {
						Log.e(TAG,"Error in accept: "+e.getMessage());
						closeInternal();
					}
			}
			catch (InterruptedException ie) {
				// round the loop...
				Log.d(TAG,"interrupted");
			}
		}
		closeInternal();
		Log.d(TAG,"Exited thread");
	}

	private void handleClient(Socket s) {
		Log.d(TAG,"New client at "+s.getRemoteSocketAddress().toString()+":"+s.getPort());
		new HttpClientHandler(service, s).start();
	}
	/** close internal */
	private synchronized void closeInternal() {
		if (socket!=null) {
			Log.d(TAG,"Close socket on port "+socket.getLocalPort());
			try {
				socket.close();
			}
			catch (IOException e) {
				Log.e(TAG,"Error closing socket: "+e.getMessage());
			}
			socket = null;
		}
	}
}


text:
from pygw.config import java_pkg
from pygw.base import GeoWaveObject

from .simple_feature_type import SimpleFeatureType
from .attribute_descriptor import AttributeDescriptor

class SimpleFeatureTypeBuilder(GeoWaveObject):
    """
    Builds `pygw.geotools.simple_feature_type.SimpleFeatureType` instances.
    """

    def __init__(self):
        self.attributes = []
        super().__init__(java_pkg.org.geotools.feature.simple.SimpleFeatureTypeBuilder())

    def set_name(self, name):
        """
        Sets the name of the feature type.

        Args:
            name (str): The name to use.
        Returns:
            This feature type builder.
        """
        self._java_ref.setName(name)
        return self

    def set_namespace_uri(self, namespace_uri):
        """
        Sets the namespace URI of the feature type.

        Args:
            namespace_uri (str): The namespace URI to use.
        Returns:
            This feature type builder.
        """
        self._java_ref.setNamespaceURI(namespace_uri)
        return self

    def set_srs(self, srs):
        """
        Sets the spatial reference system of the feature type.

        Args:
            srs (str): The spatial reference system to use.
        Returns:
            This feature type builder.
        """
        self._java_ref.setSRS(srs)
        return self

    def add(self, attribute_descriptor):
        """
        Adds an attribute to the feature type.

        Args:
            attribute_descriptor (pygw.geotools.attribute_descriptor.AttributeDescriptor): The attribute to add.
        Returns:
            This feature type builder.
        """
        if isinstance(attribute_descriptor, AttributeDescriptor):
            self.attributes.append(attribute_descriptor)
            self._java_ref.add(attribute_descriptor._java_ref)
            return self
        else:
            raise ValueError("attribute_descriptor should be of type AttributeDescriptor")

    def build_feature_type(self):
        """
        Builds the configured feature type.

        Returns:
            A `pygw.geotools.simple_feature_type.SimpleFeatureType` with the given configuration.
        """
        return SimpleFeatureType(self._java_ref.buildFeatureType(), self.attributes)


text:
#ifndef _CBTREE_H
#define _CBTREE_H

#include <stdint.h>
#include <stdio.h>

struct cbtree {
  void *root;
};

/* Re: use of intptr_t instead of void * or a union { void *; int }:
 * I am aware it is not recommened (see
 * http://stackoverflow.com/questions/9492798/using-intptr-t-instead-of-void),
 * but I am not sure I agree;  maybe I just don't understand all
 * implications.  Anyways, Judy trees, which I am replacing in my code
 * with this tiny library, are using "unsigned long", which
 * is even worse, but works everywherewhere I tested it.
 */

/* Search for the string u in the tree t.
 * Returns:
 *   NULL if not found, or
 *   a pointer to a user value associated with the string
 */
intptr_t *cbtree_find(struct cbtree *t, const char *u);

/* Insert the string u into the tree t.
 * Returns:
 *   NULL in case of an error, or
 *   a pointer to a user value associated with the string;
 *   the user value will be initialized to 0 in
 *   case the insertion has happened, and left
 *   untouched in case the string was already in the tree.
 */
intptr_t *cbtree_insert(struct cbtree *t, const char *u);

/* Delete the string u from the tree t.
 * Returns:
 *   0 in case u was not in t, or
 *   a user value which was associated with the string;
 *   please note that the user value can be 0 as well,
 *   so there is no general way to distinguish these two
 *   situations
 */
intptr_t cbtree_delete(struct cbtree *t, const char *u);

void cbtree_clear(struct cbtree *t);

int cbtree_allprefixed(struct cbtree *t, const char *prefix,
                       int (*handle)(const char *, intptr_t *, void *),
                       void *arg);

void cbtree_dump(struct cbtree *t);

char *cbtree_next(struct cbtree *t, const char *u, intptr_t *data);

#endif


text:
package org.scalawiki.wlx

import org.scalawiki.util.TestUtils.resourceAsString
import org.scalawiki.wlx.dto.Contest
import org.specs2.mutable.Specification

class RegionFixerSpec extends Specification {
  val contest: Contest = Contest.WLMUkraine(2019)
  val country = contest.country
  val listConfig = contest.uploadConfigs.head.listConfig

  "fixer" should {

    "get all regions" in {
      val updater = new RegionFixerUpdater(new MonumentDB(contest, Nil))
      updater.raions.size === 490
    }

    "fix region 1" in {
      val wiki = resourceAsString("/org/scalawiki/wlx/region_to_fix.wiki")

      val parser = new WlxTemplateParser(listConfig, "Вікіпедія:Вікі любить пам'ятки/Житомирська область/Новоград-Волинський район")
      val monuments = parser.parse(wiki).toSeq
      val updater = new RegionFixerUpdater(new MonumentDB(contest, monuments))

      val canBeFixed = monuments.filter(updater.needsUpdate)

      canBeFixed.size === 123
    }

    "fix region 2" in {
      val wiki = resourceAsString("/org/scalawiki/wlx/region_to_fix_2.wiki")

      val parser = new WlxTemplateParser(listConfig, "Вікіпедія:Вікі любить пам'ятки/Донецька область/Мангушський район")
      val monuments = parser.parse(wiki).toSeq
      val updater = new RegionFixerUpdater(new MonumentDB(contest, monuments))

      val canBeFixed = monuments.filter(updater.needsUpdate)

      canBeFixed.size === 12
    }

    "fix region 3" in {
      val wiki = resourceAsString("/org/scalawiki/wlx/region_to_fix_3.wiki")

      val parser = new WlxTemplateParser(listConfig, "Вікіпедія:Вікі любить пам'ятки/Сумська область/Білопільський район")
      val monuments = parser.parse(wiki).toSeq
      val updater = new RegionFixerUpdater(new MonumentDB(contest, monuments))

      val canBeFixed = monuments.filter(updater.needsUpdate)
      canBeFixed.size === 12
    }
  }
}


text:
<!DOCTYPE html>
<script>
  const channel = new MessageChannel();
  window.parent.postMessage(channel.port2, '*', [channel.port2]);
  channel.port1.onmessage = e => { alert(e.data); channel.port1.postMessage("message event received") };
  channel.port1.onmessageerror = () => channel.port1.postMessage("messageerror event received");
</script>