text:
#include "hw.h"
#include "boards.h"
#include "devices.h"
#include "net.h"
#include "arm_pic.h"
#include "sysemu.h"
#include "goldfish_device.h"
#include "android/globals.h"
#include "audio/audio.h"
#include "arm-misc.h"
#include "console.h"
#include "blockdev.h"
#include "goldfish_pipe.h"
#ifdef CONFIG_MEMCHECK
#include "memcheck/memcheck_api.h"
#endif  // CONFIG_MEMCHECK

#include "android/utils/debug.h"

#define  D(...)  VERBOSE_PRINT(init,__VA_ARGS__)

#define ARM_CPU_SAVE_VERSION  1

char* audio_input_source = NULL;

void goldfish_memlog_init(uint32_t base);

static struct goldfish_device event0_device = {
    .name = "goldfish_events",
    .id = 0,
    .size = 0x1000,
    .irq_count = 1
};

static struct goldfish_device nand_device = {
    .name = "goldfish_nand",
    .id = 0,
    .size = 0x1000
};

/* Board init.  */

#define TEST_SWITCH 1
#if TEST_SWITCH
uint32_t switch_test_write(void *opaque, uint32_t state)
{
    goldfish_switch_set_state(opaque, state);
    return state;
}
#endif
static void android_arm_init_(ram_addr_t ram_size,
    const char *boot_device,
    const char *kernel_filename,
    const char *kernel_cmdline,
    const char *initrd_filename,
    const char *cpu_model)
{
    CPUState *env;
    qemu_irq *cpu_pic;
    qemu_irq *goldfish_pic;
    int i;
    struct arm_boot_info  info;
    ram_addr_t ram_offset;

    if (!cpu_model)
        cpu_model = "arm926";

    env = cpu_init(cpu_model);

    ram_offset = qemu_ram_alloc(NULL,"android_arm",ram_size);
    cpu_register_physical_memory(0, ram_size, ram_offset | IO_MEM_RAM);

    cpu_pic = arm_pic_init_cpu(env);
    goldfish_pic = goldfish_interrupt_init(0xff000000, cpu_pic[ARM_PIC_CPU_IRQ], cpu_pic[ARM_PIC_CPU_FIQ]);
    goldfish_device_init(goldfish_pic, 0xff010000, 0x7f0000, 10, 22);

    goldfish_device_bus_init(0xff001000, 1);

    goldfish_timer_and_rtc_init(0xff003000, 3);

    goldfish_tty_add(serial_hds[0], 0, 0xff002000, 4);
    for(i = 1; i < MAX_SERIAL_PORTS; i++) {
        //printf("android_arm_init serial %d %x\n", i, serial_hds[i]);
        if(serial_hds[i]) {
            goldfish_tty_add(serial_hds[i], i, 0, 0);
        }
    }

    for(i = 0; i < MAX_NICS; i++) {
        if (nd_table[i].vlan) {
            if (nd_table[i].model == NULL
                || strcmp(nd_table[i].model, "smc91c111") == 0) {
                struct goldfish_device *smc_device;
                smc_device = qemu_mallocz(sizeof(*smc_device));
                smc_device->name = "smc91x";
                smc_device->id = i;
                smc_device->size = 0x1000;
                smc_device->irq_count = 1;
                goldfish_add_device_no_io(smc_device);
                smc91c111_init(&nd_table[i], smc_device->base, goldfish_pic[smc_device->irq]);
            } else {
                fprintf(stderr, "qemu: Unsupported NIC: %s\n", nd_table[0].model);
                exit (1);
            }
        }
    }

    goldfish_fb_init(0);
#ifdef HAS_AUDIO
    goldfish_audio_init(0xff004000, 0, audio_input_source);
#endif
    {
        DriveInfo* info = drive_get( IF_IDE, 0, 0 );
        if (info != NULL) {
            goldfish_mmc_init(0xff005000, 0, info->bdrv);
        }
    }

    goldfish_memlog_init(0xff006000);

    if (android_hw->hw_battery)
        goldfish_battery_init();

    goldfish_add_device_no_io(&event0_device);
    events_dev_init(event0_device.base, goldfish_pic[event0_device.irq]);

#ifdef CONFIG_NAND
    goldfish_add_device_no_io(&nand_device);
    nand_dev_init(nand_device.base);
#endif
#ifdef CONFIG_TRACE
    extern const char *trace_filename;
    /* Init trace device if either tracing, or memory checking is enabled. */
    if (trace_filename != NULL
#ifdef CONFIG_MEMCHECK
        || memcheck_enabled
#endif  // CONFIG_MEMCHECK
       ) {
        trace_dev_init();
    }
    if (trace_filename != NULL) {
        D( "Trace file name is set to %s\n", trace_filename );
    } else  {
        D("Trace file name is not set\n");
    }
#endif

    pipe_dev_init();

#if TEST_SWITCH
    {
        void *sw;
        sw = goldfish_switch_add("test", NULL, NULL, 0);
        goldfish_switch_set_state(sw, 1);
        goldfish_switch_add("test2", switch_test_write, sw, 1);
    }
#endif

    memset(&info, 0, sizeof info);
    info.ram_size        = ram_size;
    info.kernel_filename = kernel_filename;
    info.kernel_cmdline  = kernel_cmdline;
    info.initrd_filename = initrd_filename;
    info.nb_cpus         = 1;
    info.board_id        = 1441;

    arm_load_kernel(env, &info);
}

QEMUMachine android_arm_machine = {
    "android_arm",
    "ARM Android Emulator",
    android_arm_init_,
    0,
    0,
    1,
    NULL
};

static void android_arm_init(void)
{
    qemu_register_machine(&android_arm_machine);
}

machine_init(android_arm_init);


text:
package org.apache.oodt.cas.resource.system.extern;

//JDK imports
import org.apache.oodt.cas.resource.structs.Job;
import org.apache.oodt.cas.resource.structs.JobInput;
import org.apache.oodt.cas.resource.structs.JobInstance;
import org.apache.oodt.cas.resource.structs.exceptions.JobException;
import org.apache.oodt.cas.resource.structs.exceptions.JobInputException;
import org.apache.oodt.cas.resource.util.GenericResourceManagerObjectFactory;
import org.apache.oodt.cas.resource.util.XmlRpcStructFactory;
import org.apache.xmlrpc.WebServer;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

//OODT imports
//APACHE imports

/**
 * @author woollard
 * @version $Revision$
 *
 * <p>
 * An XML RPC-based Batch Submission System.
 * </p>
 *
 */
public class XmlRpcBatchStub {

    /* the port to run the XML RPC web server on, default is 2000 */
    private int webServerPort = 2000;

    /* our xml rpc web server */
    private WebServer webServer = null;

    /* our log stream */
    private static Logger LOG = Logger.getLogger(XmlRpcBatchStub.class
        .getName());

    private Map jobThreadMap = null;

    public XmlRpcBatchStub(int port) {
        webServerPort = port;

        // start up the web server
        webServer = new WebServer(webServerPort);
        webServer.addHandler("batchstub", this);
        webServer.start();

        jobThreadMap = new ConcurrentHashMap();

        LOG.log(Level.INFO, "XmlRpc Batch Stub started by "
                            + System.getProperty("user.name", "unknown"));
    }

    public boolean isAlive() {
        return true;
    }

    public boolean executeJob(Map jobHash, Map jobInput)
        throws JobException {
        return genericExecuteJob(jobHash, jobInput);
    }

    public boolean executeJob(Map jobHash, Date jobInput)
        throws JobException {
        return genericExecuteJob(jobHash, jobInput);
    }

    public boolean executeJob(Map jobHash, double jobInput)
        throws JobException {
        return genericExecuteJob(jobHash, jobInput);
    }

    public boolean executeJob(Map jobHash, int jobInput)
        throws JobException {
        return genericExecuteJob(jobHash, jobInput);
    }

    public boolean executeJob(Map jobHash, boolean jobInput)
        throws JobException {
        return genericExecuteJob(jobHash, jobInput);
    }

    public boolean executeJob(Map jobHash, Vector jobInput)
        throws JobException {
        return genericExecuteJob(jobHash, jobInput);
    }

    public boolean executeJob(Map jobHash, byte[] jobInput)
        throws JobException {
        return genericExecuteJob(jobHash, jobInput);
    }

    public synchronized boolean killJob(Map jobHash) {
        Job job = XmlRpcStructFactory.getJobFromXmlRpc(jobHash);
        Thread jobThread = (Thread) jobThreadMap.get(job.getId());
        if (jobThread == null) {
            LOG.log(Level.WARNING, "Job: [" + job.getId()
                                   + "] not managed by this batch stub");
            return false;
        }

        // okay, so interrupt it, which should cause it to stop
        jobThread.interrupt();
        return true;
    }

    private boolean genericExecuteJob(Map jobHash, Object jobInput) {
        JobInstance exec = null;
        JobInput in = null;
        try {
            Job job = XmlRpcStructFactory.getJobFromXmlRpc(jobHash);

            LOG.log(Level.INFO, "stub attempting to execute class: ["
                                + job.getJobInstanceClassName() + "]");

            exec = GenericResourceManagerObjectFactory
                .getJobInstanceFromClassName(job.getJobInstanceClassName());
            in = GenericResourceManagerObjectFactory
                .getJobInputFromClassName(job.getJobInputClassName());

            // load the input obj
            in.read(jobInput);

            // create threaded job
            // so that it can be interrupted
            RunnableJob runner = new RunnableJob(exec, in);
            Thread threadRunner = new Thread(runner);
            /* save this job thread in a map so we can kill it later */
            jobThreadMap.put(job.getId(), threadRunner);
            threadRunner.start();

            try {
                threadRunner.join();
            } catch (InterruptedException e) {
                LOG.log(Level.INFO, "Current job: [" + job.getName()
                                    + "]: killed: exiting gracefully");
                synchronized (jobThreadMap) {
                    Thread endThread = (Thread) jobThreadMap.get(job.getId());
                    if (endThread != null) {
                        endThread = null;
                    }
                }
                return false;
            }

            synchronized (jobThreadMap) {
                Thread endThread = (Thread) jobThreadMap.get(job.getId());
                if (endThread != null) {
                    endThread = null;
                }
            }

            return runner.wasSuccessful();
        } catch (Exception e) {
            LOG.log(Level.SEVERE, e.getMessage());
            return false;
        }
    }

