text:
/**
 * Created by Minh Hoang DANG on 05/05/2017.
 */

var size = 300;
//var sizeLng = 237, sizeTime = size, sizeLat = 235;
//var sizeLng = 311, sizeTime = size, sizeLat = 245;
var sizeLng = 310, sizeTime = size, sizeLat = 244;
var newSizeZ = sizeLng, newSizeY = sizeTime, newSizeX = sizeLat;
var step = 50;
var mapScaleOffsetX = sizeLng/237, mapScaleOffsetY = sizeLat/235;
var processedData = [], dataChunks = [], selectedChunk = 0, chunkSize = 1000;
var fileName = 'gistar_output_b';

// Beginning of time 1st January 2015, 0:00:00 (year, month, day, hour, minute, seconds)
var TIME_GENESIS = new Date(2015, 0, 1, 0, 0, 0);
console.log(TIME_GENESIS.toDateString());

var TIME_STEP_LOWER_BOUND, TIME_STEP_UPPER_BOUND, ZSCORE_LOWER_BOUND, ZSCORE_UPPER_BOUND, ZSCORE_SCALE, X_LOWER_BOUND, X_UPPER_BOUND, Y_LOWER_BOUND, Y_UPPER_BOUND;
var xLowerBound, xUpperBound, yLowerBound, yUpperBound, timeStepLowerBound, timeStepUpperBound, zScoreLowerBound, zScoreUpperBound;

var CSVLoader = new THREE.FileLoader();
reloadData();

var stats, camera, controls, WebGLRenderer, cssRenderer;
var WebGLScene = new THREE.Scene();
var cssScene = new THREE.Scene();
var raycaster = new THREE.Raycaster();

var mouse = new THREE.Vector2(), INTERSECTED;
var CUnitCluster = new THREE.Object3D();
//var tooltipContext, tooltipTex, spriteToolTip;
var zoomAmount = 1;
var zoomFactor = 5;
var isLMB = false, isRMB = false;

var dimensionX = sizeLat/newSizeX;
var dimensionY = sizeTime/newSizeY;
var dimensionZ = sizeLng/newSizeZ;

// Offset along axis X, Z, Y
var offsetZ = (-sizeLat + dimensionX)/2;
var offsetX = (sizeLng - dimensionZ)/2 ;
var offsetY = (sizeTime - dimensionY)/2;

var mapMesh, mapMat, mapLayer;

var extrudeLayer = -1, mustExtrude = false, mustScale = false;

// Base plane (O - Lat - Lng)
var baseOXYGridHelper = createDynamicGridHelper(sizeLat, sizeLng, newSizeX, newSizeZ);
baseOXYGridHelper.position.z = 0;
baseOXYGridHelper.position.x = 0;
baseOXYGridHelper.position.y = -sizeTime/2;

// Plane along Longitude axis (O - Time - Lng)
var baseOYZGridHelper = createDynamicGridHelper(sizeLng, sizeTime, newSizeZ, newSizeY);
baseOYZGridHelper.rotation.z = (Math.PI/2);
baseOYZGridHelper.rotation.y = (Math.PI/2);
baseOYZGridHelper.position.x = baseOXYGridHelper.position.x ;
baseOYZGridHelper.position.z = baseOXYGridHelper.position.z + sizeLat/2;
baseOYZGridHelper.position.y = baseOXYGridHelper.position.y + sizeTime/2;

// Plane along Latitude axis (O - Time - Lat)
var baseOXZGridHelper = createDynamicGridHelper(sizeLat, sizeTime, newSizeX, newSizeY);
baseOXZGridHelper.rotation.z = (Math.PI/2);
baseOXZGridHelper.position.x = baseOXYGridHelper.position.x - sizeLng/2;
baseOXZGridHelper.position.z = baseOXYGridHelper.position.z;
baseOXZGridHelper.position.y = baseOXYGridHelper.position.y + sizeTime/2;

var GEO_PRISM = new THREE.CylinderGeometry(dimensionX, dimensionZ, dimensionY, 6, 4);
var GEO_CUBE = new THREE.BoxGeometry(dimensionX, dimensionY, dimensionZ);
var BRUSH_SIZE = 1;

var CAMERA_SPAWN = new THREE.Vector3(size, size, size);

var LABEL_ORIGIN_SPAWN = new THREE.Vector3( baseOXYGridHelper.position.x - (size - sizeLng/2), baseOXYGridHelper.position.y, baseOXYGridHelper.position.z + (size - sizeLat/2));
var LABEL_TIME_SPAWN = new THREE.Vector3( baseOXZGridHelper.position.x, baseOXZGridHelper.position.y + (size - sizeTime/2), baseOXZGridHelper.position.z + (size - sizeLat/2) );
var LABEL_LAT_SPAWN = new THREE.Vector3( baseOXYGridHelper.position.x - (size - sizeLng/2), baseOXYGridHelper.position.y - size*0.1, - baseOXYGridHelper.position.z - (size - sizeLat/2) );
var LABEL_LNG_SPAWN = new THREE.Vector3( baseOXYGridHelper.position.x + (size - sizeLng/2), baseOXYGridHelper.position.y - size*0.1, baseOXYGridHelper.position.z + (size - sizeLat/2) );

var labelOrigin, labelT, labelLng, labelLat;

// Embed layer from OpenStreet Map

var zoom = 13;
var LNG_MIN = -74.25909, LNG_MAX = -73.70009, LAT_MIN = 40.477399, LAT_MAX = 40.917577;
var newLngMin = LNG_MIN, newLatMin = LAT_MIN, newLngMax = LNG_MAX, newLatMax = LAT_MAX;

var LENGTH_DEG_LAT = getDistanceBetweenCoordinates(LAT_MIN, LAT_MAX, LNG_MIN, LNG_MIN);
var LENGTH_DEG_LNG = getDistanceBetweenCoordinates(LAT_MIN, LAT_MIN, LNG_MIN, LNG_MAX);
var CELL_DISTANCE_LAT = LENGTH_DEG_LAT / sizeLat;
var CELL_DISTANCE_LNG = LENGTH_DEG_LNG / sizeLng;

console.log(CELL_DISTANCE_LAT);
console.log(CELL_DISTANCE_LNG);

var loc = encodeURIComponent(`${LNG_MIN},${LAT_MIN},${LNG_MAX},${LAT_MAX}`);

// A empty div is added in front of it to prevent users from interacting with the cube
var OSMFrame='

'+
    '

'+
    `<iframe id="OSMLayer" width="${661}px" height="${689}px" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" ` +
    `src="https://www.openstreetmap.org/export/embed.html?bbox=LOCATION&layers=MAPTYPE" ` +
    'style="border: 1px solid black">' +
    '

';

// Choose between roadmap, satellite, hybrid or terrain
var mapoption = '';
var maptype = 'mapnik' + mapoption;
var markers = encodeURIComponent(`${LAT_MIN},${LNG_MIN}`);
var sides = [];

// Camera types
var isInPerspectiveMode = true;

var combinedCamera = new THREE.CombinedCamera(window.innerWidth, window.innerHeight, 90, 1, 1000, -500, 1000);
combinedCamera.isPerspectiveCamera = true;
combinedCamera.isOrthographicCamera = false;
combinedCamera.position.copy(CAMERA_SPAWN);
combinedCamera.lookAt(new THREE.Vector3(sizeLng/2, sizeTime/2, sizeLat/2));

var perspectiveCamera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 5000 );
perspectiveCamera.position.set( 500, 350, 750 );


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using ArchiSteamFarm.Core;
using JetBrains.Annotations;
using SteamKit2;
using SteamKit2.Internal;

namespace ArchiSteamFarm.Steam.Integration.Callbacks;

public sealed class PurchaseResponseCallback : CallbackMsg {
	[PublicAPI]
	public Dictionary<uint, string>? Items { get; }

	public EPurchaseResultDetail PurchaseResultDetail { get; internal set; }

	[PublicAPI]
	public EResult Result { get; internal set; }

	internal PurchaseResponseCallback(EResult result, EPurchaseResultDetail purchaseResult) {
		if (!Enum.IsDefined(typeof(EResult), result)) {
			throw new InvalidEnumArgumentException(nameof(result), (int) result, typeof(EResult));
		}

		if (!Enum.IsDefined(typeof(EPurchaseResultDetail), purchaseResult)) {
			throw new InvalidEnumArgumentException(nameof(purchaseResult), (int) purchaseResult, typeof(EPurchaseResultDetail));
		}

		Result = result;
		PurchaseResultDetail = purchaseResult;
	}