    public static void main(String[] args)  {
        int portNum = -1;
        String usage = "XmlRpcBatchStub --portNum <port number for xml rpc service>\n";

        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("--portNum")) {
                portNum = Integer.parseInt(args[++i]);
            }
        }

        if (portNum == -1) {
            System.err.println(usage);
            System.exit(1);
        }

        XmlRpcBatchStub stub = new XmlRpcBatchStub(portNum);

        for (;;) {
            try {
                Thread.currentThread().join();
            } catch (InterruptedException ignore) {
            }
        }
    }

    private class RunnableJob implements Runnable {

        private JobInput in;

        private JobInstance job;

        private boolean successful;

        public RunnableJob(JobInstance job, JobInput in) {
            this.job = job;
            this.in = in;
            this.successful = false;
        }

        /*
         * (non-Javadoc)
         *
         * @see java.lang.Runnable#run()
         */
        public void run() {
            try {
                this.successful = job.execute(in);
            } catch (JobInputException e) {
                LOG.log(Level.SEVERE, e.getMessage());
                this.successful = false;
            }

        }

        public boolean wasSuccessful() {
            return this.successful;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using NuGet.Test;
using Xunit;

namespace NuGet.VisualStudio.Test
{
    public class VsPackageSourceProviderTest
    {
        private const string NuGetOfficialFeedUrl = "https://www.nuget.org/api/v2/";
        private const string NuGetOfficialFeedName = "nuget.org";
        private const string NuGetLegacyOfficialFeedName = "NuGet official package source";

        [Fact]
        public void CtorIfFirstRunningAddsDefaultSource()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(1, sources.Count);
            Assert.Equal(NuGetOfficialFeedUrl, sources[0].Source);
        }

        [Fact]
        public void CtorMigrateV1FeedToV2Feed()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.GetSettingValues("packageSources", true))
                    .Returns(new[] { new SettingValue(NuGetLegacyOfficialFeedName, "https://go.microsoft.com/fwlink/?LinkID=206669", false) });
            var sourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, sourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(1, sources.Count);
            Assert.Equal(NuGetOfficialFeedUrl, sources[0].Source);
        }

        [Fact]
        public void CtorMigrateV2LegacyFeedToV2Feed()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.GetSettingValues("packageSources", true))
                        .Returns(new[] { new SettingValue(NuGetLegacyOfficialFeedName, "https://go.microsoft.com/fwlink/?LinkID=230477", false) });
            var sourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, sourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(1, sources.Count);
            Assert.Equal(NuGetOfficialFeedUrl, sources[0].Source);
        }

        [Fact]
        public void CtorMigrateV2LegacyFeedNameToV2Feed()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.GetSettingValues("packageSources", true))
                        .Returns(new[] { new SettingValue(NuGetLegacyOfficialFeedName, "https://nuget.org/api/v2/", false) });
            var sourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, sourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(1, sources.Count);
            Assert.Equal(NuGetOfficialFeedUrl, sources[0].Source);
            Assert.Equal(NuGetOfficialFeedName, sources[0].Name);
        }

        [Fact]
        public void CtorMigratesEvenCaseDoesNotMatch()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.GetSettingValues("packageSources", true))
                        .Returns(new[] { new SettingValue("NuGET oFFIcial PACKAGE souRCe", "HTTPS://nUGet.org/ApI/V2/", false) });
            var sourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, sourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(1, sources.Count);
            Assert.Equal(NuGetOfficialFeedUrl, sources[0].Source);
            Assert.Equal(NuGetOfficialFeedName, sources[0].Name);
        }

        // Test that when there are non-machine wide user specified sources, the
        // official source is added but disabled.
        [Fact]
        public void DefaultSourceAddedButDisabled()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.GetSettingValues("packageSources", true))
                        .Returns(new[] {
                            new SettingValue("Test1", "https://test1", true),
                            new SettingValue("Test2", "https://test2", false)
                        });
            var sourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, sourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(3, sources.Count);

            Assert.Equal("https://test2", sources[0].Source);

            Assert.Equal(NuGetOfficialFeedUrl, sources[1].Source);
            Assert.False(sources[1].IsEnabled);

            Assert.Equal("https://test1", sources[2].Source);
        }

        // Test that when there are machine wide user specified sources, but no non-machine
        // wide user specified sources, then the official source is added and ENABLED.
        [Fact]
        public void DefaultSourceAddedAndEnabled()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.GetSettingValues("packageSources", true))
                        .Returns(new[] {
                            new SettingValue("Test1", "https://test1", true),
                            new SettingValue("Test2", "https://test2", true)
                        });
            var sourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, sourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(3, sources.Count);
            Assert.Equal(NuGetOfficialFeedUrl, sources[0].Source);
            Assert.True(sources[0].IsEnabled);
        }

        [Fact]
        public void LoadPackageSourcesAddOfficialSourceIfMissing()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.GetSettingValues("packageSources", true))
                        .Returns(new[] { new SettingValue("my source", "http://www.nuget.org", false) });
            var sourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, sourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(2, sources.Count);
            AssertPackageSource(sources[0], "my source", "http://www.nuget.org");
            AssertPackageSource(sources[1], NuGetOfficialFeedName, NuGetOfficialFeedUrl);
            Assert.False(sources[1].IsEnabled);
            Assert.True(sources[1].IsOfficial);
        }

        [Fact]
        public void CtorMigrateV1FeedToV2FeedAndPreserveIsEnabledProperty()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.GetSettingValues("packageSources", true))
                        .Returns(new[] { new SettingValue(NuGetLegacyOfficialFeedName, "https://go.microsoft.com/fwlink/?LinkID=206669", false) });

            // disable the official source
            userSettings.Setup(s => s.GetValues("disabledPackageSources"))
                        .Returns(new[] { new KeyValuePair<string, string>(NuGetLegacyOfficialFeedName, "true") });

            var provider = new VsPackageSourceProvider(userSettings.Object, CreateDefaultSourceProvider(userSettings.Object), new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(1, sources.Count);
            Assert.Equal(NuGetOfficialFeedUrl, sources[0].Source);
            Assert.Equal(NuGetOfficialFeedName, sources[0].Name);
            Assert.False(sources[0].IsEnabled);
        }

        [Fact]
        public void PreserveActiveSourceWhileMigratingNuGetFeed()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.GetSettingValues("packageSources", true)).Returns(new[]
            {
                new SettingValue(NuGetLegacyOfficialFeedName, "https://go.microsoft.com/fwlink/?LinkID=206669", false),
                new SettingValue("one", "onesource", false),
            });

            userSettings.Setup(s => s.GetValues("activePackageSource"))
                        .Returns(new[] { new KeyValuePair<string, string>("one", "onesource") });

            var provider = new VsPackageSourceProvider(userSettings.Object, CreateDefaultSourceProvider(userSettings.Object), new Mock<IVsShellInfo>().Object);

            // Act
            var activeSource = provider.ActivePackageSource;

            // Assert
            AssertPackageSource(activeSource, "one", "onesource");
        }

        [Fact]
        public void CtorAddsAggregrateIfNothingWasPersistedIntoSettingsManager()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(1, sources.Count);
            Assert.Equal(NuGetOfficialFeedName, sources[0].Name);
        }

        [Fact]
        public void MigrateActivePackageSourceToV2()
        {
            // Arrange
            var settings = new Mock<ISettings>();
            settings.Setup(s => s.GetValue("activePackageSource", NuGetLegacyOfficialFeedName))
                    .Returns("https://go.microsoft.com/fwlink/?LinkID=206669");
            var provider = new VsPackageSourceProvider(settings.Object, CreateDefaultSourceProvider(settings.Object), new Mock<IVsShellInfo>().Object);

            // Act
            PackageSource activePackageSource = provider.ActivePackageSource;

            // Assert
            AssertPackageSource(activePackageSource, NuGetOfficialFeedName, NuGetOfficialFeedUrl);
        }

        [Fact]
        public void SetActivePackageSourcePersistsItToSettingsManager()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            userSettings.Setup(s => s.SetValue("activePackageSource", "name", "source")).Verifiable();

            var packageSourceProvider = new Mock<IPackageSourceProvider>();
            packageSourceProvider.Setup(s => s.LoadPackageSources())
                                 .Returns(new[] { new PackageSource("source", "name"), new PackageSource("source1", "name1") });
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, new Mock<IVsShellInfo>().Object);

            // Act
            provider.ActivePackageSource = new PackageSource("source", "name");

            // Assert
            userSettings.Verify();
        }

        [Fact]
        public void SettingActivePackageSourceToNonExistantSourceThrows()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            ExceptionAssert.ThrowsArgumentException(() => provider.ActivePackageSource = new PackageSource("a", "a"), "value",
                "The package source does not belong to the collection of available sources.");
        }

        [Fact]
        public void SettingsWithMoreThanOneAggregateSourceAreModifiedToNotHaveOne()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = CreateDefaultSourceProvider(userSettings.Object);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider, new Mock<IVsShellInfo>().Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(1, sources.Count);
            Assert.Equal(NuGetOfficialFeedName, sources[0].Name);
        }

        [Fact]
        public void GetActivePackageSourceWillPreserveWindows8ExpressSourceWhenRunningWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>(MockBehavior.Strict);
            userSettings.Setup(_ => _.GetSettingValues("packageSources", true)).Returns(new[]
            {
                new SettingValue(NuGetOfficialFeedName, NuGetOfficialFeedUrl, false)
            });
            userSettings.Setup(_ => _.GetValues("activePackageSource")).Returns(new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("Windows 8 Packages", NuGetConstants.VSExpressForWindows8FeedUrl)
            });

            var packageSourceProvider = new Mock<IPackageSourceProvider>();
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);

            // Act
            var source = provider.ActivePackageSource;

            // Assert
            AssertPackageSource(source, "Windows 8 Packages", NuGetConstants.VSExpressForWindows8FeedUrl);
        }

        [Fact]
        public void SetActivePackageSourceAcceptsValueForWindows8FeedWhenRunningWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>(MockBehavior.Strict);
            var packageSourceProvider = new Mock<IPackageSourceProvider>();
            packageSourceProvider.Setup(_ => _.LoadPackageSources()).Returns(new[]
            {
                new PackageSource("theFirstSource", "theFirstFeed"),
                new PackageSource(NuGetOfficialFeedUrl, NuGetOfficialFeedName),
                new PackageSource("theThirdSource", "theThirdFeed"),
            });

            userSettings.Setup(_ => _.GetValues("activePackageSource")).Returns(new[]
            {
                new KeyValuePair<string, string>("theFirstFeed", "theFirstSource")
            });
            userSettings.Setup(_ => _.DeleteSection("activePackageSource")).Returns(true);
            userSettings.Setup(_ => _.SetValue("activePackageSource", "Windows 8 packages", NuGetConstants.VSExpressForWindows8FeedUrl)).Verifiable();

            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);

            // Act
            provider.ActivePackageSource = new PackageSource(NuGetConstants.VSExpressForWindows8FeedUrl, "Windows 8 packages");

            // Assert
            userSettings.Verify();
        }

        [Fact]
        public void TheDisabledStateOfWindows8FeedIsPersistedWhenRunningOnWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = new Mock<IPackageSourceProvider>();

            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);
            packageSourceProvider.Setup(p => p.DisablePackageSource(It.IsAny<PackageSource>())).Callback<PackageSource>(
                ps => AssertPackageSource(ps, "Windows 8 Packages", NuGetConstants.VSExpressForWindows8FeedUrl));

            // Act
            var packageSources = new PackageSource[]
            {
                new PackageSource(NuGetConstants.VSExpressForWindows8FeedUrl, "Windows 8 packages", isEnabled: false, isOfficial: true),
                new PackageSource("theFirstSource", "theFirstFeed", isEnabled: true)
            };
            provider.SavePackageSources(packageSources);

            // Assert
            packageSourceProvider.Verify(p => p.DisablePackageSource(It.IsAny<PackageSource>()), Times.Once());
        }

        [Fact]
        public void TheEnabledStateOfWindows8FeedIsNotPersistedWhenRunningOnWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = new Mock<IPackageSourceProvider>();

            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);

            // Act
            var packageSources = new PackageSource[]
            {
                new PackageSource(NuGetConstants.VSExpressForWindows8FeedUrl, "Windows 8 packages", isEnabled: true, isOfficial: true)
            };
            provider.SavePackageSources(packageSources);

            // Assert
            packageSourceProvider.Verify(p => p.DisablePackageSource(It.IsAny<PackageSource>()), Times.Never());
        }

        [Fact]
        public void TheEnabledStateOfWindows8FeedIsRestoredWhenRunningOnWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = new Mock<IPackageSourceProvider>();
            packageSourceProvider.Setup(_ => _.LoadPackageSources()).Returns(new PackageSource[]
                {
                    new PackageSource("source", "name"),
                    new PackageSource("theFirstSource", "theFirstFeed", isEnabled: true)
                });

            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);
            packageSourceProvider.Setup(p => p.IsPackageSourceEnabled(
                                                It.Is<PackageSource>(ps => ps.Name.Equals("Windows 8 packages", StringComparison.OrdinalIgnoreCase))))
                                 .Returns(false);

            // Act
            var packageSources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(3, packageSources.Count);
            AssertPackageSource(packageSources[0], "Windows 8 Packages", NuGetConstants.VSExpressForWindows8FeedUrl);
            Assert.False(packageSources[0].IsEnabled);
        }

        [Fact]
        public void SetActivePackageSourceToWindows8FeedWillThrowWhenNotRunningWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = new Mock<IPackageSourceProvider>();
            packageSourceProvider.Setup(_ => _.LoadPackageSources()).Returns(new[]
            {
                new PackageSource("theFirstSource", "theFirstFeed"),
                new PackageSource("theOfficialSource", "NuGet official source"),
                new PackageSource("theThirdSource", "theThirdFeed"),
            });
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(false);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);

            // Act & Assert
            ExceptionAssert.ThrowsArgumentException(
                () => provider.ActivePackageSource = new PackageSource(NuGetConstants.VSExpressForWindows8FeedUrl, "Windows 8 packages"),
                "value",
                "The package source does not belong to the collection of available sources.");
        }

        [Fact]
        public void LoadPackageSourcesWillAddTheWindows8SourceAtTheFrontWhenRunningWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = new Mock<IPackageSourceProvider>();
            packageSourceProvider.Setup(_ => _.LoadPackageSources()).Returns(new[]
            {
                new PackageSource("theFirstSource", "theFirstFeed"),
                new PackageSource(NuGetOfficialFeedUrl, NuGetOfficialFeedName),
                new PackageSource("theThirdSource", "theThirdFeed"),
            });
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(4, sources.Count);
            AssertPackageSource(sources[0], "Windows 8 Packages", NuGetConstants.VSExpressForWindows8FeedUrl);
            AssertPackageSource(sources[1], "theFirstFeed", "theFirstSource");
            AssertPackageSource(sources[2], NuGetOfficialFeedName, NuGetOfficialFeedUrl);
            AssertPackageSource(sources[3], "theThirdFeed", "theThirdSource");
        }

        [Fact]
        public void LoadPackageSourcesWillNotAddTheWindows8SourceWhenNotRunningWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = new Mock<IPackageSourceProvider>();
            packageSourceProvider.Setup(_ => _.LoadPackageSources()).Returns(new[]
            {
                new PackageSource("theFirstSource", "theFirstFeed"),
                new PackageSource(NuGetOfficialFeedUrl, NuGetOfficialFeedName),
                new PackageSource("theThirdSource", "theThirdFeed"),
            });
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(false);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(3, sources.Count);
            AssertPackageSource(sources[0], "theFirstFeed", "theFirstSource");
            AssertPackageSource(sources[1], NuGetOfficialFeedName, NuGetOfficialFeedUrl);
            AssertPackageSource(sources[2], "theThirdFeed", "theThirdSource");
        }

        [Fact]
        public void SavePackageSourcesWillNotSaveTheWindows8ExpressFeedWhenRunningWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = new Mock<IPackageSourceProvider>();
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);

            IList<PackageSource> savedSources = null;
            packageSourceProvider.Setup(_ => _.SavePackageSources(It.IsAny<IEnumerable<PackageSource>>()))
                                 .Callback((IEnumerable<PackageSource> _) => savedSources = _.ToList())
                                 .Verifiable();

            // Act
            provider.SavePackageSources(new[]
                {
                    new PackageSource("theFirstSource", "theFirstFeed"),
                    new PackageSource(NuGetOfficialFeedUrl + "curated-feeds/windows8-packages/", "Windows 8 Packages"){ IsOfficial = true },
                    new PackageSource("theThirdSource", "theThirdFeed"),
                });

            // Assert
            Assert.NotNull(savedSources);
            Assert.Equal(2, savedSources.Count);
            AssertPackageSource(savedSources[0], "theFirstFeed", "theFirstSource");
            AssertPackageSource(savedSources[1], "theThirdFeed", "theThirdSource");
        }

        [Fact]
        public void SavePackageSourcesWillSaveTheWindows8ExpressFeedWhenNotRunningWindows8Express()
        {
            // Arrange
            var userSettings = new Mock<ISettings>();
            var packageSourceProvider = new Mock<IPackageSourceProvider>();
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(false);
            var provider = new VsPackageSourceProvider(userSettings.Object, packageSourceProvider.Object, vsShellInfo.Object);

            IList<PackageSource> savedSources = null;
            packageSourceProvider.Setup(_ => _.SavePackageSources(It.IsAny<IEnumerable<PackageSource>>()))
                                 .Callback((IEnumerable<PackageSource> _) => savedSources = _.ToList())
                                 .Verifiable();

            // Act
            provider.SavePackageSources(new[]
                {
                    new PackageSource("theFirstSource", "theFirstFeed"),
                    new PackageSource(NuGetOfficialFeedUrl + "curated-feeds/windows8-packages/", "Windows 8 Packages"){ IsOfficial = true },
                    new PackageSource("theThirdSource", "theThirdFeed"),
                });

            // Assert
            Assert.NotNull(savedSources);
            Assert.Equal(3, savedSources.Count);
            AssertPackageSource(savedSources[0], "theFirstFeed", "theFirstSource");
            AssertPackageSource(savedSources[1], "Windows 8 Packages", NuGetOfficialFeedUrl + "curated-feeds/windows8-packages/");
            AssertPackageSource(savedSources[2], "theThirdFeed", "theThirdSource");
        }

        private static void AssertPackageSource(PackageSource ps, string name, string source)
        {
            Assert.Equal(name, ps.Name);
            Assert.Equal(source, ps.Source);
        }

        private static PackageSourceProvider CreateDefaultSourceProvider(ISettings settings)
        {
            return new PackageSourceProvider(settings, VsPackageSourceProvider.DefaultSources, VsPackageSourceProvider.FeedsToMigrate, configurationDefaultSources: null);
        }
    }
}


text:
import { uiModules } from 'ui/modules';
import watcherWizardAddIndex from './watcher_wizard_add_index';

const module = uiModules.get('apps/sentinl');
module.directive('watcherWizardAddIndex', watcherWizardAddIndex);


text:
import React from "react";
import { shallow } from "enzyme";
import styles from "../styles";
import GobiernoAragon from "../gobierno-aragon-logo.svg";

import Footer from "../index";
import FooterSection from "../FooterSection";

describe("<Footer />", () => {
  it("should render the logos", () => {
    const renderedComponent = shallow(<Footer docked={true} />);
    expect(renderedComponent.find("img").length).toEqual(2);
  });

  it("should render Arasaac Logo", () => {
    const renderedComponent = shallow(<Footer docked={true} />);
    expect(
      renderedComponent.contains(
        <img alt="Arasaac Logo" style={styles.logoGA} src={GobiernoAragon} />
      )
    ).toEqual(true);
  });

  it("should render a FooterSection", () => {
    const renderedComponent = shallow(<Footer docked={true} />);
    expect(renderedComponent.type()).toEqual(FooterSection);
  });

  it("should accept {docked:true} prop", () => {
    const docked = true;
    const renderedComponent = shallow(<Footer docked={docked} />);
    expect(renderedComponent.prop("docked")).toEqual(docked);
  });
  it("should accept {docked:false} prop", () => {
    const docked = false;
    const renderedComponent = shallow(<Footer docked={docked} />);
    expect(renderedComponent.prop("docked")).toEqual(docked);
  });
});


text:
<?php
/**
 * Created by PhpStorm.
 * User: robingodart
 * Date: 03/01/2014
 * Time: 00:48
 */

namespace YourBooks\UserBundle\Form\Type;

use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseType;

class ProfileFormType extends BaseType
{
    public function buildUserForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildUserForm($builder, $options);

        $builder
            ->add('firstname', null, array('label' => 'form.firstname', 'translation_domain' => 'FOSUserBundle'))
            ->add('lastname', null, array('label' => 'form.lastname', 'translation_domain' => 'FOSUserBundle'))
            ->add('phone', null, array('label' => 'form.phone', 'translation_domain' => 'FOSUserBundle'))
            ->add('dateOfBirth', 'birthday', array('label' => 'form.dateOfBirth', 'translation_domain' => 'FOSUserBundle'))
            ->add('biography', 'textarea', array('label' => 'form.biography', 'translation_domain' => 'FOSUserBundle'))
            ->add('street', null, array('label' => 'form.street', 'translation_domain' => 'FOSUserBundle'))
            ->add('zipcode', null, array('label' => 'form.zipcode', 'translation_domain' => 'FOSUserBundle'))
            ->add('city', 'text', array('label' => 'form.city', 'translation_domain' => 'FOSUserBundle'))
        ;
    }

    public function addAuthorFields(FormBuilderInterface $builder)
    {
        $builder
            ->add('phone', null, array('label' => 'form.phone', 'translation_domain' => 'FOSUserBundle'))
            ->add('dateOfBirth', 'birthday', array('label' => 'form.dateOfBirth', 'translation_domain' => 'FOSUserBundle'))
            ->add('biography', 'textarea', array('label' => 'form.biography', 'translation_domain' => 'FOSUserBundle'))
            ->add('street', null, array('label' => 'form.street', 'translation_domain' => 'FOSUserBundle'))
            ->add('zipcode', null, array('label' => 'form.zipcode', 'translation_domain' => 'FOSUserBundle'))
            ->add('city', 'text', array('label' => 'form.city', 'translation_domain' => 'FOSUserBundle'))
        ;

        return $builder;
    }

    public function getName()
    {
        return 'yourbooks_user_profile';
    }
}