	internal PurchaseResponseCallback(JobID jobID, CMsgClientPurchaseResponse msg) {
		if (jobID == null) {
			throw new ArgumentNullException(nameof(jobID));
		}

		if (msg == null) {
			throw new ArgumentNullException(nameof(msg));
		}

		JobID = jobID;
		PurchaseResultDetail = (EPurchaseResultDetail) msg.purchase_result_details;
		Result = (EResult) msg.eresult;

		if (msg.purchase_receipt_info == null) {
			ASF.ArchiLogger.LogNullError(nameof(msg.purchase_receipt_info));

			return;
		}

		KeyValue receiptInfo = new();

		using (MemoryStream ms = new(msg.purchase_receipt_info)) {
			if (!receiptInfo.TryReadAsBinary(ms)) {
				ASF.ArchiLogger.LogNullError(nameof(ms));

				return;
			}
		}

		List<KeyValue> lineItems = receiptInfo["lineitems"].Children;

		if (lineItems.Count == 0) {
			return;
		}

		Items = new Dictionary<uint, string>(lineItems.Count);

		foreach (KeyValue lineItem in lineItems) {
			uint packageID = lineItem["PackageID"].AsUnsignedInteger();

			if (packageID == 0) {
				// Coupons have PackageID of -1 (don't ask me why)
				// We'll use ItemAppID in this case
				packageID = lineItem["ItemAppID"].AsUnsignedInteger();

				if (packageID == 0) {
					ASF.ArchiLogger.LogNullError(nameof(packageID));

					return;
				}
			}

			string? gameName = lineItem["ItemDescription"].AsString();

			if (string.IsNullOrEmpty(gameName)) {
				ASF.ArchiLogger.LogNullError(nameof(gameName));

				return;
			}

			// Apparently steam expects client to decode sent HTML
			gameName = WebUtility.HtmlDecode(gameName);
			Items[packageID] = gameName;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import urllib.request
import os
import locale
import platform

import pytest
import numpy as np
from numpy.testing import assert_array_equal
import erfa

from astropy.time import Time, TimeDelta
from astropy.utils.iers import iers
from astropy.utils.data import get_pkg_data_filename
from astropy.tests.tests.test_imports import test_imports

# Import every top-level astropy module as a test that the ERFA leap second
# table is not updated for normal imports.
test_imports()

# Now test that the erfa leap_seconds table has not been updated. This must be
# done at the module level, which unfortunately will abort the entire test run
# if if fails. Running within a normal pytest test will not work because the
# other tests will end up updating this attribute by virtue of doing Time UTC
# transformations.
assert erfa.leap_seconds._expires is None

# Tests in this module assume that the erfa.leap_seconds attribute has been
# updated from the `erfa` package built-in table to the astropy built-in
# leap-second table. That has the effect of ensuring that the
# `erfa.leap_seconds.expires` property is sufficiently in the future.
iers_table = iers.LeapSeconds.auto_open()
erfa.leap_seconds.update(iers_table)
assert erfa.leap_seconds._expires is not None

SYSTEM_FILE = '/usr/share/zoneinfo/leap-seconds.list'

# Test leap_seconds.list in test/data.
LEAP_SECOND_LIST = get_pkg_data_filename('data/leap-seconds.list')

def test_configuration():
    # This test just ensures things stay consistent.
    # Adjust if changes are made.
    assert iers.conf.iers_leap_second_auto_url == iers.IERS_LEAP_SECOND_URL
    assert iers.conf.ietf_leap_second_auto_url == iers.IETF_LEAP_SECOND_URL

class TestReading:
    """Basic tests that leap seconds can be read."""

    def verify_day_month_year(self, ls):
        assert np.all(ls['day'] == 1)
        assert np.all((ls['month'] == 1) | (ls['month'] == 7) |
                      (ls['year'] < 1970))
        assert np.all(ls['year'] >= 1960)
        t = Time({'year': ls['year'], 'month': ls['month'], 'day': ls['day']},
                 format='ymdhms')
        assert np.all(t == Time(ls['mjd'], format='mjd'))

    def test_read_leap_second_dat(self):
        ls = iers.LeapSeconds.from_iers_leap_seconds(
            iers.IERS_LEAP_SECOND_FILE)
        # Below, >= to take into account we might ship and updated file.
        assert ls.expires >= Time('2020-06-28', scale='tai')
        assert ls['mjd'][0] == 41317
        assert ls['tai_utc'][0] == 10
        assert ls['mjd'][-1] >= 57754
        assert ls['tai_utc'][-1] >= 37
        self.verify_day_month_year(ls)

    def test_read_leap_second_dat_locale(self):
        current = locale.setlocale(locale.LC_ALL)
        try:
            if platform.system() == 'Darwin':
                locale.setlocale(locale.LC_ALL, 'fr_FR')
            else:
                locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')

            ls = iers.LeapSeconds.from_iers_leap_seconds(
                iers.IERS_LEAP_SECOND_FILE)
        except locale.Error as e:
            pytest.skip(f'Locale error: {e}')
        finally:
            locale.setlocale(locale.LC_ALL, current)

        # Below, >= to take into account we might ship and updated file.
        assert ls.expires >= Time('2020-06-28', scale='tai')

    def test_open_leap_second_dat(self):
        ls = iers.LeapSeconds.from_iers_leap_seconds(
            iers.IERS_LEAP_SECOND_FILE)
        ls2 = iers.LeapSeconds.open(iers.IERS_LEAP_SECOND_FILE)
        assert np.all(ls == ls2)

    @pytest.mark.parametrize('file', (
        LEAP_SECOND_LIST,
        "file:" + urllib.request.pathname2url(LEAP_SECOND_LIST)))
    def test_read_leap_seconds_list(self, file):
        ls = iers.LeapSeconds.from_leap_seconds_list(file)
        assert ls.expires == Time('2020-06-28', scale='tai')
        assert ls['mjd'][0] == 41317
        assert ls['tai_utc'][0] == 10
        assert ls['mjd'][-1] == 57754
        assert ls['tai_utc'][-1] == 37
        self.verify_day_month_year(ls)

    @pytest.mark.parametrize('file', (
        LEAP_SECOND_LIST,
        "file:" + urllib.request.pathname2url(LEAP_SECOND_LIST)))
    def test_open_leap_seconds_list(self, file):
        ls = iers.LeapSeconds.from_leap_seconds_list(file)
        ls2 = iers.LeapSeconds.open(file)
        assert np.all(ls == ls2)

    @pytest.mark.skipif(not os.path.isfile(SYSTEM_FILE),
                        reason=f'system does not have {SYSTEM_FILE}')
    def test_open_system_file(self):
        ls = iers.LeapSeconds.open(SYSTEM_FILE)
        expired = ls.expires < Time.now()
        if expired:
            pytest.skip("System leap second file is expired.")
        assert not expired

def make_fake_file(expiration, tmpdir):
    """copy the built-in IERS file but set a different expiration date."""
    ls = iers.LeapSeconds.from_iers_leap_seconds()
    fake_file = str(tmpdir.join('fake_leap_seconds.dat'))
    with open(fake_file, 'w') as fh:
        fh.write('\n'.join([f'#  File expires on {expiration}']
                           + str(ls).split('\n')[2:-1]))
        return fake_file

def test_fake_file(tmpdir):
    fake_file = make_fake_file('28 June 2345', tmpdir)
    fake = iers.LeapSeconds.from_iers_leap_seconds(fake_file)
    assert fake.expires == Time('2345-06-28', scale='tai')

class TestAutoOpenExplicitLists:
    # For this set of tests, leap-seconds are allowed to be expired
    # except as explicitly tested.
    @pytest.mark.filterwarnings(iers.IERSStaleWarning)
    def test_auto_open_simple(self):
        ls = iers.LeapSeconds.auto_open([iers.IERS_LEAP_SECOND_FILE])
        assert ls.meta['data_url'] == iers.IERS_LEAP_SECOND_FILE

    @pytest.mark.filterwarnings(iers.IERSStaleWarning)
    def test_auto_open_erfa(self):
        ls = iers.LeapSeconds.auto_open(['erfa', iers.IERS_LEAP_SECOND_FILE])
        assert ls.meta['data_url'] in ['erfa', iers.IERS_LEAP_SECOND_FILE]

    @pytest.mark.filterwarnings(iers.IERSStaleWarning)
    def test_fake_future_file(self, tmpdir):
        fake_file = make_fake_file('28 June 2345', tmpdir)
        # Try as system file for auto_open, setting auto_max_age such
        # that any ERFA or system files are guaranteed to be expired,
        # while the fake file is guaranteed to be OK.
        with iers.conf.set_temp('auto_max_age', -100000):
            ls = iers.LeapSeconds.auto_open([
                'erfa', iers.IERS_LEAP_SECOND_FILE, fake_file])
            assert ls.expires == Time('2345-06-28', scale='tai')
            assert ls.meta['data_url'] == str(fake_file)
            # And as URL
            fake_url = "file:" + urllib.request.pathname2url(fake_file)
            ls2 = iers.LeapSeconds.auto_open([
                'erfa', iers.IERS_LEAP_SECOND_FILE, fake_url])
            assert ls2.expires == Time('2345-06-28', scale='tai')
            assert ls2.meta['data_url'] == str(fake_url)

    def test_fake_expired_file(self, tmpdir):
        fake_file1 = make_fake_file('28 June 2010', tmpdir)
        fake_file2 = make_fake_file('27 June 2012', tmpdir)
        # Between these and the built-in one, the built-in file is best.
        ls = iers.LeapSeconds.auto_open([fake_file1, fake_file2,
                                         iers.IERS_LEAP_SECOND_FILE])
        assert ls.meta['data_url'] == iers.IERS_LEAP_SECOND_FILE

        # But if we remove the built-in one, the least expired one will be
        # used and we get a warning that it is stale.
        with pytest.warns(iers.IERSStaleWarning):
            ls2 = iers.LeapSeconds.auto_open([fake_file1, fake_file2])
        assert ls2.meta['data_url'] == fake_file2
        assert ls2.expires == Time('2012-06-27', scale='tai')

        # Use the fake files to make sure auto_max_age is safe.
        # Should have no warning in either example.
        with iers.conf.set_temp('auto_max_age', None):
            ls3 = iers.LeapSeconds.auto_open([fake_file1,
                                              iers.IERS_LEAP_SECOND_FILE])
        assert ls3.meta['data_url'] == iers.IERS_LEAP_SECOND_FILE
        with iers.conf.set_temp('auto_max_age', None):
            ls4 = iers.LeapSeconds.auto_open([fake_file1, fake_file2])
        assert ls4.meta['data_url'] == fake_file2

@pytest.mark.remote_data
class TestRemoteURLs:
    def setup_class(cls):
        # Need auto_download so that IERS_B won't be loaded and cause tests to
        # fail.
        iers.conf.auto_download = True

    def teardown_class(cls):
        # This setting is to be consistent with astropy/conftest.py
        iers.conf.auto_download = False

    # In these tests, the results may be cached.
    # This is fine - no need to download again.
    def test_iers_url(self):
        ls = iers.LeapSeconds.auto_open([iers.IERS_LEAP_SECOND_URL])
        assert ls.expires > Time.now()

    def test_ietf_url(self):
        ls = iers.LeapSeconds.auto_open([iers.IETF_LEAP_SECOND_URL])
        assert ls.expires > Time.now()

class TestDefaultAutoOpen:
    """Test auto_open with different _auto_open_files."""
    def setup(self):
        # Identical to what is used in LeapSeconds.auto_open().
        self.good_enough = (iers.LeapSeconds._today()
                            + TimeDelta(180 - iers._none_to_float(iers.conf.auto_max_age),
                                        format='jd'))
        self._auto_open_files = iers.LeapSeconds._auto_open_files.copy()

    def teardown(self):
        iers.LeapSeconds._auto_open_files = self._auto_open_files

    def remove_auto_open_files(self, *files):
        """Remove some files from the auto-opener.

        The default set is restored in teardown.
        """
        for f in files:
            iers.LeapSeconds._auto_open_files.remove(f)

    def test_erfa_found(self):
        # Set huge maximum age such that whatever ERFA has is OK.
        # Since it is checked first, it should thus be found.
        with iers.conf.set_temp('auto_max_age', 100000):
            ls = iers.LeapSeconds.open()
        assert ls.meta['data_url'] == 'erfa'

    def test_builtin_found(self):
        # Set huge maximum age such that built-in file is always OK.
        # If we remove 'erfa', it should thus be found.
        self.remove_auto_open_files('erfa')
        with iers.conf.set_temp('auto_max_age', 100000):
            ls = iers.LeapSeconds.open()
        assert ls.meta['data_url'] == iers.IERS_LEAP_SECOND_FILE

    # The test below is marked remote_data only to ensure it runs
    # as an allowed-fail job on CI: i.e., we will notice it (eventually)
    # but will not be misled in thinking that a PR is bad.
    @pytest.mark.remote_data
    def test_builtin_not_expired(self):
        # TODO: would be nice to have automatic PRs for this!
        ls = iers.LeapSeconds.open(iers.IERS_LEAP_SECOND_FILE)
        assert ls.expires > self.good_enough, (
            "The leap second file built in to astropy is expired. Fix with:\n"
            "cd astropy/utils/iers/data/; . update_builtin_iers.sh\n"
            "and commit as a PR (for details, see release procedure).")

    def test_fake_future_file(self, tmpdir):
        fake_file = make_fake_file('28 June 2345', tmpdir)
        # Try as system file for auto_open, setting auto_max_age such
        # that any ERFA or system files are guaranteed to be expired.
        with iers.conf.set_temp('auto_max_age', -100000), \
                iers.conf.set_temp('system_leap_second_file', fake_file):
            ls = iers.LeapSeconds.open()
        assert ls.expires == Time('2345-06-28', scale='tai')
        assert ls.meta['data_url'] == str(fake_file)
        # And as URL
        fake_url = "file:" + urllib.request.pathname2url(fake_file)
        with iers.conf.set_temp('auto_max_age', -100000), \
                iers.conf.set_temp('iers_leap_second_auto_url', fake_url):
            ls2 = iers.LeapSeconds.open()
        assert ls2.expires == Time('2345-06-28', scale='tai')
        assert ls2.meta['data_url'] == str(fake_url)

    def test_fake_expired_file(self, tmpdir):
        self.remove_auto_open_files('erfa', 'iers_leap_second_auto_url',
                                    'ietf_leap_second_auto_url')
        fake_file = make_fake_file('28 June 2010', tmpdir)
        with iers.conf.set_temp('system_leap_second_file', fake_file):
            # If we try this directly, the built-in file will be found.
            ls = iers.LeapSeconds.open()
            assert ls.meta['data_url'] == iers.IERS_LEAP_SECOND_FILE

            # But if we remove the built-in one, the expired one will be
            # used and we get a warning that it is stale.
            self.remove_auto_open_files(iers.IERS_LEAP_SECOND_FILE)
            with pytest.warns(iers.IERSStaleWarning):
                ls2 = iers.LeapSeconds.open()
            assert ls2.meta['data_url'] == fake_file
            assert ls2.expires == Time('2010-06-28', scale='tai')

    @pytest.mark.skipif(not os.path.isfile(SYSTEM_FILE),
                        reason=f'system does not have {SYSTEM_FILE}')
    def test_system_file_used_if_not_expired(self, tmpdir):
        # We skip the test if the system file is on a CI and is expired -
        # we should not depend on CI keeping it up to date, but if it is,
        # we should check that it is used if possible.
        if (iers.LeapSeconds.open(SYSTEM_FILE).expires <= self.good_enough):
            pytest.skip("System leap second file is expired.")

        self.remove_auto_open_files('erfa')
        with iers.conf.set_temp('system_leap_second_file', SYSTEM_FILE):
            ls = iers.LeapSeconds.open()
            assert ls.expires > self.good_enough
            assert ls.meta['data_url'] in (iers.IERS_LEAP_SECOND_FILE,
                                           SYSTEM_FILE)

            # Also check with a "built-in" file that is expired
            fake_file = make_fake_file('28 June 2017', tmpdir)
            iers.LeapSeconds._auto_open_files[0] = fake_file
            ls2 = iers.LeapSeconds.open()
            assert ls2.expires > Time.now()
            assert ls2.meta['data_url'] == SYSTEM_FILE

    @pytest.mark.remote_data
    def test_auto_open_urls_always_good_enough(self):
        # Avoid using the erfa, built-in and system files, as they might
        # be good enough already.
        try:
            # Need auto_download so that IERS_B won't be loaded and
            # cause tests to fail.
            iers.conf.auto_download = True

            self.remove_auto_open_files('erfa', iers.IERS_LEAP_SECOND_FILE,
                                        'system_leap_second_file')
            ls = iers.LeapSeconds.open()
            assert ls.expires > self.good_enough
            assert ls.meta['data_url'].startswith('http')
        finally:
            # This setting is to be consistent with astropy/conftest.py
            iers.conf.auto_download = False

class ERFALeapSecondsSafe:
    """Base class for tests that change the ERFA leap-second tables.

    It ensures the original state is restored.
    """
    def setup(self):
        # Keep current leap-second table and expiration.
        self.erfa_ls = self._erfa_ls = erfa.leap_seconds.get()
        self.erfa_expires = self._expires = erfa.leap_seconds._expires

    def teardown(self):
        # Restore leap-second table and expiration.
        erfa.leap_seconds.set(self.erfa_ls)
        erfa.leap_seconds._expires = self._expires

class TestFromERFA(ERFALeapSecondsSafe):
    def test_get_erfa_ls(self):
        ls = iers.LeapSeconds.from_erfa()
        assert ls.colnames == ['year', 'month', 'tai_utc']
        assert isinstance(ls.expires, Time)
        assert ls.expires == self.erfa_expires
        ls_array = np.array(ls['year', 'month', 'tai_utc'])
        assert np.all(ls_array == self.erfa_ls)

    def test_get_built_in_erfa_ls(self):
        ls = iers.LeapSeconds.from_erfa(built_in=True)
        assert ls.colnames == ['year', 'month', 'tai_utc']
        assert isinstance(ls.expires, Time)
        ls_array = np.array(ls['year', 'month', 'tai_utc'])
        assert np.all(ls_array == self.erfa_ls[:len(ls_array)])

    def test_get_modified_erfa_ls(self):
        erfa.leap_seconds.set(self.erfa_ls[:-10])
        ls = iers.LeapSeconds.from_erfa()
        assert len(ls) == len(self.erfa_ls)-10
        ls_array = np.array(ls['year', 'month', 'tai_utc'])
        assert np.all(ls_array == self.erfa_ls[:-10])
        ls2 = iers.LeapSeconds.from_erfa(built_in=True)
        assert len(ls2) > len(ls)
        erfa.leap_seconds.set(None)
        erfa_built_in = erfa.leap_seconds.get()
        assert len(ls2) == len(erfa_built_in)
        ls2_array = np.array(ls2['year', 'month', 'tai_utc'])
        assert np.all(ls2_array == erfa_built_in)

    def test_open(self):
        ls = iers.LeapSeconds.open('erfa')
        assert isinstance(ls.expires, Time)
        assert ls.expires == self.erfa_expires
        ls_array = np.array(ls['year', 'month', 'tai_utc'])
        assert np.all(ls_array == self.erfa_ls)

class TestUpdateLeapSeconds(ERFALeapSecondsSafe):
    def setup(self):
        super().setup()
        # Read default leap second table.
        self.ls = iers.LeapSeconds.from_iers_leap_seconds()
        # For tests, reset ERFA table to built-in default.
        erfa.leap_seconds.set()
        self.erfa_ls = erfa.leap_seconds.get()

    def test_built_in_up_to_date(self):
        """Leap second should match between built-in and ERFA."""
        erfa_since_1970 = self.erfa_ls[self.erfa_ls['year'] > 1970]
        assert len(self.ls) >= len(erfa_since_1970), \
            "built-in leap seconds out of date"
        assert len(self.ls) <= len(erfa_since_1970), \
            "ERFA leap seconds out of date"
        overlap = np.array(self.ls['year', 'month', 'tai_utc'])
        assert np.all(overlap == erfa_since_1970.astype(overlap.dtype))

    def test_update_with_built_in(self):
        """An update with built-in should not do anything."""
        n_update = self.ls.update_erfa_leap_seconds()
        assert n_update == 0
        new_erfa_ls = erfa.leap_seconds.get()
        assert np.all(new_erfa_ls == self.erfa_ls)

    @pytest.mark.parametrize('n_short', (1, 3))
    def test_update(self, n_short):
        """Check whether we can recover removed leap seconds."""
        erfa.leap_seconds.set(self.erfa_ls[:-n_short])
        n_update = self.ls.update_erfa_leap_seconds()
        assert n_update == n_short
        new_erfa_ls = erfa.leap_seconds.get()
        assert_array_equal(new_erfa_ls, self.erfa_ls)
        # Check that a second update does not do anything.
        n_update2 = self.ls.update_erfa_leap_seconds()
        assert n_update2 == 0
        new_erfa_ls2 = erfa.leap_seconds.get()
        assert_array_equal(new_erfa_ls2, self.erfa_ls)

    def test_update_initialize_erfa(self):
        # With pre-initialization, update does nothing.
        erfa.leap_seconds.set(self.erfa_ls[:-2])
        n_update = self.ls.update_erfa_leap_seconds(initialize_erfa=True)
        assert n_update == 0
        new_erfa_ls = erfa.leap_seconds.get()
        assert_array_equal(new_erfa_ls, self.erfa_ls)

    def test_update_overwrite(self):
        n_update = self.ls.update_erfa_leap_seconds(initialize_erfa='empty')
        assert n_update == len(self.ls)
        new_erfa_ls = erfa.leap_seconds.get()
        assert new_erfa_ls['year'].min() > 1970
        n_update2 = self.ls.update_erfa_leap_seconds()
        assert n_update2 == 0
        new_erfa_ls2 = erfa.leap_seconds.get()
        assert_array_equal(new_erfa_ls2, new_erfa_ls)
        n_update3 = self.ls.update_erfa_leap_seconds(initialize_erfa=True)
        assert n_update3 == 0
        new_erfa_ls3 = erfa.leap_seconds.get()
        assert_array_equal(new_erfa_ls3, self.erfa_ls)

    def test_bad_jump(self):
        erfa.leap_seconds.set(self.erfa_ls[:-2])
        bad = self.ls.copy()
        bad['tai_utc'][-1] = 5
        with pytest.raises(ValueError, match='jump'):
            bad.update_erfa_leap_seconds()
        # With an error the ERFA table should not change.
        assert_array_equal(erfa.leap_seconds.get(), self.erfa_ls[:-2])

        # Unless we initialized it beforehand.
        with pytest.raises(ValueError, match='jump'):
            bad.update_erfa_leap_seconds(initialize_erfa=True)
        assert_array_equal(erfa.leap_seconds.get(), self.erfa_ls)

        # Of course, we get no errors if we initialize only.
        erfa.leap_seconds.set(self.erfa_ls[:-2])
        n_update = bad.update_erfa_leap_seconds(initialize_erfa='only')
        assert n_update == 0
        new_erfa_ls = erfa.leap_seconds.get()
        assert_array_equal(new_erfa_ls, self.erfa_ls)

    def test_bad_day(self):
        erfa.leap_seconds.set(self.erfa_ls[:-2])
        bad = self.ls.copy()
        bad['day'][-1] = 5
        with pytest.raises(ValueError, match='not on 1st'):
            bad.update_erfa_leap_seconds()

    def test_bad_month(self):
        erfa.leap_seconds.set(self.erfa_ls[:-2])
        bad = self.ls.copy()
        bad['month'][-1] = 5
        with pytest.raises(ValueError, match='January'):
            bad.update_erfa_leap_seconds()
        assert_array_equal(erfa.leap_seconds.get(), self.erfa_ls[:-2])


text:
layout: tag
title: scala
tag: scala
---


text:
package org.apache.felix.upnp.sample.tv;
import java.io.IOException;
import java.io.InputStream;

import org.osgi.service.upnp.UPnPIcon;

public class TvIcon implements UPnPIcon {

	/* (non-Javadoc)
	 * @see org.osgi.service.upnp.UPnPIcon#getMimeType()
	 */
	public String getMimeType() {
		return "image/gif";
	}

	/* (non-Javadoc)
	 * @see org.osgi.service.upnp.UPnPIcon#getWidth()
	 */
	public int getWidth() {
		return 32;
	}

	/* (non-Javadoc)
	 * @see org.osgi.service.upnp.UPnPIcon#getHeight()
	 */
	public int getHeight() {
		return 32;
	}

	/* (non-Javadoc)
	 * @see org.osgi.service.upnp.UPnPIcon#getSize()
	 */
	public int getSize() {
		return 0;
	}

	/* (non-Javadoc)
	 * @see org.osgi.service.upnp.UPnPIcon#getDepth()
	 */
	public int getDepth() {
		return 16;
	}

	/* (non-Javadoc)
	 * @see org.osgi.service.upnp.UPnPIcon#getInputStream()
	 */
	public InputStream getInputStream() throws IOException {
		return TvIcon.class.getResourceAsStream("images/tv.gif");
	}
}


text:
namespace Dropbox.Api.FileProperties
{
    using sys = System;
    using col = System.Collections.Generic;
    using re = System.Text.RegularExpressions;

    using enc = Dropbox.Api.Stone;

    /// <summary>
    /// <para>The invalid property group error object</para>
    /// </summary>
    public class InvalidPropertyGroupError
    {
        #pragma warning disable 108

        /// <summary>
        /// <para>The encoder instance.</para>
        /// </summary>
        internal static enc.StructEncoder<InvalidPropertyGroupError> Encoder = new InvalidPropertyGroupErrorEncoder();

        /// <summary>
        /// <para>The decoder instance.</para>
        /// </summary>
        internal static enc.StructDecoder<InvalidPropertyGroupError> Decoder = new InvalidPropertyGroupErrorDecoder();

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="InvalidPropertyGroupError" />
        /// class.</para>
        /// </summary>
        public InvalidPropertyGroupError()
        {
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is PropertyFieldTooLarge</para>
        /// </summary>
        public bool IsPropertyFieldTooLarge
        {
            get
            {
                return this is PropertyFieldTooLarge;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a PropertyFieldTooLarge, or <c>null</c>.</para>
        /// </summary>
        public PropertyFieldTooLarge AsPropertyFieldTooLarge
        {
            get
            {
                return this as PropertyFieldTooLarge;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is DoesNotFitTemplate</para>
        /// </summary>
        public bool IsDoesNotFitTemplate
        {
            get
            {
                return this is DoesNotFitTemplate;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a DoesNotFitTemplate, or <c>null</c>.</para>
        /// </summary>
        public DoesNotFitTemplate AsDoesNotFitTemplate
        {
            get
            {
                return this as DoesNotFitTemplate;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is
        /// DuplicatePropertyGroups</para>
        /// </summary>
        public bool IsDuplicatePropertyGroups
        {
            get
            {
                return this is DuplicatePropertyGroups;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a DuplicatePropertyGroups, or <c>null</c>.</para>
        /// </summary>
        public DuplicatePropertyGroups AsDuplicatePropertyGroups
        {
            get
            {
                return this as DuplicatePropertyGroups;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is Path</para>
        /// </summary>
        public bool IsPath
        {
            get
            {
                return this is Path;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a Path, or <c>null</c>.</para>
        /// </summary>
        public Path AsPath
        {
            get
            {
                return this as Path;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is UnsupportedFolder</para>
        /// </summary>
        public bool IsUnsupportedFolder
        {
            get
            {
                return this is UnsupportedFolder;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a UnsupportedFolder, or <c>null</c>.</para>
        /// </summary>
        public UnsupportedFolder AsUnsupportedFolder
        {
            get
            {
                return this as UnsupportedFolder;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is TemplateNotFound</para>
        /// </summary>
        public bool IsTemplateNotFound
        {
            get
            {
                return this is TemplateNotFound;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a TemplateNotFound, or <c>null</c>.</para>
        /// </summary>
        public TemplateNotFound AsTemplateNotFound
        {
            get
            {
                return this as TemplateNotFound;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is RestrictedContent</para>
        /// </summary>
        public bool IsRestrictedContent
        {
            get
            {
                return this is RestrictedContent;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a RestrictedContent, or <c>null</c>.</para>
        /// </summary>
        public RestrictedContent AsRestrictedContent
        {
            get
            {
                return this as RestrictedContent;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is Other</para>
        /// </summary>
        public bool IsOther
        {
            get
            {
                return this is Other;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a Other, or <c>null</c>.</para>
        /// </summary>
        public Other AsOther
        {
            get
            {
                return this as Other;
            }
        }

        #region Encoder class

        /// <summary>
        /// <para>Encoder for  <see cref="InvalidPropertyGroupError" />.</para>
        /// </summary>
        private class InvalidPropertyGroupErrorEncoder : enc.StructEncoder<InvalidPropertyGroupError>
        {
            /// <summary>
            /// <para>Encode fields of given value.</para>
            /// </summary>
            /// <param name="value">The value.</param>
            /// <param name="writer">The writer.</param>
            public override void EncodeFields(InvalidPropertyGroupError value, enc.IJsonWriter writer)
            {
                if (value is PropertyFieldTooLarge)
                {
                    WriteProperty(".tag", "property_field_too_large", writer, enc.StringEncoder.Instance);
                    PropertyFieldTooLarge.Encoder.EncodeFields((PropertyFieldTooLarge)value, writer);
                    return;
                }
                if (value is DoesNotFitTemplate)
                {
                    WriteProperty(".tag", "does_not_fit_template", writer, enc.StringEncoder.Instance);
                    DoesNotFitTemplate.Encoder.EncodeFields((DoesNotFitTemplate)value, writer);
                    return;
                }
                if (value is DuplicatePropertyGroups)
                {
                    WriteProperty(".tag", "duplicate_property_groups", writer, enc.StringEncoder.Instance);
                    DuplicatePropertyGroups.Encoder.EncodeFields((DuplicatePropertyGroups)value, writer);
                    return;
                }
                if (value is Path)
                {
                    WriteProperty(".tag", "path", writer, enc.StringEncoder.Instance);
                    Path.Encoder.EncodeFields((Path)value, writer);
                    return;
                }
                if (value is UnsupportedFolder)
                {
                    WriteProperty(".tag", "unsupported_folder", writer, enc.StringEncoder.Instance);
                    UnsupportedFolder.Encoder.EncodeFields((UnsupportedFolder)value, writer);
                    return;
                }
                if (value is TemplateNotFound)
                {
                    WriteProperty(".tag", "template_not_found", writer, enc.StringEncoder.Instance);
                    TemplateNotFound.Encoder.EncodeFields((TemplateNotFound)value, writer);
                    return;
                }
                if (value is RestrictedContent)
                {
                    WriteProperty(".tag", "restricted_content", writer, enc.StringEncoder.Instance);
                    RestrictedContent.Encoder.EncodeFields((RestrictedContent)value, writer);
                    return;
                }
                if (value is Other)
                {
                    WriteProperty(".tag", "other", writer, enc.StringEncoder.Instance);
                    Other.Encoder.EncodeFields((Other)value, writer);
                    return;
                }
                throw new sys.InvalidOperationException();
            }
        }

        #endregion

        #region Decoder class

        /// <summary>
        /// <para>Decoder for  <see cref="InvalidPropertyGroupError" />.</para>
        /// </summary>
        private class InvalidPropertyGroupErrorDecoder : enc.UnionDecoder<InvalidPropertyGroupError>
        {
            /// <summary>
            /// <para>Create a new instance of type <see cref="InvalidPropertyGroupError"
            /// />.</para>
            /// </summary>
            /// <returns>The struct instance.</returns>
            protected override InvalidPropertyGroupError Create()
            {
                return new InvalidPropertyGroupError();
            }

            /// <summary>
            /// <para>Decode based on given tag.</para>
            /// </summary>
            /// <param name="tag">The tag.</param>
            /// <param name="reader">The json reader.</param>
            /// <returns>The decoded object.</returns>
            protected override InvalidPropertyGroupError Decode(string tag, enc.IJsonReader reader)
            {
                switch (tag)
                {
                    case "property_field_too_large":
                        return PropertyFieldTooLarge.Decoder.DecodeFields(reader);
                    case "does_not_fit_template":
                        return DoesNotFitTemplate.Decoder.DecodeFields(reader);
                    case "duplicate_property_groups":
                        return DuplicatePropertyGroups.Decoder.DecodeFields(reader);
                    case "path":
                        return Path.Decoder.DecodeFields(reader);
                    case "unsupported_folder":
                        return UnsupportedFolder.Decoder.DecodeFields(reader);
                    case "template_not_found":
                        return TemplateNotFound.Decoder.DecodeFields(reader);
                    case "restricted_content":
                        return RestrictedContent.Decoder.DecodeFields(reader);
                    case "other":
                        return Other.Decoder.DecodeFields(reader);
                    default:
                        throw new sys.InvalidOperationException();
                }
            }
        }

        #endregion

        /// <summary>
        /// <para>One or more of the supplied property field values is too large.</para>
        /// </summary>
        public sealed class PropertyFieldTooLarge : InvalidPropertyGroupError
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<PropertyFieldTooLarge> Encoder = new PropertyFieldTooLargeEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<PropertyFieldTooLarge> Decoder = new PropertyFieldTooLargeDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="PropertyFieldTooLarge" />
            /// class.</para>
            /// </summary>
            private PropertyFieldTooLarge()
            {
            }

            /// <summary>
            /// <para>A singleton instance of PropertyFieldTooLarge</para>
            /// </summary>
            public static readonly PropertyFieldTooLarge Instance = new PropertyFieldTooLarge();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="PropertyFieldTooLarge" />.</para>
            /// </summary>
            private class PropertyFieldTooLargeEncoder : enc.StructEncoder<PropertyFieldTooLarge>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(PropertyFieldTooLarge value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="PropertyFieldTooLarge" />.</para>
            /// </summary>
            private class PropertyFieldTooLargeDecoder : enc.StructDecoder<PropertyFieldTooLarge>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="PropertyFieldTooLarge"
                /// />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override PropertyFieldTooLarge Create()
                {
                    return PropertyFieldTooLarge.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>One or more of the supplied property fields does not conform to the template
        /// specifications.</para>
        /// </summary>
        public sealed class DoesNotFitTemplate : InvalidPropertyGroupError
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<DoesNotFitTemplate> Encoder = new DoesNotFitTemplateEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<DoesNotFitTemplate> Decoder = new DoesNotFitTemplateDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="DoesNotFitTemplate" />
            /// class.</para>
            /// </summary>
            private DoesNotFitTemplate()
            {
            }

            /// <summary>
            /// <para>A singleton instance of DoesNotFitTemplate</para>
            /// </summary>
            public static readonly DoesNotFitTemplate Instance = new DoesNotFitTemplate();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="DoesNotFitTemplate" />.</para>
            /// </summary>
            private class DoesNotFitTemplateEncoder : enc.StructEncoder<DoesNotFitTemplate>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(DoesNotFitTemplate value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="DoesNotFitTemplate" />.</para>
            /// </summary>
            private class DoesNotFitTemplateDecoder : enc.StructDecoder<DoesNotFitTemplate>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="DoesNotFitTemplate"
                /// />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override DoesNotFitTemplate Create()
                {
                    return DoesNotFitTemplate.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>There are 2 or more property groups referring to the same templates in the
        /// input.</para>
        /// </summary>
        public sealed class DuplicatePropertyGroups : InvalidPropertyGroupError
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<DuplicatePropertyGroups> Encoder = new DuplicatePropertyGroupsEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<DuplicatePropertyGroups> Decoder = new DuplicatePropertyGroupsDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="DuplicatePropertyGroups" />
            /// class.</para>
            /// </summary>
            private DuplicatePropertyGroups()
            {
            }

            /// <summary>
            /// <para>A singleton instance of DuplicatePropertyGroups</para>
            /// </summary>
            public static readonly DuplicatePropertyGroups Instance = new DuplicatePropertyGroups();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="DuplicatePropertyGroups" />.</para>
            /// </summary>
            private class DuplicatePropertyGroupsEncoder : enc.StructEncoder<DuplicatePropertyGroups>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(DuplicatePropertyGroups value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="DuplicatePropertyGroups" />.</para>
            /// </summary>
            private class DuplicatePropertyGroupsDecoder : enc.StructDecoder<DuplicatePropertyGroups>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="DuplicatePropertyGroups"
                /// />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override DuplicatePropertyGroups Create()
                {
                    return DuplicatePropertyGroups.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>The path object</para>
        /// </summary>
        public sealed class Path : InvalidPropertyGroupError
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<Path> Encoder = new PathEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<Path> Decoder = new PathDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Path" /> class.</para>
            /// </summary>
            /// <param name="value">The value</param>
            public Path(LookupError value)
            {
                this.Value = value;
            }
            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Path" /> class.</para>
            /// </summary>
            private Path()
            {
            }

            /// <summary>
            /// <para>Gets the value of this instance.</para>
            /// </summary>
            public LookupError Value { get; private set; }

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="Path" />.</para>
            /// </summary>
            private class PathEncoder : enc.StructEncoder<Path>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(Path value, enc.IJsonWriter writer)
                {
                    WriteProperty("path", value.Value, writer, global::Dropbox.Api.FileProperties.LookupError.Encoder);
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="Path" />.</para>
            /// </summary>
            private class PathDecoder : enc.StructDecoder<Path>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="Path" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override Path Create()
                {
                    return new Path();
                }

                /// <summary>
                /// <para>Set given field.</para>
                /// </summary>
                /// <param name="value">The field value.</param>
                /// <param name="fieldName">The field name.</param>
                /// <param name="reader">The json reader.</param>
                protected override void SetField(Path value, string fieldName, enc.IJsonReader reader)
                {
                    switch (fieldName)
                    {
                        case "path":
                            value.Value = global::Dropbox.Api.FileProperties.LookupError.Decoder.Decode(reader);
                            break;
                        default:
                            reader.Skip();
                            break;
                    }
                }
            }

            #endregion
        }

        /// <summary>
        /// <para>This folder cannot be tagged. Tagging folders is not supported for team-owned
        /// templates.</para>
        /// </summary>
        public sealed class UnsupportedFolder : InvalidPropertyGroupError
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<UnsupportedFolder> Encoder = new UnsupportedFolderEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<UnsupportedFolder> Decoder = new UnsupportedFolderDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="UnsupportedFolder" />
            /// class.</para>
            /// </summary>
            private UnsupportedFolder()
            {
            }

            /// <summary>
            /// <para>A singleton instance of UnsupportedFolder</para>
            /// </summary>
            public static readonly UnsupportedFolder Instance = new UnsupportedFolder();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="UnsupportedFolder" />.</para>
            /// </summary>
            private class UnsupportedFolderEncoder : enc.StructEncoder<UnsupportedFolder>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(UnsupportedFolder value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="UnsupportedFolder" />.</para>
            /// </summary>
            private class UnsupportedFolderDecoder : enc.StructDecoder<UnsupportedFolder>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="UnsupportedFolder"
                /// />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override UnsupportedFolder Create()
                {
                    return UnsupportedFolder.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>Template does not exist for the given identifier.</para>
        /// </summary>
        public sealed class TemplateNotFound : InvalidPropertyGroupError
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<TemplateNotFound> Encoder = new TemplateNotFoundEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<TemplateNotFound> Decoder = new TemplateNotFoundDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="TemplateNotFound" />
            /// class.</para>
            /// </summary>
            /// <param name="value">The value</param>
            public TemplateNotFound(string value)
            {
                this.Value = value;
            }
            /// <summary>
            /// <para>Initializes a new instance of the <see cref="TemplateNotFound" />
            /// class.</para>
            /// </summary>
            private TemplateNotFound()
            {
            }

            /// <summary>
            /// <para>Gets the value of this instance.</para>
            /// </summary>
            public string Value { get; private set; }

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="TemplateNotFound" />.</para>
            /// </summary>
            private class TemplateNotFoundEncoder : enc.StructEncoder<TemplateNotFound>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(TemplateNotFound value, enc.IJsonWriter writer)
                {
                    WriteProperty("template_not_found", value.Value, writer, enc.StringEncoder.Instance);
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="TemplateNotFound" />.</para>
            /// </summary>
            private class TemplateNotFoundDecoder : enc.StructDecoder<TemplateNotFound>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="TemplateNotFound" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override TemplateNotFound Create()
                {
                    return new TemplateNotFound();
                }

                /// <summary>
                /// <para>Set given field.</para>
                /// </summary>
                /// <param name="value">The field value.</param>
                /// <param name="fieldName">The field name.</param>
                /// <param name="reader">The json reader.</param>
                protected override void SetField(TemplateNotFound value, string fieldName, enc.IJsonReader reader)
                {
                    switch (fieldName)
                    {
                        case "template_not_found":
                            value.Value = enc.StringDecoder.Instance.Decode(reader);
                            break;
                        default:
                            reader.Skip();
                            break;
                    }
                }
            }

            #endregion
        }

        /// <summary>
        /// <para>You do not have permission to modify this template.</para>
        /// </summary>
        public sealed class RestrictedContent : InvalidPropertyGroupError
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<RestrictedContent> Encoder = new RestrictedContentEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<RestrictedContent> Decoder = new RestrictedContentDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="RestrictedContent" />
            /// class.</para>
            /// </summary>
            private RestrictedContent()
            {
            }

            /// <summary>
            /// <para>A singleton instance of RestrictedContent</para>
            /// </summary>
            public static readonly RestrictedContent Instance = new RestrictedContent();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="RestrictedContent" />.</para>
            /// </summary>
            private class RestrictedContentEncoder : enc.StructEncoder<RestrictedContent>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(RestrictedContent value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="RestrictedContent" />.</para>
            /// </summary>
            private class RestrictedContentDecoder : enc.StructDecoder<RestrictedContent>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="RestrictedContent"
                /// />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override RestrictedContent Create()
                {
                    return RestrictedContent.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>The other object</para>
        /// </summary>
        public sealed class Other : InvalidPropertyGroupError
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<Other> Encoder = new OtherEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<Other> Decoder = new OtherDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Other" /> class.</para>
            /// </summary>
            private Other()
            {
            }

            /// <summary>
            /// <para>A singleton instance of Other</para>
            /// </summary>
            public static readonly Other Instance = new Other();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="Other" />.</para>
            /// </summary>
            private class OtherEncoder : enc.StructEncoder<Other>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(Other value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="Other" />.</para>
            /// </summary>
            private class OtherDecoder : enc.StructDecoder<Other>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="Other" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override Other Create()
                {
                    return Other.Instance;
                }

            }

            #endregion
        }
    }
}


text:
FactoryBot.define do
  factory :garden_crop do
    quantity    { rand(100) }
    sowed       { Faker::Date.between(2.days.ago, Date.today) }
    stage
    garden
    guide
  end
end


text:
package suite

import (
	"context"
	"fmt"
	"os"
	"strings"
	"testing"
	"time"

	corev1 "k8s.io/api/core/v1"
	discov1 "k8s.io/api/discovery/v1"
	discov1beta1 "k8s.io/api/discovery/v1beta1"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/fields"
	k8sRuntime "k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	versionapi "k8s.io/apimachinery/pkg/version"
	"k8s.io/apimachinery/pkg/watch"
	fakediscovery "k8s.io/client-go/discovery/fake"
	k8sTesting "k8s.io/client-go/testing"

	operatorOption "github.com/cilium/cilium/operator/option"
	"github.com/cilium/cilium/operator/watchers"
	"github.com/cilium/cilium/pkg/hive"
	"github.com/cilium/cilium/pkg/hive/cell"
	"github.com/cilium/cilium/pkg/k8s/version"
	agentOption "github.com/cilium/cilium/pkg/option"

	agentCmd "github.com/cilium/cilium/daemon/cmd"
	operatorCmd "github.com/cilium/cilium/operator/cmd"
	fakeDatapath "github.com/cilium/cilium/pkg/datapath/fake"
	fqdnproxy "github.com/cilium/cilium/pkg/fqdn/proxy"
	ipamOption "github.com/cilium/cilium/pkg/ipam/option"
	cilium_v2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
	k8sClient "github.com/cilium/cilium/pkg/k8s/client"
	slim_corev1 "github.com/cilium/cilium/pkg/k8s/slim/k8s/api/core/v1"
	"github.com/cilium/cilium/pkg/node/types"
	"github.com/cilium/cilium/pkg/proxy"
)

const (
	validationTimeout = 10 * time.Second
)

type trackerAndDecoder struct {
	tracker k8sTesting.ObjectTracker
	decoder k8sRuntime.Decoder
}

type ControlPlaneTest struct {
	t              *testing.T
	nodeName       string
	clients        *k8sClient.FakeClientset
	trackers       []trackerAndDecoder
	agentHandle    *agentHandle
	operatorHandle *operatorHandle
	Datapath       *fakeDatapath.FakeDatapath
}

func NewControlPlaneTest(t *testing.T, nodeName string, k8sVersion string) *ControlPlaneTest {
	clients, _ := k8sClient.NewFakeClientset()
	clients.KubernetesFakeClientset = addFieldSelection(clients.KubernetesFakeClientset)
	clients.SlimFakeClientset = addFieldSelection(clients.SlimFakeClientset)
	clients.CiliumFakeClientset = addFieldSelection(clients.CiliumFakeClientset)
	clients.APIExtFakeClientset = addFieldSelection(clients.APIExtFakeClientset)
	fd := clients.KubernetesFakeClientset.Discovery().(*fakediscovery.FakeDiscovery)
	fd.FakedServerVersion = toVersionInfo(k8sVersion)

	resources, ok := apiResources[k8sVersion]
	if !ok {
		panic(fmt.Sprintf("k8s version %s not found in apiResources", k8sVersion))
	}
	clients.KubernetesFakeClientset.Resources = resources
	clients.SlimFakeClientset.Resources = resources
	clients.CiliumFakeClientset.Resources = resources
	clients.APIExtFakeClientset.Resources = resources

	trackers := []trackerAndDecoder{
		{clients.KubernetesFakeClientset.Tracker(), coreDecoder},
		{clients.SlimFakeClientset.Tracker(), slimDecoder},
		{clients.CiliumFakeClientset.Tracker(), ciliumDecoder},
	}

	return &ControlPlaneTest{
		t:        t,
		nodeName: nodeName,
		clients:  clients,
		trackers: trackers,
	}
}

// SetupEnvironment sets the fake k8s clients and the mock FQDN proxy required for control-plane testing.
// Then, it loads the defaults values for both the daemon and the operator configurations.
// Finally, it calls modConfig to overwrite testcase specific options values.
func (cpt *ControlPlaneTest) SetupEnvironment(modConfig func(*agentOption.DaemonConfig, *operatorOption.OperatorConfig)) *ControlPlaneTest {
	types.SetName(cpt.nodeName)

	// Configure k8s and perform capability detection with the fake client.
	version.Update(cpt.clients, true)

	agentOption.Config.Populate(agentCmd.Vp)
	agentOption.Config.IdentityAllocationMode = agentOption.IdentityAllocationModeCRD
	agentOption.Config.DryMode = true
	agentOption.Config.IPAM = ipamOption.IPAMKubernetes
	agentOption.Config.Opts = agentOption.NewIntOptions(&agentOption.DaemonMutableOptionLibrary)
	agentOption.Config.Opts.SetBool(agentOption.DropNotify, true)
	agentOption.Config.Opts.SetBool(agentOption.TraceNotify, true)
	agentOption.Config.Opts.SetBool(agentOption.PolicyVerdictNotify, true)
	agentOption.Config.Opts.SetBool(agentOption.Debug, true)
	agentOption.Config.EnableIPSec = false
	agentOption.Config.EnableIPv6 = false
	agentOption.Config.KubeProxyReplacement = agentOption.KubeProxyReplacementStrict
	agentOption.Config.EnableHostIPRestore = false
	agentOption.Config.K8sRequireIPv6PodCIDR = false
	agentOption.Config.K8sEnableK8sEndpointSlice = true
	agentOption.Config.EnableL7Proxy = false
	agentOption.Config.EnableHealthCheckNodePort = false
	agentOption.Config.Debug = true

	operatorOption.Config.Populate(operatorCmd.Vp)
	operatorOption.Config.SkipCRDCreation = true

	// Apply the test specific configuration
	modConfig(agentOption.Config, operatorOption.Config)

	if agentOption.Config.EnableL7Proxy {
		proxy.DefaultDNSProxy = fqdnproxy.MockFQDNProxy{}
	}
	return cpt
}

func (cpt *ControlPlaneTest) StartAgent() *ControlPlaneTest {
	if cpt.agentHandle != nil {
		cpt.t.Fatal("StartAgent() already called")
	}
	datapath, agentHandle, err := startCiliumAgent(cpt.t, cpt.nodeName, cpt.clients)
	if err != nil {
		cpt.t.Fatalf("Failed to start cilium agent: %s", err)
	}
	cpt.agentHandle = &agentHandle
	cpt.Datapath = datapath
	return cpt
}

func (cpt *ControlPlaneTest) StopAgent() {
	cpt.agentHandle.tearDown()
	cpt.agentHandle = nil
	cpt.Datapath = nil
}

func (cpt *ControlPlaneTest) StartOperator() *ControlPlaneTest {
	if cpt.operatorHandle != nil {
		cpt.t.Fatal("StartOperator() already called")
	}

	operatorCmd.ResetCiliumNodesCacheSyncedStatus()
	watchers.PodStoreSynced = make(chan struct{})
	watchers.UnmanagedPodStoreSynced = make(chan struct{})

	cpt.operatorHandle = &operatorHandle{
		t: cpt.t,
		hive: hive.New(
			cell.Provide(func() k8sClient.Clientset {
				return cpt.clients
			}),
			operatorCmd.OperatorCell,
		),
	}

	// Disable support for operator HA. This should be cleaned up
	// by injecting the capabilities, or by supporting the leader
	// election machinery in the controlplane tests.
	version.DisableLeasesResourceLock()

	err := cpt.operatorHandle.hive.Start(context.Background())
	if err != nil {
		cpt.t.Fatalf("Failed to start operator: %s", err)
	}

	return cpt
}

func (cpt *ControlPlaneTest) StopOperator() {
	cpt.operatorHandle.tearDown()
	cpt.operatorHandle = nil
}

func (cpt *ControlPlaneTest) UpdateObjects(objs ...k8sRuntime.Object) *ControlPlaneTest {
	t := cpt.t
	for _, obj := range objs {
		gvr, ns, name := gvrAndName(obj)

		// Convert to unstructured form for JSON marshalling.
		// TODO: simpler way?
		uobj, ok := obj.(*unstructured.Unstructured)
		if !ok {
			fields, err := k8sRuntime.DefaultUnstructuredConverter.ToUnstructured(obj)
			if err != nil {
				t.Fatalf("Failed to convert %T to unstructured: %s", obj, err)
			}
			uobj = &unstructured.Unstructured{Object: fields}
		}

		// Marshal the object to JSON in order to allow decoding it in different ways,
		// e.g. as v1.Node and as slim_corev1.Node. This avoids having to write both
		// the core and slim versions of the object in the test case.
		jsonBytes, err := uobj.MarshalJSON()
		if err != nil {
			t.Fatalf("Failed to marshal %T to JSON: %s", obj, err)
		}

		accepted := false
		var errors []error
		for _, td := range cpt.trackers {
			if obj, _, err := td.decoder.Decode(jsonBytes, nil, nil); err == nil {
				accepted = true

				if _, err := td.tracker.Get(gvr, ns, name); err == nil {
					if err := td.tracker.Update(gvr, obj, ns); err != nil {
						t.Fatalf("Failed to update object %T: %s", obj, err)
					}
				} else {
					if err := td.tracker.Add(obj); err != nil {
						t.Fatalf("Failed to add object %T: %s", obj, err)
					}
				}
			} else {
				errors = append(errors, err)
			}
		}
		if !accepted {
			t.Fatalf("None of the decoders accepted %s: %v", gvr, errors)
		}
	}
	return cpt
}

// Get retrieves a k8s object given its group-version-resource, namespace and name.
// All the mocked control plane trackers will be queried in the search:
// - core
// - slim
// - cilium
// The first match will be returned.
// If the object cannot be found, a non nil error is returned.
func (cpt *ControlPlaneTest) Get(gvr schema.GroupVersionResource, ns, name string) (k8sRuntime.Object, error) {
	var (
		obj k8sRuntime.Object
		err error
	)
	for _, td := range cpt.trackers {
		if obj, err = td.tracker.Get(gvr, ns, name); err == nil {
			return obj, nil
		}
	}
	return nil, err
}

func (cpt *ControlPlaneTest) UpdateObjectsFromFile(filename string) *ControlPlaneTest {
	bs, err := os.ReadFile(filename)
	if err != nil {
		cpt.t.Fatalf("Failed to read %s: %s", filename, err)
	}
	objs, err := unmarshalList(bs)
	if err != nil {
		cpt.t.Fatalf("Failed to unmarshal objects from %s: %s", filename, err)
	}
	return cpt.UpdateObjects(objs...)
}

func (cpt *ControlPlaneTest) DeleteObjects(objs ...k8sRuntime.Object) *ControlPlaneTest {
	for _, obj := range objs {
		gvr, ns, name := gvrAndName(obj)

		deleted := false
		for _, td := range cpt.trackers {
			if err := td.tracker.Delete(gvr, ns, name); err == nil {
				deleted = true
			}
		}
		if !deleted {
			cpt.t.Fatalf("Failed to delete object %s/%s as it was not found", ns, name)
		}
	}
	return cpt
}

func (cpt *ControlPlaneTest) Eventually(check func() error) *ControlPlaneTest {
	if err := retryUptoDuration(check, validationTimeout); err != nil {
		cpt.t.Fatal(err)
	}
	return cpt
}

func (cpt *ControlPlaneTest) Execute(task func() error) *ControlPlaneTest {
	if err := task(); err != nil {
		cpt.t.Fatal(err)
	}
	return cpt
}

func retryUptoDuration(act func() error, maxDuration time.Duration) error {
	wait := 50 * time.Millisecond
	end := time.Now().Add(maxDuration)

	for time.Now().Add(wait).Before(end) {
		time.Sleep(wait)
		if err := act(); err == nil {
			return nil
		}
		wait *= 2
	}

	time.Sleep(end.Sub(time.Now()))
	return act()
}

func toVersionInfo(rawVersion string) *versionapi.Info {
	parts := strings.Split(rawVersion, ".")
	return &versionapi.Info{Major: parts[0], Minor: parts[1]}
}

func gvrAndName(obj k8sRuntime.Object) (gvr schema.GroupVersionResource, ns string, name string) {
	gvk := obj.GetObjectKind().GroupVersionKind()
	gvr, _ = meta.UnsafeGuessKindToResource(gvk)
	objMeta, err := meta.Accessor(obj)
	if err != nil {
		panic(err)
	}
	ns = objMeta.GetNamespace()
	name = objMeta.GetName()
	return
}

var (
	corev1APIResources = &metav1.APIResourceList{
		GroupVersion: corev1.SchemeGroupVersion.String(),
		APIResources: []metav1.APIResource{
			{Name: "nodes", Kind: "Node"},
			{Name: "pods", Namespaced: true, Kind: "Pod"},
			{Name: "services", Namespaced: true, Kind: "Service"},
			{Name: "endpoints", Namespaced: true, Kind: "Endpoint"},
		},
	}

	ciliumv2APIResources = &metav1.APIResourceList{
		TypeMeta:     metav1.TypeMeta{},
		GroupVersion: cilium_v2.SchemeGroupVersion.String(),
		APIResources: []metav1.APIResource{
			{Name: cilium_v2.CNPluralName, Kind: cilium_v2.CNKindDefinition},
			{Name: cilium_v2.CEPPluralName, Namespaced: true, Kind: cilium_v2.CEPKindDefinition},
			{Name: cilium_v2.CIDPluralName, Namespaced: true, Kind: cilium_v2.CIDKindDefinition},
			{Name: cilium_v2.CEGPPluralName, Namespaced: true, Kind: cilium_v2.CEGPKindDefinition},
			{Name: cilium_v2.CNPPluralName, Namespaced: true, Kind: cilium_v2.CNPKindDefinition},
			{Name: cilium_v2.CCNPPluralName, Namespaced: true, Kind: cilium_v2.CCNPKindDefinition},
			{Name: cilium_v2.CLRPPluralName, Namespaced: true, Kind: cilium_v2.CLRPKindDefinition},
			{Name: cilium_v2.CEWPluralName, Namespaced: true, Kind: cilium_v2.CEWKindDefinition},
			{Name: cilium_v2.CCECPluralName, Namespaced: true, Kind: cilium_v2.CCECKindDefinition},
			{Name: cilium_v2.CECPluralName, Namespaced: true, Kind: cilium_v2.CECKindDefinition},
		},
	}

	discoveryV1APIResources = &metav1.APIResourceList{
		TypeMeta:     metav1.TypeMeta{},
		GroupVersion: discov1.SchemeGroupVersion.String(),
		APIResources: []metav1.APIResource{
			{Name: "endpointslices", Namespaced: true, Kind: "EndpointSlice"},
		},
	}

	discoveryV1beta1APIResources = &metav1.APIResourceList{
		GroupVersion: discov1beta1.SchemeGroupVersion.String(),
		APIResources: []metav1.APIResource{
			{Name: "endpointslices", Namespaced: true, Kind: "EndpointSlice"},
		},
	}

	// apiResources is the list of API resources for the k8s version that we're mocking.
	// This is mostly relevant for the feature detection at pkg/k8s/version/version.go.
	// The lists here are currently not exhaustive and expanded on need-by-need basis.
	apiResources = map[string][]*metav1.APIResourceList{
		"1.23": {
			corev1APIResources,
			discoveryV1APIResources,
			discoveryV1beta1APIResources,
			ciliumv2APIResources,
		},
		"1.24": {
			corev1APIResources,
			discoveryV1APIResources,
			discoveryV1beta1APIResources,
			ciliumv2APIResources,
		},
		"1.25": {
			corev1APIResources,
			discoveryV1APIResources,
			ciliumv2APIResources,
		},
	}
)

func matchFieldSelector(obj k8sRuntime.Object, selector fields.Selector) bool {
	if selector == nil {
		return true
	}

	fs := fields.Set{}
	acc, err := meta.Accessor(obj)
	if err != nil {
		panic(err)
	}
	fs["metadata.name"] = acc.GetName()
	fs["metadata.namespace"] = acc.GetNamespace()

	// Special handling for specific objects. Only add things here that k8s api-server
	// handles, see for example ToSelectableFields() in pkg/registry/core/pod/strategy.go
	// of kubernetes. We don't want to end up with tests passing with fake client and
	// failing against the real API server.
	if pod, ok := obj.(*corev1.Pod); ok {
		fs["spec.nodeName"] = pod.Spec.NodeName
	}
	if pod, ok := obj.(*slim_corev1.Pod); ok {
		fs["spec.nodeName"] = pod.Spec.NodeName
	}

	if !selector.Matches(fs) {
		// Check if we failed because we were trying to match a field that doesn't exist.
		// If so, we'll panic so that an exception can be added.
		for _, req := range selector.Requirements() {
			if _, ok := fs[req.Field]; !ok {
				panic(fmt.Sprintf(
					"Unknown field selector %q!\nPlease add handling for it to matchFieldSelector() in test/controlplane/suite/testcase.go",
					req.Field))
			}
		}
		return false
	}
	return true
}

type fakeWithTracker interface {
	PrependReactor(verb string, resource string, reaction k8sTesting.ReactionFunc)
	PrependWatchReactor(resource string, reaction k8sTesting.WatchReactionFunc)
	Tracker() k8sTesting.ObjectTracker
}

type filteringWatcher struct {
	parent       watch.Interface
	events       chan watch.Event
	restrictions k8sTesting.WatchRestrictions
}

var _ watch.Interface = &filteringWatcher{}

func (fw *filteringWatcher) Stop() {
	fw.parent.Stop()
	close(fw.events)
	fw.events = nil
}

func (fw *filteringWatcher) ResultChan() <-chan watch.Event {
	if fw.events != nil {
		return fw.events
	}

	fw.events = make(chan watch.Event)
	selector := fw.restrictions.Fields
	go func() {
		for event := range fw.parent.ResultChan() {
			if matchFieldSelector(event.Object, selector) {
				fw.events <- event
			}
		}
	}()
	return fw.events
}

func filterList(obj k8sRuntime.Object, restrictions k8sTesting.ListRestrictions) {
	selector := restrictions.Fields
	if selector == nil || selector.Empty() {
		return
	}

	switch obj := obj.(type) {
	case *corev1.NodeList:
		items := make([]corev1.Node, 0, len(obj.Items))
		for i := range obj.Items {
			if matchFieldSelector(&obj.Items[i], selector) {
				items = append(items, obj.Items[i])
			}
		}
		obj.Items = items
	case *slim_corev1.EndpointsList:
		items := make([]slim_corev1.Endpoints, 0, len(obj.Items))
		for i := range obj.Items {
			if matchFieldSelector(&obj.Items[i], selector) {
				items = append(items, obj.Items[i])
			}
		}
		obj.Items = items
	case *slim_corev1.PodList:
		items := make([]slim_corev1.Pod, 0, len(obj.Items))
		for i := range obj.Items {
			if matchFieldSelector(&obj.Items[i], selector) {
				items = append(items, obj.Items[i])
			}
		}
		obj.Items = items
	default:
		panic(
			fmt.Sprintf("Unhandled type %T for field selector filtering!\nPlease add handling for it to filterList()", obj),
		)
	}
}

// addFieldSelection augments the fake clientset to support filtering with a field selector
// in List and Watch actions
func addFieldSelection[T fakeWithTracker](f T) T {
	o := f.Tracker()
	objectReaction := k8sTesting.ObjectReaction(o)

	// Prepend our own reactors that adds field selector filtering to
	// the results.
	f.PrependReactor("*", "*", func(action k8sTesting.Action) (handled bool, ret k8sRuntime.Object, err error) {
		handled, ret, err = objectReaction(action)

		switch action := action.(type) {
		case k8sTesting.ListActionImpl:
			filterList(ret, action.GetListRestrictions())
		}
		return

	})

	f.PrependWatchReactor(
		"*",
		func(action k8sTesting.Action) (handled bool, ret watch.Interface, err error) {
			w := action.(k8sTesting.WatchAction)
			gvr := w.GetResource()
			ns := w.GetNamespace()
			watch, err := o.Watch(gvr, ns)
			if err != nil {
				return false, nil, err
			}
			fw := &filteringWatcher{
				parent:       watch,
				restrictions: w.GetWatchRestrictions(),
			}
			return true, fw, nil

		})

	return f
}


text:
<?php

namespace CP\AdminBundle\Controller;

use CP\CPBundle\Entity\Application;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use CP\AdminBundle\Form\Type\ApplicationAdminType;

class ApplicationAdminController extends Controller
{

    public function editAction (Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $application = $em->getRepository('CPBundle:Application')->find(1);

        $form = $this->get('form.factory')->create(new ApplicationAdminType(), $application );

        if ($form->handleRequest($request)->isValid())
        {
            $em = $this->getDoctrine()->getManager();
            $em->persist($application);
            $em->flush();
            return $this->redirect($this->generateUrl('admin'));
        }

        return $this->render('AdminBundle:ApplicationAdmin:edit.html.twig', array(
            'form'      =>  $form->createView(),
            'application'  => $application
        ));
    }

}


text:
package com.example.amit.popularmovies.reviews;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.example.amit.popularmovies.R;

import java.util.ArrayList;

public class ReviewAdapter extends ArrayAdapter<MovieReviewModel> {
    private ArrayList<MovieReviewModel> mReviewData = new ArrayList<>();

    public static class ViewHolder{
        public TextView author;
        public TextView content;
    }

    public ReviewAdapter(Context context, int layoutResourceId, ArrayList<MovieReviewModel> reviews){
        super(context, layoutResourceId, reviews);
        this.mReviewData = reviews;
    }

    @Override
    public int getCount(){
        return this.mReviewData.size();
    }

    @Override
    public View getView(int pos, View convertView, ViewGroup parent){
        ViewHolder viewHolder;
        if(convertView == null){
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.list_item_review, parent, false);
            viewHolder.author = (TextView) convertView.findViewById(R.id.text_view_author);
            viewHolder.content = (TextView) convertView.findViewById(R.id.text_view_content);
            convertView.setTag(viewHolder);
        }else
            viewHolder = (ViewHolder)convertView.getTag();

        MovieReviewModel movieReviewModel = mReviewData.get(pos);
        Log.v("ReviewAdapter",movieReviewModel.mAuthor);
        viewHolder.author.setText(getContext().getString(R.string.reviewby_text)+" "+movieReviewModel.mAuthor);
        viewHolder.content.setText(movieReviewModel.mContent);

        return convertView;
    }
}


text:
using UnityEngine;
using System.Collections.Generic;

public class UI
{
	static GUISkin mNullSkin = null;
	static GUIContent mContent = null;
	static Color mColor;

	/// <summary>
	/// It's often useful to have a skin that is clean and devoid of borders, padding, margins, etc.
	/// </summary>

	static public GUISkin nullSkin
	{
		get
		{
			if (mNullSkin == null)
			{
				mNullSkin = GUISkin.CreateInstance("GUISkin") as GUISkin;
				mNullSkin.name = "Null Skin (Tools.cs)";

				if (Config.Instance != null)
				{
					mNullSkin.box.normal.background = Config.Instance.windowBorder;
					mNullSkin.box.border.left = Config.Instance.windowPadding;
					mNullSkin.box.border.right = Config.Instance.windowPadding;
					mNullSkin.box.border.top = Config.Instance.windowPadding;
					mNullSkin.box.border.bottom = Config.Instance.windowPadding;
				}
			}
			return mNullSkin;
		}
	}

	/// <summary>
	/// Wraps the angle, ensuring that it's always in the -360 to 360 range.
	/// </summary>

	static public float WrapAngle (float a)
	{
		while (a < -180.0f) a += 360.0f;
		while (a > 180.0f) a -= 360.0f;
		return a;
	}

	/// <summary>
	/// Replaces the GUI color with the specified alpha value.
	/// </summary>

	static public void SetAlpha (float a)
	{
		mColor = GUI.color;
		GUI.color = new Color(1.0f, 1.0f, 1.0f, a);
	}

	/// <summary>
	/// Restores the previous GUI color.
	/// </summary>

	static public void RestoreAlpha () { GUI.color = mColor; }

	/// <summary>
	/// Draws the tiled texture. Like GUI.DrawTexture() but tiled instead of stretched.
	/// </summary>

	static public void DrawTiledTexture (Rect rect, Texture tex)
	{
		GUI.BeginGroup(rect);
		{
			int width  = Mathf.RoundToInt(rect.width);
			int height = Mathf.RoundToInt(rect.height);

			for (int y = 0; y < height; y += tex.height)
			{
				for (int x = 0; x < width; x += tex.width)
				{
					GUI.DrawTexture(new Rect(x, y, tex.width, tex.height), tex);
				}
			}
		}
		GUI.EndGroup();
	}

	/// <summary>
	/// Draws the specified tiled texture using the given element's offset.
	/// </summary>

	static public Rect DrawTiledTexture (Rect rect, float offset, Texture tex)
	{
		rect = new Rect(rect.x + offset, rect.y + offset,
			rect.width - offset - offset,
			rect.height - offset - offset);

		DrawTiledTexture(rect, tex);
		return rect;
	}

	/// <summary>
	/// Helper function that draws a texture, cleanly with no border, margin, or padding.
	/// </summary>

	static public Rect DrawTexture (float x, float y, Texture tex)
	{
		Rect rect = new Rect(x, y, tex.width, tex.height);
		GUI.DrawTexture(rect, tex);
		return rect;
	}

	/// <summary>
	/// Helper function that draws a box similar to GUI.Box(), but with a THS border and a tiled background.
	/// </summary>

	static public Rect DrawPanel (Rect rect)
	{
		Rect retVal = DrawTiledTexture(rect,
			Config.Instance.windowPadding,
			Config.Instance.windowBackground);

		GUI.Box(rect, "", nullSkin.box);

		// Content rectangle
		return retVal;
	}

	/// <summary>
	/// Draws a window over the specified rectangle.
	/// </summary>

	static public Rect DrawWindow (Rect rect, string text)
	{
		rect = DrawPanel(rect);
		Rect titleRect = new Rect(rect.x + 50.0f, rect.y - 25.0f, rect.width - 100.0f, 40.0f);
		DrawPanel(titleRect);
		DrawTitle(titleRect, text, Config.Instance.headerStyle);
		return Bevel(rect, 8f);
	}

	/// <summary>
	/// Draws a shadowed (or beveled) label with specified colors.
	/// </summary>

	static public void DrawLabel (Rect rect, string text, GUIStyle style, Color front, Color back)
	{
		DrawLabel(rect, text, style, front, back, false);
	}

	/// <summary>
	/// Draws a shadowed (or beveled) label with specified colors.
	/// </summary>

	static public void DrawLabel (Rect rect, string text, GUIStyle style, Color front, Color back, bool outline)
	{
		Color prev = style.normal.textColor;

		// Shadow
		style.normal.textColor = back;
		GUI.Label(new Rect(rect.x + 1.0f, rect.y + 1.0f, rect.width, rect.height), text, style);

		if (outline)
		{
			GUI.Label(new Rect(rect.x + 1.0f, rect.y - 1.0f, rect.width, rect.height), text, style);
			GUI.Label(new Rect(rect.x - 1.0f, rect.y - 1.0f, rect.width, rect.height), text, style);
			GUI.Label(new Rect(rect.x - 1.0f, rect.y + 1.0f, rect.width, rect.height), text, style);
		}

		// Actual label
		style.normal.textColor = front;
		GUI.Label(rect, text, style);

		style.normal.textColor = prev;
	}

	/// <summary>
	/// Draws a shadowed (or beveled) label with specified colors.
	/// </summary>

	static public void DrawLabel (string text, GUIStyle style, Color front, Color back)
	{
		Color prev = style.normal.textColor;

		// Shadow
		style.normal.textColor = back;
		GUILayout.Label(text, style);

		// Actual label
		style.normal.textColor = front;
		Rect rect = GUILayoutUtility.GetLastRect();
		GUI.Label(new Rect(rect.x - 1.0f, rect.y - 1.0f, rect.width, rect.height), text, style);

		style.normal.textColor = prev;
	}

	/// <summary>
	/// Draws a label with a distinct beveled style.
	/// </summary>

	static public void DrawLabel (string text, GUIStyle style)
	{
		DrawLabel(text, style, style.normal.textColor, style.hover.textColor);
	}

	/// <summary>
	/// Draws a label with a distinct beveled style.
	/// </summary>

	static public void DrawLabel (string text)
	{
		DrawLabel(text, GUI.skin.label);
	}

	/// <summary>
	/// Draws a label with a distinct beveled style.
	/// </summary>

	static public void DrawLabel (Rect rect, string text, GUIStyle style)
	{
		DrawLabel(rect, text, style, style.normal.textColor, style.hover.textColor, false);
	}

	/// <summary>
	/// Draws a label with a distinct beveled style.
	/// </summary>

	static public void DrawLabel (Rect rect, string text)
	{
		DrawLabel(rect, text, GUI.skin.label);
	}

	/// <summary>
	/// Common functionality for DrawTitle functions.
	/// </summary>

	static private void DrawBlobShadow (Rect rect, string text, GUIStyle style)
	{
		if (Config.Instance.townNameBackground != null)
		{
			Vector3 size = style.CalcSize(mContent);

			float padX = size.x * 0.25f;
			float padY = size.y * 0.5f;
			float x = (rect.width - size.x) * 0.5f - padX;
			float y = (rect.height - size.y) * 0.5f - padY;

			Color prev = GUI.color;
			GUI.color = new Color(1.0f, 1.0f, 1.0f, prev.a * 0.5f);
			GUI.DrawTexture(new Rect(rect.x + x, rect.y + y, rect.width - x * 2.0f, rect.height - y * 2.0f),
				Config.Instance.townNameBackground);
			GUI.color = prev;
		}
	}

	/// <summary>
	/// Draws a title label -- beveled header label with a blob shadow.
	/// </summary>

	static public void DrawTitle (Rect rect, string text, GUIStyle style)
	{
		TextAnchor prev = style.alignment;
		style.alignment = TextAnchor.MiddleCenter;

		if (mContent == null) mContent = new GUIContent();
		mContent.text = text;

		DrawBlobShadow(rect, text, style);
		DrawLabel(rect, text, style);
		style.alignment = prev;
	}

	/// <summary>
	/// Draws a title label -- beveled header label with a blob shadow.
	/// </summary>

	static public void DrawTitle (string text, GUIStyle style)
	{
		TextAnchor prev = style.alignment;
		style.alignment = TextAnchor.MiddleCenter;

		if (mContent == null) mContent = new GUIContent();
		mContent.text = text;

		Rect rect = GUILayoutUtility.GetRect(mContent, style);
		DrawBlobShadow(rect, text, style);
		DrawLabel(rect, text, style);
		style.alignment = prev;
	}

	/// <summary>
	/// Bevel the specified rect by the specified number of pixels.
	/// </summary>

	static public Rect Bevel (Rect rect, float pixels)
	{
		return new Rect(rect.x + pixels, rect.y + pixels, rect.width - pixels * 2.0f, rect.height - pixels * 2.0f);
	}

	/// <summary>
	/// Draws a grid of boxes and returns their positions.
	/// </summary>

	static public List<Vector2> DrawGrid (Rect rect, float sizeX, float sizeY, float padX, float padY, float border, int cells)
	{
		List<Vector2> list = new List<Vector2>();

		sizeX += border * 2.0f;
		sizeY += border * 2.0f;

		float x = rect.x;
		float y = rect.y;
		float mx = x + rect.width;
		float my = y + rect.height;
		int count = 0;

		GUIStyle style = Config.Instance.skin.box;

		while (y < my)
		{
			if (y + sizeY > my) break;

			while (x < mx)
			{
				if (x + sizeX > mx) break;

				Vector2 pos = new Vector2(x, y);
				GUI.Box(new Rect(x, y, sizeX, sizeY), "", style);
				x += sizeX + padX;
				pos.x += border;
				pos.y += border;
				list.Add(pos);

				if (++count >= cells) return list;
			}
			y += sizeY + padY;
			x = rect.x;
		}
		return list;
	}

	/// <summary>
	/// Whether the specified screen rectangle contains the mouse position.
	/// </summary>

	static public bool ContainsMouse (Rect rect)
	{
		Vector2 pos = Input.mousePosition;
		pos.y = Screen.height - pos.y;
		return rect.Contains(pos);
	}

	/// <summary>
	/// Gets the mouse position in GUI space (top-left based).
	/// </summary>

	static public Vector2 GetMousePos ()
	{
		Vector2 pos = Input.mousePosition;
		pos.y = Screen.height - pos.y;
		return pos;
	}

	/// <summary>
	/// Gets the screen position of the specified world position.
	/// </summary>

	static public Vector3 GetScreenPos (Vector3 worldPos)
	{
		Vector3 pos = Camera.main.WorldToScreenPoint(worldPos);
		pos.y = Screen.height - pos.y;
		return pos;
	}

	/// <summary>
	/// Whether this screen position is currently visible.
	/// </summary>

	static public bool IsVisible (Vector3 screenPos)
	{
		return !(screenPos.z < 0f ||
			screenPos.x < 0f ||
			screenPos.y < 0f ||
			screenPos.x > Screen.width ||
			screenPos.y > Screen.height);
	}
}


text:
<?php

/**
 * This class defines attributes, valid values, and usage which is generated from
 * a given json schema. http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
 *
 * @author Chirag Shah <chirags@google.com>
 *
 */
class apiModel {
  public function __construct( /* polymorphic */ ) {
    if (func_num_args() ==  1 && 'array' == gettype(func_get_arg(0))) {
      // Initialize the model with the array's contents.
      $array = func_get_arg(0);
      $this->mapTypes($array);
    }
  }

  /**
   * Initialize this object's properties from an array.
   *
   * @param array Used to seed this object's properties.
   * @return void
   */
  private function mapTypes($array) {
    foreach ($array as $key => $val) {
      $this->$key = $val;

      $keyTypeName = "__$key" . 'Type';
      if ($this->useObjects() && property_exists($this, $keyTypeName)) {
        if ($this->isAssociativeArray($val)) {
          $this->$key = $this->createObjectFromName($keyTypeName, $val);
        } else if (is_array($val)) {
          $arrayObject = array();
          foreach ($val as $arrayIndex => $arrayItem) {
            $arrayObject[$arrayIndex] = $this->createObjectFromName($keyTypeName, $arrayItem);
          }
          $this->$key = $arrayObject;
        }
      }
    }
  }

  /**
   * Returns true only if the array is associative.
   * @param array $array
   * @return bool True if the array is associative.
   */
  private function isAssociativeArray($array) {
    if (!is_array($array)) {
      return false;
    }
    $keys = array_keys($array);
    foreach($keys as $key) {
      if (is_string($key)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Given a variable name, discover its type.
   *
   * @param $name
   * @param $item
   * @return object The object from the item.
   */
  private function createObjectFromName($name, $item) {
    $type = $this->$name;
    return new $type($item);
  }

  protected function useObjects() {
    global $apiConfig;
    return (isset($apiConfig['use_objects']) && $apiConfig['use_objects']);
  }
}