text:
#ifndef _RU_DUPELIM_CONST_H_
#define _RU_DUPELIM_CONST_H_

/* -*-C++-*-
******************************************************************************
*
* File:         RuDupElimConst.h
* Description:  Definition of class CRUDupElimConst
*
* Created:      06/12/2000
* Language:     C++
*
*
******************************************************************************
*/

#include "refresh.h"

//--------------------------------------------------------------------------//
//	CRUDupElimConst
//
//	This class is rather a namespace.
//
//	It contains the definitions of the constants common to
//	the classes that implement the duplicate elimination
//	algorithm.
//
//--------------------------------------------------------------------------//

class REFRESH_LIB_CLASS CRUDupElimConst {

public:
	// @OPERATION_TYPE bitmaps
	enum
	{
		IS_DELETE			= 0x1,
		IS_PART_OF_UPDATE	= 0x2,
		IS_RANGE_RECORD		= 0x4,
		IS_BEGIN_RANGE		= 0x8
	};

public:
	// Types of the queries to compute the delta
	enum {

		// Query for the first txn (no lower bound)
		PHASE_0_QUERY	= 0,
		// Query for the following txns (with lower bound)
		PHASE_1_QUERY	= 1,

		NUM_QUERY_STMTS
	};

	// The maximum number of epochs for optimizable query
	enum { MAX_SELECT_CLAUSES = 10 };

public:
	// Types of the Insert/Update/Delete statements
	// to be applied to the range log and the IUD log
	// by the range resolver
	enum {

		// Insert a new record to the range-log
		RANGE_LOG_INSERT			= 0,
		// Delete a subset of records from the range-log
		RANGE_LOG_DELETE			= 1,
		// Delete a subset of records from the IUD-log
		IUD_LOG_SUBSET_DELETE		= 2,
		// Update the @IGNORE column
		// in a subset of records in the IUD-log
		IUD_LOG_SUBSET_UPDATE_IGNORE = 3,
		// Update the @IGNORE column to the max-int number
		// These rows will always be ignored
		IUD_LOG_SUBSET_UPDATE_ALWAYS_IGNORE = 4,
		NUM_RNG_RESOLV_STMTS
	};

	// Control statements that force/reset the MDAM
	// optimization in the access to the IUD log
	// CQS stands for "control query shape", CT for "control table"
	enum {

		IUD_LOG_FORCE_MDAM_CQS	= 0,
		RNG_LOG_FORCE_MDAM_CQS	= 1,
		RESET_MDAM_CQS	= 2,

		FORCE_MDAM_CT	= 3,
		RESET_MDAM_CT	= 4,

		NUM_CONTROL_STMTS
	};

public:
	// Types of the Insert/Update/Delete statements
	// to be applied to the IUD log by the single-row resolver
	enum {
		// Delete a single record from the IUD-log
		IUD_LOG_SINGLE_DELETE			= 0,
		// Update the @IGNORE column of a single record
		IUD_LOG_SINGLE_UPDATE_IGNORE	= 1,
		// Update the @UPDATE_BITMAP column of all the
		// "update" records in the chain
		IUD_LOG_UPDATE_BITMAP			= 2,
		// Reset the Update bit in the @OPERATION_TYPE column
		// of all the "update" records in the chain
		IUD_LOG_UPDATE_OPTYPE		= 3,

		NUM_SINGLE_RESOLV_STMTS
	};

public:
	// Order between the control (@) columns in the query select list
	enum {

		OFS_EPOCH	= 0,
		OFS_OPTYPE	= 1,
		OFS_RNGSIZE	= 2,
		// Optional columns, required only for DE level = 3
		OFS_IGNORE	= 3,
		OFS_UPD_BMP	= 4,

		NUM_IUD_LOG_CONTROL_COLS_BASIC  = 3,	// DE level=1/2
		NUM_IUD_LOG_CONTROL_COLS_EXTEND = 5		// DE level=3
	};

	// The number of control (@...) columns in the range log
	enum { NUM_RNG_LOG_CONTROL_COLS = 3 };
};

#endif


text:
<?php

/**
 * A representer which will represent a HTTP API Problem
 * as a JSON or XML document.
 *
 * See: https://tools.ietf.org/html/rfc7807
 *
 * Supported internet media types (MIMEs):
 *
 *     application/problem+json q=1.0 [advertised,default]
 *     application/json         q=1.0
 *     application/problem+xml  q=1.0 [advertised]
 *     application/xml          q=1.0
 *     text/json                q=0.9
 *     text/x-json              q=0.9
 *     text/xml                 q=0.9
 *     * / *                    q=0.001
 */
class ProblemRepresenter extends BasicRepresenter {

	/** @ignore */
	public function __construct() {
		parent::__construct(
			array(
				new InternetMediaType('application', 'problem+json',     1.0, TRUE),
				new InternetMediaType('application', 'problem+xml',      1.0, TRUE),
				new InternetMediaType('application', 'api-problem+json'), // from early draft specs
				new InternetMediaType('application', 'api-problem+xml'),  // from early draft specs
				new InternetMediaType('application', 'json',   0.5), # note: these are relatively low because they also represent
				new InternetMediaType('application', 'xml',    0.5), # hopefully-200OK responses, and I really want to lean towards
				new InternetMediaType('text',        'json',   0.4), # different content-types for Ok vs Problem responses
				new InternetMediaType('text',        'x-json', 0.4),
				new InternetMediaType('text',        'xml',    0.4),
				new InternetMediaType('*', '*', 1.0, FALSE, 'application/problem+json'),
			),
			array(),
			array(),
			array('object:Problem')
		);
	}

	/** @ignore */
	public function rep($m, $d, $t, $c, $l, $response) {
		// web browser hack because argh!
		if ($t['media-range']  == '*/*' && ($ua=Request::header('User-Agent')) && strpos($ua,'curl')===false) {
			$t['media-range']  = 'text/xml';
		}

		$response->allow_not_modified = false;
		$response->allow_auto_etag = false;
		$response->nocache();

		$response->status( $m->status() );
		$this->response_type($response, $t, NULL, TRUE, TRUE); // NULL charset because blarflrf
		$this->response_language($response, 'en', FALSE, TRUE); // ???force language???

		switch (strtolower($t['media-range'])) {
		case 'application/problem+json':
		case 'application/api-problem+json':
		case 'application/json':
		case 'text/json':
		case 'text/x-json':
		case '*/*':
			$response->body( json_encode($m->to_array()) );
			break;
		case 'application/problem+xml':
		case 'application/api-problem+xml':
		case 'application/xml':
		case 'text/xml':
			$response->body( $this->xml($m->to_array()) );
			break;
		default:
			throw new InternalServerErrorException("cannot represent ".get_class($m)." as '{$t}'");
		}
	}

	protected function xml($array) {
		$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet href="/assets/problem.xsl" type="text/xsl" ?>
<problem xmlns="urn:ietf:rfc:7807">';
		foreach ($array as $k=>$v) {
			#$k = htmlspecialchars($k);
			$v = htmlspecialchars($v);
			$xml .= "<$k>$v</$k>";
		}
		$xml .= '</problem>';
		return $xml;
	}
}


text:
class Group < ActiveRecord::Base
  has_many :users, inverse_of: :group, dependent: :restrict_with_error
  has_many :group_offerings, dependent: :restrict_with_error
  has_many :offers, through: :group_offerings, dependent: :restrict_with_error
end


text:
<?php
namespace Workflow\Execution\Router\Exception;

class ProcessRouterException extends \RuntimeException {

}


text:
<?php
namespace metastore;

/**
 * Autogenerated by Thrift Compiler (0.16.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
use Thrift\Base\TBase;
use Thrift\Type\TType;
use Thrift\Type\TMessageType;
use Thrift\Exception\TException;
use Thrift\Exception\TProtocolException;
use Thrift\Protocol\TProtocol;
use Thrift\Protocol\TBinaryProtocolAccelerated;
use Thrift\Exception\TApplicationException;

class HiveObjectRef
{
    static public $isValidate = false;

    static public $_TSPEC = array(
        1 => array(
            'var' => 'objectType',
            'isRequired' => false,
            'type' => TType::I32,
            'class' => '\metastore\HiveObjectType',
        ),
        2 => array(
            'var' => 'dbName',
            'isRequired' => false,
            'type' => TType::STRING,
        ),
        3 => array(
            'var' => 'objectName',
            'isRequired' => false,
            'type' => TType::STRING,
        ),
        4 => array(
            'var' => 'partValues',
            'isRequired' => false,
            'type' => TType::LST,
            'etype' => TType::STRING,
            'elem' => array(
                'type' => TType::STRING,
                ),
        ),
        5 => array(
            'var' => 'columnName',
            'isRequired' => false,
            'type' => TType::STRING,
        ),
        6 => array(
            'var' => 'catName',
            'isRequired' => false,
            'type' => TType::STRING,
        ),
    );

    /**
     * @var int
     */
    public $objectType = null;
    /**
     * @var string
     */
    public $dbName = null;
    /**
     * @var string
     */
    public $objectName = null;
    /**
     * @var string[]
     */
    public $partValues = null;
    /**
     * @var string
     */
    public $columnName = null;
    /**
     * @var string
     */
    public $catName = null;

    public function __construct($vals = null)
    {
        if (is_array($vals)) {
            if (isset($vals['objectType'])) {
                $this->objectType = $vals['objectType'];
            }
            if (isset($vals['dbName'])) {
                $this->dbName = $vals['dbName'];
            }
            if (isset($vals['objectName'])) {
                $this->objectName = $vals['objectName'];
            }
            if (isset($vals['partValues'])) {
                $this->partValues = $vals['partValues'];
            }
            if (isset($vals['columnName'])) {
                $this->columnName = $vals['columnName'];
            }
            if (isset($vals['catName'])) {
                $this->catName = $vals['catName'];
            }
        }
    }

    public function getName()
    {
        return 'HiveObjectRef';
    }

    public function read($input)
    {
        $xfer = 0;
        $fname = null;
        $ftype = 0;
        $fid = 0;
        $xfer += $input->readStructBegin($fname);
        while (true) {
            $xfer += $input->readFieldBegin($fname, $ftype, $fid);
            if ($ftype == TType::STOP) {
                break;
            }
            switch ($fid) {
                case 1:
                    if ($ftype == TType::I32) {
                        $xfer += $input->readI32($this->objectType);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                case 2:
                    if ($ftype == TType::STRING) {
                        $xfer += $input->readString($this->dbName);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                case 3:
                    if ($ftype == TType::STRING) {
                        $xfer += $input->readString($this->objectName);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                case 4:
                    if ($ftype == TType::LST) {
                        $this->partValues = array();
                        $_size58 = 0;
                        $_etype61 = 0;
                        $xfer += $input->readListBegin($_etype61, $_size58);
                        for ($_i62 = 0; $_i62 < $_size58; ++$_i62) {
                            $elem63 = null;
                            $xfer += $input->readString($elem63);
                            $this->partValues []= $elem63;
                        }
                        $xfer += $input->readListEnd();
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                case 5:
                    if ($ftype == TType::STRING) {
                        $xfer += $input->readString($this->columnName);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                case 6:
                    if ($ftype == TType::STRING) {
                        $xfer += $input->readString($this->catName);
                    } else {
                        $xfer += $input->skip($ftype);
                    }
                    break;
                default:
                    $xfer += $input->skip($ftype);
                    break;
            }
            $xfer += $input->readFieldEnd();
        }
        $xfer += $input->readStructEnd();
        return $xfer;
    }

    public function write($output)
    {
        $xfer = 0;
        $xfer += $output->writeStructBegin('HiveObjectRef');
        if ($this->objectType !== null) {
            $xfer += $output->writeFieldBegin('objectType', TType::I32, 1);
            $xfer += $output->writeI32($this->objectType);
            $xfer += $output->writeFieldEnd();
        }
        if ($this->dbName !== null) {
            $xfer += $output->writeFieldBegin('dbName', TType::STRING, 2);
            $xfer += $output->writeString($this->dbName);
            $xfer += $output->writeFieldEnd();
        }
        if ($this->objectName !== null) {
            $xfer += $output->writeFieldBegin('objectName', TType::STRING, 3);
            $xfer += $output->writeString($this->objectName);
            $xfer += $output->writeFieldEnd();
        }
        if ($this->partValues !== null) {
            if (!is_array($this->partValues)) {
                throw new TProtocolException('Bad type in structure.', TProtocolException::INVALID_DATA);
            }
            $xfer += $output->writeFieldBegin('partValues', TType::LST, 4);
            $output->writeListBegin(TType::STRING, count($this->partValues));
            foreach ($this->partValues as $iter64) {
                $xfer += $output->writeString($iter64);
            }
            $output->writeListEnd();
            $xfer += $output->writeFieldEnd();
        }
        if ($this->columnName !== null) {
            $xfer += $output->writeFieldBegin('columnName', TType::STRING, 5);
            $xfer += $output->writeString($this->columnName);
            $xfer += $output->writeFieldEnd();
        }
        if ($this->catName !== null) {
            $xfer += $output->writeFieldBegin('catName', TType::STRING, 6);
            $xfer += $output->writeString($this->catName);
            $xfer += $output->writeFieldEnd();
        }
        $xfer += $output->writeFieldStop();
        $xfer += $output->writeStructEnd();
        return $xfer;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <label>Gender</label>
    <name>Gender__c</name>
    <picklistValues>
        <masterLabel>Decline to State</masterLabel>
        <translation>Decline to State</translation>
    </picklistValues>
    <picklistValues>
        <masterLabel>Female</masterLabel>
        <translation>Female</translation>
    </picklistValues>
    <picklistValues>
        <masterLabel>Male</masterLabel>
        <translation>Male</translation>
    </picklistValues>
</CustomFieldTranslation>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBitcoin;
using Nethereum.RLP;
using Stratis.SmartContracts.Core.Receipts;
using Xunit;

namespace Stratis.SmartContracts.Core.Tests.Receipts
{
    public class ReceiptSerializationTest
    {
        [Fact]
        public void Log_Serializes_And_Deserializes()
        {
            var data = new byte[] { 1, 2, 3, 4 };
            var topics = new List<byte[]>
            {
                Encoding.UTF8.GetBytes("ALogStructName"),
                BitConverter.GetBytes(123)
            };
            var log = new Log(new uint160(1234), topics, data);

            byte[] serialized = log.ToBytesRlp();
            Log deserialized = Log.FromBytesRlp(serialized);
            TestLogsEqual(log, deserialized);
        }

        [Fact]
        public void Receipt_Serializes_And_Deserializes()
        {
            var data1 = new byte[] { 1, 2, 3, 4 };
            var topics1 = new List<byte[]>
            {
                Encoding.UTF8.GetBytes("ALogStructName"),
                BitConverter.GetBytes(123)
            };
            var log1 = new Log(new uint160(1234), topics1, data1);

            var data2 = new byte[] { 4, 5, 6, 7 };
            var topics2 = new List<byte[]>
            {
                Encoding.UTF8.GetBytes("ALogStructName2"),
                BitConverter.GetBytes(234)
            };
            var log2 = new Log(new uint160(12345), topics2, data2);

            var receipt = new Receipt(new uint256(1234), 12345, new Log[] { log1, log2 });
            TestConsensusSerialize(receipt);
            receipt = new Receipt(receipt.PostState, receipt.GasUsed, receipt.Logs, new uint256(12345), new uint160(25), new uint160(24), new uint160(23), true, null, null, 54321, 1_000_000) { BlockHash = new uint256(1234) };
            TestStorageSerialize(receipt);

            // Test cases where either the sender or contract is null - AKA CALL vs CREATE
            receipt = new Receipt(receipt.PostState, receipt.GasUsed, receipt.Logs, new uint256(12345), new uint160(25), new uint160(24), null, true, "Test Result", "Test Error Message", 54321, 1_000_000, "TestMethodName") { BlockHash = new uint256(1234) };
            TestStorageSerialize(receipt);
            receipt = new Receipt(receipt.PostState, receipt.GasUsed, receipt.Logs, new uint256(12345), new uint160(25), null, new uint160(23), true, "Test Result 2", "Test Error Message 2", 54321, 1_000_000) { BlockHash = new uint256(1234) };
            TestStorageSerialize(receipt);
        }

        [Fact]
        public void Receipt_With_No_MethodName_Deserializes_Correctly()
        {
            var receipt = new Receipt(new uint256(1234), 12345, new Log[]{}, new uint256(12345), new uint160(25), new uint160(24), null, true, "Test Result", "Test Error Message", 54321, 1_000_000) { BlockHash = new uint256(1234) };

            byte[] serialized = ToStorageBytesRlp_NoMethodName(receipt);

            Receipt deserialized = Receipt.FromStorageBytesRlp(serialized);
            TestStorageReceiptEquality(receipt, deserialized);
        }

        private void TestConsensusSerialize(Receipt receipt)
        {
            byte[] serialized = receipt.ToConsensusBytesRlp();
            Receipt deserialized = Receipt.FromConsensusBytesRlp(serialized);
            Assert.Equal(receipt.PostState, deserialized.PostState);
            Assert.Equal(receipt.GasUsed, deserialized.GasUsed);
            Assert.Equal(receipt.Bloom, deserialized.Bloom);
            Assert.Equal(receipt.Logs.Length, deserialized.Logs.Length);

            for(int i=0; i < receipt.Logs.Length; i++)
            {
                TestLogsEqual(receipt.Logs[i], deserialized.Logs[i]);
            }
        }

        private void TestStorageSerialize(Receipt receipt)
        {
            byte[] serialized = receipt.ToStorageBytesRlp();
            Receipt deserialized = Receipt.FromStorageBytesRlp(serialized);
            TestStorageReceiptEquality(receipt, deserialized);
        }

        /// <summary>
        /// Serializes a receipt without including the method name. For backwards compatibility testing.
        /// </summary>
        /// <param name="receipt"></param>
        /// <returns></returns>
        public byte[] ToStorageBytesRlp_NoMethodName(Receipt receipt)
        {
            IList<byte[]> encodedLogs = receipt.Logs.Select(x => RLP.EncodeElement(x.ToBytesRlp())).ToList();

            return RLP.EncodeList(
                RLP.EncodeElement(receipt.PostState.ToBytes()),
                RLP.EncodeElement(BitConverter.GetBytes(receipt.GasUsed)),
                RLP.EncodeElement(receipt.Bloom.ToBytes()),
                RLP.EncodeElement(RLP.EncodeList(encodedLogs.ToArray())),
                RLP.EncodeElement(receipt.TransactionHash.ToBytes()),
                RLP.EncodeElement(receipt.BlockHash.ToBytes()),
                RLP.EncodeElement(receipt.From.ToBytes()),
                RLP.EncodeElement(receipt.To?.ToBytes()),
                RLP.EncodeElement(receipt.NewContractAddress?.ToBytes()),
                RLP.EncodeElement(BitConverter.GetBytes(receipt.Success)),
                RLP.EncodeElement(Encoding.UTF8.GetBytes(receipt.Result ?? "")),
                RLP.EncodeElement(Encoding.UTF8.GetBytes(receipt.ErrorMessage ?? "")),
                RLP.EncodeElement(BitConverter.GetBytes(receipt.GasPrice)),
                RLP.EncodeElement(BitConverter.GetBytes(receipt.Amount))
            );
        }

        /// <summary>
        /// Ensures 2 receipts and all their properties are equal.
        /// </summary>
        public static void TestStorageReceiptEquality(Receipt receipt1, Receipt receipt2)
        {
            Assert.Equal(receipt1.PostState, receipt2.PostState);
            Assert.Equal(receipt1.GasUsed, receipt2.GasUsed);
            Assert.Equal(receipt1.Bloom, receipt2.Bloom);
            Assert.Equal(receipt1.Logs.Length, receipt2.Logs.Length);

            for (int i = 0; i < receipt1.Logs.Length; i++)
            {
                TestLogsEqual(receipt1.Logs[i], receipt2.Logs[i]);
            }

            Assert.Equal(receipt1.TransactionHash, receipt2.TransactionHash);
            Assert.Equal(receipt1.BlockHash, receipt2.BlockHash);
            Assert.Equal(receipt1.From, receipt2.From);
            Assert.Equal(receipt1.To, receipt2.To);
            Assert.Equal(receipt1.NewContractAddress, receipt2.NewContractAddress);
            Assert.Equal(receipt1.Success, receipt2.Success);
            Assert.Equal(receipt1.ErrorMessage, receipt2.ErrorMessage);
            Assert.Equal(receipt1.MethodName, receipt2.MethodName);
        }

        private static void TestLogsEqual(Log log1, Log log2)
        {
            Assert.Equal(log1.Address, log2.Address);
            Assert.Equal(log1.Data, log2.Data);
            Assert.Equal(log1.Topics.Count, log2.Topics.Count);
            for(int i=0; i < log1.Topics.Count; i++)
            {
                Assert.Equal(log1.Topics[i], log2.Topics[i]);
            }
        }
    }
}


text:
package org.javaee7.jsf.passthrough;

import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

/**
 * @author Arun Gupta
 */
@Named
@SessionScoped
public class UserBean implements Serializable {
    private String name;
    private int age;
    private String email;
    private String blog;
    private String tel;
    private String dob;
    private String color;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getBlog() {
        return blog;
    }

    public void setBlog(String blog) {
        this.blog = blog;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}


text:
namespace DefaultNamespace
{
    using System;
    class JITcrash
    {
        public
        static
        int Main(String[] args)
        {
            UInt32 x = (0xFFFFFFFF);
            Int64 y = x;

            //	just added few cases of WriteLine
            Console.WriteLine("Running test");
            Console.WriteLine("x = " + x);
            Console.WriteLine("x = " + x + ".");
            Console.WriteLine("x = " + x + " y = " + y + ".");
            Console.WriteLine("Test passed.");
            return 100;
        }
    }
}


text:
#ifndef THREAD_DISCOVERY_H_
#define THREAD_DISCOVERY_H_

struct protocol_interface_info_entry;

/* Structure that discovery_response_list_t */
typedef struct discovery_additional_info {
    uint8_t domain_name[16];
    uint16_t ae_port;
    uint16_t nmk_port;
    bool ccm_supported: 1;
} discovery_additional_info_t;

typedef struct discovery_response_list {
    discovery_additional_info_t ccm_info;
    uint8_t network_name[16];
    uint8_t steering_data[16];
    uint8_t extented_pan_id[8];
    uint8_t extented_mac[8];
    uint16_t pan_id;
    uint16_t joiner_port;
    uint16_t commissioner_port;
    uint8_t channel;
    int8_t dbm;
    unsigned version: 4;
    unsigned steering_data_valid: 5;

    ns_list_link_t link;
} discovery_response_list_t;

typedef struct {
    uint64_t active_timestamp;
    uint16_t pan_id;
    uint8_t  channel;
} announce_discovery_response_t;

typedef NS_LIST_HEAD(discovery_response_list_t, link) thread_nwk_discovery_response_list_t;

typedef struct {
    uint8_t *extented_pan_id;
    uint8_t *network_name;
    uint16_t pan_id;
    unsigned version: 4;
} discover_server_info_t;

/**
 * Thread network discovery
 */
typedef struct {
    uint32_t channel_mask;
    bool joiner_flag: 1;
    bool native_commisioner; //Set for native commisioner
    uint8_t filter_tlv_length; //Optional Filter data length
    uint8_t *filter_tlv_data; //Pointer for filter specific data
} thread_discover_reques_t;

/**
 * Thread network discovery
 */
typedef struct {
    uint64_t active_timestamp;
    uint32_t channel_mask;
    uint16_t pan_id;
} thread_announce_discover_reques_t;

/**
 *  Thread discovery ready callback
 *
 *
 *  \param cur_interface Interface pointer
 *  \param discover_response discovery response list (linked list)
 */
typedef void (thread_discovery_ready_cb)(struct protocol_interface_info_entry *cur_interface, thread_nwk_discovery_response_list_t *discover_response);

/**
 *  Thread Orphan nwk discovery ready callback
 *
 *
 *  \param cur_interface Interface pointer
 *  \param nwk discovery response list (linked list)
 */
typedef void (thread_announce_scan_ready_cb)(struct protocol_interface_info_entry *cur_interface, announce_discovery_response_t *discover_response);

/**
 * Init discovery service
 */
int thread_discovery_init(int8_t interface_id, struct protocol_interface_info_entry *cur_interface, uint8_t version, bool reedDevice);

/**
 * Reset discovery class state to idle
 */
int thread_discovery_reset(int8_t interface_id);

/**
 * Enable thread discovery request response support
 */
int thread_discovery_responser_enable(int8_t interface_id, bool enable_service);

/**
 * Start Thread network discovery
 */
int thread_discovery_network_scan(struct protocol_interface_info_entry *cur_interface, thread_discover_reques_t *scan_request, thread_discovery_ready_cb *ready_cb);

/**
 * Start device orphan scan
 */
int thread_discovery_announce_network_scan(int8_t interface_id, thread_announce_discover_reques_t *scan_request, thread_announce_scan_ready_cb *ready_cb);

/**
 * Get primary network from discovered list
 */
discovery_response_list_t *thread_discovery_network_description_get(int8_t interface_id);

#if 0
/**
 * Free all allocated memory and free class
 * Not used API function, flagged away. This should be taken in use when refactoring ifdown - functionality.
 */
int thread_discovery_free(int8_t interface_id);
#endif
#endif /* THREAD_DISCOVERY_H_ */


text:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

import { ConfigHttpService } from './config-http.service';

@Injectable()
export class ConfigService {
    protected logo: BehaviorSubject<string> = new BehaviorSubject<string>(null);
    protected title: BehaviorSubject<string> = new BehaviorSubject<string>(null);
    protected footer: BehaviorSubject<string> = new BehaviorSubject<string>(null);

    private config: object;

    constructor(protected service: ConfigHttpService) {
        this.service.getConfig().subscribe((data: object) => {
            this.config = data;
            this.logo.next(data['logo']);
            this.title.next(data['title']);
            this.footer.next(data['footer']);
        });
    }

    public getFooter(): Subject<string>  {
        return this.footer;
    }

    public getLogo(): Subject<string>  {
        return this.logo;
    }

    public getEventTitle(): Subject<string> {
        return this.title;
    }
}


text:
<!doctype html>

        <base href="../../" target="_blank">

		<meta charset="utf-8">

		<title>The America's Cup</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/coderus.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

What is it?

Yacht sailing race first held in 1851

No regular schedule

Currently held by Oracle Team USA

The 2017 America's Cup

35th time the contest has been held

Surrounded in controversy

Will be held in Bermuda

Challenger to be decided by qualifying races

The America's Cup World Series

Race in a smaller AC45

Chance to gather data

Held all around the world, next races are in Toulon

Race Format

The Boat

Fixed Sail Wing and Foiling

Sailing Upwind

Sailing Upwind

Why is the America's Cup Interesting?

Questions


text:
<?php

namespace ZF2rapid\Task\Display;

use Zend\Console\ColorInterface as Color;
use Zend\Version\Version;
use ZFrapidCore\Task\AbstractTask;

/**
 * Class ZFVersion
 *
 * @package ZF2rapid\Task\Display
 */
class ZFVersion extends AbstractTask
{
    /**
     * Process the command
     *
     * @return integer
     */
    public function processCommandTask()
    {
        $workingPath = $this->params->workingPath;

        if (is_dir(
            $workingPath . '/vendor/zendframework/zendframework/library'
        )) {
            $library = '/vendor/zendframework/zendframework/library';
        } elseif (is_dir(
            $workingPath . '/vendor/zendframework/zend-version'
        )) {
            $library = '/vendor/zendframework/zend-version';
        } elseif (is_dir($workingPath . '/vendor/ZF2/library')) {
            $library = '/vendor/ZF2/library';
        } else {
            $library = false;
        }

        // set version file name
        $versionFile = $workingPath . $library . '/Zend/Version/Version.php';

        // check for individual Zend\Version repository
        if (!file_exists($versionFile)) {
            $versionFile = $workingPath . $library . '/src/Version.php';
        }

        // load version file
        require_once $versionFile;

        // output success message
        $this->console->writeTaskLine(
            'task_display_zfversion_path',
            [
                $this->console->colorize(
                    $workingPath . $library, Color::GREEN
                )
            ]
        );

        $this->console->writeIndentedLine(
            'task_display_zfversion_version',
            [
                $this->console->colorize(
                    $workingPath, Color::GREEN
                ),
                $this->console->colorize(
                    Version::VERSION, Color::BLUE
                )
            ]
        );

        return 0;
    }

}


text:
package org.spongepowered.api.data.manipulator.immutable.entity;

import org.spongepowered.api.data.manipulator.ImmutableDataManipulator;
import org.spongepowered.api.data.manipulator.mutable.entity.BreathingData;
import org.spongepowered.api.data.value.immutable.ImmutableBoundedValue;
import org.spongepowered.api.entity.Entity;

/**
 * An {@link ImmutableDataManipulator} representing the current "air" quantity
 * that an {@link Entity} can have while "under water".
 */
public interface ImmutableBreathingData extends ImmutableDataManipulator<ImmutableBreathingData, BreathingData> {

    /**
     * Gets the {@link ImmutableBoundedValue} for the remaining air. Can be
     * changed to {@code (air >= 0 && air <= maxAir)}.
     *
     * @return The immutable value of remaining air
     */
    ImmutableBoundedValue<Integer> remainingAir();

    /**
     * Gets the {@link ImmutableBoundedValue} for the maximum air capacity.
     * The reasoning for it being bounded is that the air capacity must always
     * remain at least 1.
     *
     * @return The immutable bounded value of maximum air capacity
     */
    ImmutableBoundedValue<Integer> maxAir();

}


text: <title>Social Tally Counter</title>


text:
package org.apache.derby.impl.sql.conn;

import org.apache.derby.iapi.services.context.Context;

import org.apache.derby.shared.common.sanity.SanityManager;

import org.apache.derby.iapi.services.monitor.Monitor;

import org.apache.derby.iapi.services.timer.TimerFactory;

import org.apache.derby.iapi.error.StandardException;

import org.apache.derby.iapi.sql.conn.LanguageConnectionContext;
import org.apache.derby.iapi.sql.conn.StatementContext;
import org.apache.derby.iapi.sql.conn.SQLSessionContext;

import org.apache.derby.iapi.sql.depend.Dependency;
import org.apache.derby.iapi.sql.depend.DependencyManager;

import org.apache.derby.iapi.sql.execute.NoPutResultSet;

import org.apache.derby.iapi.sql.Activation;
import org.apache.derby.iapi.sql.ResultSet;
import org.apache.derby.iapi.sql.ParameterValueSet;

import org.apache.derby.iapi.services.context.ContextImpl;

import org.apache.derby.iapi.error.ExceptionSeverity;
import org.apache.derby.iapi.reference.SQLState;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TimerTask;

/**
 * GenericStatementContext is pushed/popped around a statement prepare and execute
 * so that any statement specific clean up can be performed.
 *
 *
 */
final class GenericStatementContext
	extends ContextImpl implements StatementContext
{
	private boolean		setSavePoint;
	private String		internalSavePointName;
	private ResultSet	topResultSet;
	private ArrayList<Dependency>		dependencies;
	private NoPutResultSet[] subqueryTrackingArray;
	private NoPutResultSet[] materializedSubqueries;
	private	final LanguageConnectionContext lcc;
	private boolean		inUse = true;

    // This flag satisfies all the conditions
    // for using volatile instead of synchronized.
    // (Source: Doug Lea, Concurrent Programming in Java, Second Edition,
    // section 2.2.7.4, page 97)
    // true if statement has been cancelled
    private volatile boolean cancellationFlag = false;

    // Reference to the TimerTask that will time out this statement.
    // Needed for stopping the task when execution completes before timeout.
    private CancelQueryTask cancelTask = null;

    private	boolean		parentInTrigger;	// whetherparent started with a trigger on stack
    private	boolean		isForReadOnly = false;
    private	boolean		isAtomic;
	private boolean		isSystemCode;
	private boolean		rollbackParentContext;
    private boolean     statementWasInvalidated;
    private	String		stmtText;
    private	ParameterValueSet			pvs;

	/**
		Set to one of RoutineAliasInfo.{MODIFIES_SQL_DATA, READS_SQL_DATA, CONTAINS_SQL, NO_SQL}
	*/
	private short			sqlAllowed = -1;

	/**
	 * The activation associated with this context, or null
	 */
	private Activation activation;

	/**
	 * The SQLSessionContext associated with a statement context.
	 */
	private SQLSessionContext sqlSessionContext;

	/*
	   constructor
		@param tc transaction
	*/
	GenericStatementContext(LanguageConnectionContext lcc)
	{
		super(lcc.getContextManager(), org.apache.derby.iapi.reference.ContextId.LANG_STATEMENT);
		this.lcc = lcc;

		if (SanityManager.DEBUG)
		{
			SanityManager.ASSERT((lcc != null),
					"Failed to get language connection context");
		}

        internalSavePointName = lcc.getUniqueSavepointName();
	}

    /**
     * This is a TimerTask that is responsible for timing out statements,
     * typically when an application has called Statement.setQueryTimeout().
     *
     * When the application invokes execute() on a statement object, or
     * fetches data on a ResultSet, a StatementContext object is allocated
     * for the duration of the execution in the engine (until control is
     * returned to the application).
     *
     * When the StatementContext object is assigned with setInUse(),
     * a CancelQueryTask is scheduled if a timeout > 0 has been set.
     */
    private static class CancelQueryTask
        extends
            TimerTask
    {
        /**
         * Reference to the StatementContext for the executing statement
         * which might time out.
         */
        private StatementContext statementContext;

        /**
         * Initializes a new task for timing out a statement's execution.
         * This does not schedule it for execution, the caller is
         * responsible for calling Timer.schedule() with this object
         * as parameter.
         */
        public CancelQueryTask(StatementContext ctx)
        {
            statementContext = ctx;
        }

        /**
         * Invoked by a Timer class to cancel an executing statement.
         * This method just sets a volatile flag in the associated
         * StatementContext object by calling StatementContext.cancel();
         * it is the responsibility of the thread executing the statement
         * to check this flag regularly.
         */
        public void run()
        {
            synchronized (this) {
                if (statementContext != null) {
                    statementContext.cancel();
                }
            }
        }

        /**
         * Stops this task and prevents it from cancelling a statement.
         * Guarantees that after this method returns, the associated
         * StatementContext object will not be tampered with by this task.
         * Thus, the StatementContext object may safely be allocated to
         * other executing statements.
         */
        public void forgetContext() {
            synchronized (this) {
                statementContext = null;
            }
            getTimerFactory().cancel(this);
        }
    }

    private static TimerFactory getTimerFactory() {
        return Monitor.getMonitor().getTimerFactory();
    }

	// StatementContext Interface

	public void setInUse
	(
		boolean parentInTrigger,
		boolean isAtomic,
                boolean isForReadOnly,
		String stmtText,
		ParameterValueSet pvs,
        long timeoutMillis
	)
	{
		inUse = true;

		this.parentInTrigger = parentInTrigger;
		this.isForReadOnly = isForReadOnly;
		this.isAtomic = isAtomic;
		this.stmtText = stmtText;
		this.pvs = pvs;
		rollbackParentContext = false;
        if (timeoutMillis > 0) {
            cancelTask = new CancelQueryTask(this);
            getTimerFactory().schedule(cancelTask, timeoutMillis);
        }
	}

	public void clearInUse() {
		/* We must clear out the current top ResultSet to prepare for
		 * reusing a StatementContext.
		 */
		stuffTopResultSet( null, null );
		inUse = false;

		parentInTrigger = false;
		isAtomic = false;
		isForReadOnly = false;
		this.stmtText = null;
		sqlAllowed = -1;
		isSystemCode = false;
		rollbackParentContext = false;
        statementWasInvalidated = false;

        if (cancelTask != null) {
            cancelTask.forgetContext();
            cancelTask = null;
        }
        cancellationFlag = false;
        activation = null;
		sqlSessionContext = null;
    }

	/**
	 * @see StatementContext#setSavePoint
	 * @exception StandardException Thrown on error
	 */
	public void setSavePoint() throws StandardException {

		if (SanityManager.DEBUG)
		{
			if (SanityManager.DEBUG_ON("traceSavepoints"))
			{
				SanityManager.DEBUG_PRINT(
									"GenericStatementContext.setSavePoint()",
									internalSavePointName);
			}
		}

		pleaseBeOnStack();

		lcc.getTransactionExecute().setSavePoint(internalSavePointName, null);
		setSavePoint = true;
	}

	/**
	 * Resets the savepoint to the current spot if it is
	 * set, otherwise, noop.  Used when a commit is
	 * done on a nested connection.
	 *
	 * @see StatementContext#resetSavePoint
	 * @exception StandardException Thrown on error
	 */
	public void resetSavePoint() throws StandardException {
		if (SanityManager.DEBUG)
		{
			if (SanityManager.DEBUG_ON("traceSavepoints"))
			{
				SanityManager.DEBUG_PRINT(
					"GenericStatementContext.resetSavePoint()",
					internalSavePointName);
			}
		}

		if (inUse && setSavePoint)
		{
			// RESOLVE PLUGIN ???. For the plugin, there will be no transaction controller
			lcc.getTransactionExecute().setSavePoint(internalSavePointName, null);
			// stage buffer management
		}
	}

	/**
	 * @see StatementContext#clearSavePoint
	 * @exception StandardException Thrown on error
	 */
	public void clearSavePoint() throws StandardException {

		if (SanityManager.DEBUG)
		{
			if (SanityManager.DEBUG_ON("traceSavepoints"))
			{
				SanityManager.DEBUG_PRINT("GenericStatementContext.clearSavePoint()",
										  internalSavePointName);
			}
		}

		pleaseBeOnStack();

		if (SanityManager.DEBUG)
		{
			SanityManager.ASSERT(setSavePoint, "setSavePoint is expected to be true");
		}

		// RESOLVE PLUGIN ???. For the plugin, there will be no transaction controller
		lcc.getTransactionExecute().releaseSavePoint(internalSavePointName, null);
		setSavePoint = false;
	}

	/**
	 * Set the top ResultSet in the ResultSet tree for close down on
	 * an error.
	 *
	 * @exception StandardException thrown on error.
	 */
	public void setTopResultSet(ResultSet topResultSet,
							    NoPutResultSet[] subqueryTrackingArray)
		 throws StandardException
	{
		pleaseBeOnStack();

		/* We have to handle both materialize and non-materialized subqueries.
		 * Materialized subqueries are attached before the top result set is
		 * set.  If there are any, then we must copy them into the new
		 * subqueryTrackingArray.
		 */
		if (materializedSubqueries != null)
		{
			// Do the merging into the passed in array.
			if (subqueryTrackingArray != null)
			{
				if (SanityManager.DEBUG)
				{
					if (this.materializedSubqueries.length != subqueryTrackingArray.length)
					{
						SanityManager.THROWASSERT(
							"this.ms.length (" + this.materializedSubqueries.length +
							") expected to = sta.length(" + subqueryTrackingArray.length +
							")");
					}
				}
				for (int index = 0; index < subqueryTrackingArray.length; index++)
				{
                    if (this.materializedSubqueries[index] != null)
					{
						subqueryTrackingArray[index] = this.materializedSubqueries[index];
					}
				}
			}
			else
			{
				subqueryTrackingArray = this.materializedSubqueries;
			}
			materializedSubqueries = null;
		}

		stuffTopResultSet( topResultSet, subqueryTrackingArray );
	}

	/**
	  *	Private minion of setTopResultSet() and clearInUse()
	  *
	  *	@param	topResultSet	make this the top result set
	  *	@param	subqueryTrackingArray	where to keep track of subqueries in this statement
	  */
	private	void	stuffTopResultSet(ResultSet topResultSet,
									  NoPutResultSet[] subqueryTrackingArray)
	{
		this.topResultSet = topResultSet;
		this.subqueryTrackingArray = subqueryTrackingArray;
		dependencies = null;
	}

	/**
	 * Set the appropriate entry in the subquery tracking array for
	 * the specified subquery.
	 * Useful for closing down open subqueries on an exception.
	 *
	 * @param subqueryNumber	The subquery # for this subquery
	 * @param subqueryResultSet	The ResultSet at the top of the subquery
	 * @param numSubqueries		The total # of subqueries in the entire query
	 *
	 * @exception StandardException thrown on error.
	 */
	public void setSubqueryResultSet(int subqueryNumber,
									 NoPutResultSet subqueryResultSet,
									 int numSubqueries)
		throws StandardException
	{
		pleaseBeOnStack();

		/* NOTE: In degenerate cases, it is possible that there is no top
		 * result set.  For example:
		 *		call (select 1 from systables).valueOf('111');
		 * In that case, we allocate our own subquery tracking array on
		 * each call. (Gross!)
		 * (Trust me, this is only done in degenerate cases.  The tests passed,
		 * except for the degenerate cases, before making this change, so we
		 * know that the top result set and array reuse is working for
		 * the non-degenerate cases.)
		 */
		if (subqueryTrackingArray == null)
		{
			if (topResultSet == null)
			{
				subqueryTrackingArray = new NoPutResultSet[numSubqueries];
				materializedSubqueries = new NoPutResultSet[numSubqueries];
			}
			else
			{
				subqueryTrackingArray =
					topResultSet.getSubqueryTrackingArray(numSubqueries);
			}
		}
		subqueryTrackingArray[subqueryNumber] = subqueryResultSet;
		if (materializedSubqueries != null)
		{
			materializedSubqueries[subqueryNumber] = subqueryResultSet;
		}
	}

	/**
	 * Get the subquery tracking array for this query.
	 * (Useful for runtime statistics.)
	 *
	 * @return NoPutResultSet[]	The	(sparse) array of tops of subquery ResultSet trees
	 * @exception StandardException thrown on error.
	 */
	public NoPutResultSet[] getSubqueryTrackingArray()
		throws StandardException
	{
		pleaseBeOnStack();

		return subqueryTrackingArray;
	}

	/**
	 * Track a Dependency within this StatementContext.
	 * (We need to clear any dependencies added within this
	 * context on an error.
	 *
	 * @param dy	The dependency to track.
	 *
	 * @exception StandardException thrown on error.
	 */
	public void addDependency(Dependency dy)
		throws StandardException
	{
		pleaseBeOnStack();

		if (dependencies == null)
		{
			dependencies = new ArrayList<Dependency>();
		}
		dependencies.add(dy);
	}

	/**
	 * Returns whether we started from within the context of a trigger
	 * or not.
	 *
	 * @return	true if we are in a trigger context
	 */
	public	boolean	inTrigger()
	{
		return	parentInTrigger;
	}

	//
	// Context interface
	//
	/**
	 * Close down the top ResultSet, if relevant, and rollback to the
	 * internal savepoint, if one was set.
	 *
	 * @exception StandardException thrown on error. REVISIT: don't want
	 * cleanupOnError's to throw exceptions.
	 */
	public void cleanupOnError(Throwable error) throws StandardException
	{

		if (SanityManager.DEBUG)
		{
			if (SanityManager.DEBUG_ON("traceSavepoints"))
			{
				SanityManager.DEBUG_PRINT(
						"GenericStatementContext.cleanupOnError()",
						String.valueOf( hashCode() ) );
			}
		}

		/*
		** If it isn't a StandardException, then assume
		** session severity.  It is probably an unexpected
		** java error somewhere in the language.
        ** Store layer treats JVM error as session severity,
        ** hence to be consistent and to avoid getting rawstore
        ** protocol violation errors, we treat java errors here
        ** to be of session severity.
        */
        int severity = ExceptionSeverity.SESSION_SEVERITY;
        if (error instanceof StandardException) {
            StandardException se = (StandardException)error;
            // Update the severity.
            severity = se.getSeverity();
            // DERBY-4849: Remember that the plan was invalidated, such that
            // we can avoid performing certain actions more than once
            // (for correctness, not optimization).
            if (SQLState.LANG_STATEMENT_NEEDS_RECOMPILE.equals(
                    se.getMessageId())) {
                statementWasInvalidated = true;
            }
        }

		/**
		 * Don't clean up this statement context if it's not in use.
		 * This can happen if you get an error while calling one of
		 * the JDBC getxxxx() methods on a ResultSet, since no statement
		 * context is pushed when those calls occur.
		 */
		if (! inUse)
		{
			return;
		}

		/* Clean up the ResultSet, if one exists */
		if (topResultSet != null)
		{
			topResultSet.cleanUp();
		}

		/* Close down any open subqueries */
		if (subqueryTrackingArray != null)
		{
			for (int index = 0; index < subqueryTrackingArray.length; index++)
			{
				/* Remember, the array is sparse, so only check
				 * non-null entries.
				 */
				if (subqueryTrackingArray[index] != null)
				{
					subqueryTrackingArray[index].cleanUp();
				}
			}
		}

		/* Clean up any dependencies */
		if (dependencies != null)
		{
			DependencyManager dmgr = lcc.getDataDictionary().getDependencyManager();

			for (Iterator<Dependency> iterator = dependencies.iterator(); iterator.hasNext(); )
			{
				Dependency dy = iterator.next();
				dmgr.clearInMemoryDependency(dy);
			}

			dependencies = null;
		}

		if (severity <= ExceptionSeverity.STATEMENT_SEVERITY
			&& setSavePoint)
		{
			if (SanityManager.DEBUG)
			{
				if (SanityManager.DEBUG_ON("traceSavepoints"))
				{
					SanityManager.DEBUG_PRINT(
						"GenericStatementContext.cleanupOnError",
						"rolling back to: " + internalSavePointName);
				}
			}

			lcc.internalRollbackToSavepoint( internalSavePointName, false, null);

			clearSavePoint();
		}

		if (severity >= ExceptionSeverity.TRANSACTION_SEVERITY )
		{
			// transaction severity errors roll back the transaction.

			/*
			** We call clearSavePoint() above only for statement errors.
			** We don't call clearSavePoint() for transaction errors because
			** the savepoint will be rolled back anyway.  So in this case,
			** we need to indicate that the savepoint is not set.
			*/
			setSavePoint = false;
		}

		/* Pop the context */
		lcc.popStatementContext(this, error);
	}

	/**
	 * @see Context#isLastHandler
	 */
	public boolean isLastHandler(int severity)
	{
        // For JVM errors, severity gets mapped to
        // ExceptionSeverity.NO_APPLICABLE_SEVERITY
        // in ContextManager.cleanupOnError. It is necessary to
        // let outer contexts take corrective action for jvm errors, so
        // return false as this will not be the last handler for such
        // errors.
		return inUse && !rollbackParentContext &&
            ( severity == ExceptionSeverity.STATEMENT_SEVERITY );
	}

	/**
	  *	Reports whether this StatementContext is on the context stack.
	  *
	  *	@return	true if this StatementContext is on the context stack. false otherwise.
	  */
    public	boolean	onStack() { return inUse; }

	/**
	 * Indicates whether the statement needs to be executed atomically
	 * or not, i.e., whether a commit/rollback is permitted by a
 	 * connection nested in this statement.
	 *
	 * @return true if needs to be atomic
	 */
	public boolean isAtomic()
	{
		return isAtomic;
	}

	/**
	 * Return the text of the current statement.
	 * Note that this may be null.  It is currently
	 * not set up correctly for ResultSets that aren't
	 * single row result sets (e.g SELECT), replication,
	 * and setXXXX/getXXXX jdbc methods.
	 *
	 * @return the statement text
	 */
	public String getStatementText()
	{
		return stmtText;
	}

	//
	// class implementation
	//

	/**
	  *	Raise an exception if this Context is not in use, that is, on the
	  * Context Stack.
	  *
	  * @exception StandardException thrown on error.
	  */
	private	void	pleaseBeOnStack() throws StandardException
	{
		if ( !inUse ) { throw StandardException.newException(SQLState.LANG_DEAD_STATEMENT); }
	}

	public boolean inUse()
	{
		return inUse;
	}
    public boolean isForReadOnly()
    {
	return isForReadOnly;
    }

    /**
     * Tests whether the statement which has allocated this StatementContext
     * object has been cancelled. This method is typically called from the
     * thread which is executing the statement, to test whether execution
     * should continue or stop.
     *
     * @return whether the statement which has allocated this StatementContext
     *  object has been cancelled.
     */
    public boolean isCancelled()
    {
        return cancellationFlag;
    }

    /**
     * Cancels the statement which has allocated this StatementContext object.
     * This is done by setting a flag in the StatementContext object. For
     * this to have any effect, it is the responsibility of the executing
     * statement to check this flag regularly.
     */
    public void cancel()
    {
        cancellationFlag = true;
    }

	public void setSQLAllowed(short allow, boolean force) {

		// cannot override a stricter setting.
		// -1 is no routine restriction in place
		// 0 is least restrictive
		// 4 is most
		if (force || (allow > sqlAllowed))
			sqlAllowed = allow;

	}
	public short getSQLAllowed() {
		if (!inUse)
			return org.apache.derby.catalog.types.RoutineAliasInfo.NO_SQL;

		return sqlAllowed;
	}

	/**
	 * Indicate that, in the event of a statement-level exception,
	 * this context is NOT the last one that needs to be rolled
	 * back--rather, it is nested within some other statement
	 * context, and that other context needs to be rolled back,
	 * too.
	*/
	public void setParentRollback() {
		rollbackParentContext = true;
	}

	/**
		Set to indicate statement is system code.
		For example a system procedure, view, function etc.
	*/
	public void setSystemCode() {
		isSystemCode = true;
	}

	/**
		Return true if this statement is system code.
	*/
	public boolean getSystemCode() {
		return isSystemCode;
	}

	public StringBuffer appendErrorInfo() {

		StringBuffer sb = ((ContextImpl) lcc).appendErrorInfo();
		if (sb != null) {

			sb.append("Failed Statement is: ");

			sb.append(getStatementText());

			if ((pvs != null) && pvs.getParameterCount() > 0)
			{
				String pvsString = " with " + pvs.getParameterCount() +
						" parameters " + pvs.toString();
				sb.append(pvsString);
			}
		}
		return sb;

	}

	/**
	 * @see StatementContext#setActivation(Activation a)
	 */
	public void setActivation(Activation a) {
		activation = a;
	}

	/**
	 * @see StatementContext#getActivation
	 */
	public Activation getActivation() {
		return activation;
	}

	/**
	 * @see StatementContext#getSQLSessionContext
	 */
	public SQLSessionContext getSQLSessionContext() {
		return sqlSessionContext;
	}

	/**
	 * @see StatementContext#setSQLSessionContext(SQLSessionContext ctx)
	 */
	public void setSQLSessionContext(SQLSessionContext ctx) {
		sqlSessionContext = ctx;
	}

    public boolean getStatementWasInvalidated() {
        return statementWasInvalidated;
    }
}


text:
/**
 * Es6 module for Redux Architecture.
 *
 * @file
 * @module
 *
 * @author hello@ulrichmerkel.com (Ulrich Merkel), 2021
 */

/**
 * @type {string}
 */
export const CONFIG_RESOURCE_NAME = 'config';

/**
 * @type {string}
 */
export const FETCH_CONFIG_CONTENT_REQUEST = `${CONFIG_RESOURCE_NAME}/FETCH_CONFIG_CONTENT_REQUEST`;

/**
 * @type {string}
 */
export const FETCH_CONFIG_CONTENT_FAILURE = `${CONFIG_RESOURCE_NAME}/FETCH_CONFIG_CONTENT_FAILURE`;

/**
 * @type {string}
 */
export const FETCH_CONFIG_CONTENT_SUCCESS = `${CONFIG_RESOURCE_NAME}/FETCH_CONFIG_CONTENT_SUCCESS`;

/**
 * @type {string}
 */
export const CONFIG_CONTENT_ADD = `${CONFIG_RESOURCE_NAME}/CONFIG_CONTENT_ADD`;

/**
 * @type {string}
 */
export const FETCH_CONFIG_TRANSLATION_REQUEST = `${CONFIG_RESOURCE_NAME}/FETCH_CONFIG_TRANSLATION_REQUEST`;

/**
 * @type {string}
 */
export const FETCH_CONFIG_TRANSLATION_FAILURE = `${CONFIG_RESOURCE_NAME}/FETCH_CONFIG_TRANSLATION_FAILURE`;

/**
 * @type {string}
 */
export const FETCH_CONFIG_TRANSLATION_SUCCESS = `${CONFIG_RESOURCE_NAME}/FETCH_CONFIG_TRANSLATION_SUCCESS`;

/**
 * @type {string}
 */
export const CONFIG_TRANSLATION_ADD = `${CONFIG_RESOURCE_NAME}/CONFIG_TRANSLATION_ADD`;

/**
 * @type {object}
 */
export const INITIAL_STATE = {
    content: {
        isFetching: false,
        didInvalidate: false
    }
};