text:
namespace Js
{

    class WaiterList;
    typedef JsUtil::List<DWORD_PTR, HeapAllocator> SharableAgents;
    typedef JsUtil::BaseDictionary<uint, WaiterList *, HeapAllocator> IndexToWaitersMap;

    class SharedContents
    {
    public:
        BYTE  *buffer;             // Points to a heap allocated RGBA buffer, can be null
        IndexToWaitersMap *indexToWaiterList;  // Map of agents waiting on a particular index.
        uint32 bufferLength;       // Number of bytes allocated
        uint32 maxBufferLength = 0; // Maximum number of bytes to allocate (only used by WebAssemblySharedArrayBuffer)
        bool isWebAssembly = false;
    private:
        // Addref/release counter for current buffer, this is needed as the current buffer will be shared among different workers
        long refCount;

    public:
        long AddRef();
        long Release();
        bool IsWebAssembly() const { return isWebAssembly; }
        void SetIsWebAssembly() { isWebAssembly = true; }
        static int GetBufferOffset() { return offsetof(SharedContents, buffer); }
        static int GetBufferLengthOffset() { return offsetof(SharedContents, bufferLength); }

#if DBG
        // This is mainly used for validation purpose as the wait/wake APIs should be used on the agents (Workers) among which this buffer is shared.
        SharableAgents *allowedAgents;
        CriticalSection csAgent;
        void AddAgent(DWORD_PTR agent);
        bool IsValidAgent(DWORD_PTR agent);
#endif

        void Cleanup();

        SharedContents(BYTE* b, uint32 l, uint32 m)
            : buffer(b), bufferLength(l), maxBufferLength(m), refCount(1), indexToWaiterList(nullptr)
#if DBG
            , allowedAgents(nullptr)
#endif
        {
        }
    };

    class SharedArrayBuffer : public ArrayBufferBase
    {
    public:
        DEFINE_VTABLE_CTOR_ABSTRACT(SharedArrayBuffer, ArrayBufferBase);
        SharedArrayBuffer(DynamicType * type);
        SharedArrayBuffer(SharedContents *contents, DynamicType * type);

        class EntryInfo
        {
        public:
            static FunctionInfo NewInstance;
            static FunctionInfo Slice;
            static FunctionInfo GetterByteLength;
            static FunctionInfo GetterSymbolSpecies;
        };

        static Var NewInstance(RecyclableObject* function, CallInfo callInfo, ...);
        static Var EntrySlice(RecyclableObject* function, CallInfo callInfo, ...);
        static Var EntryGetterByteLength(RecyclableObject* function, CallInfo callInfo, ...);
        static Var EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...);

        virtual BOOL GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext) override;
        virtual BOOL GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext) override;

        virtual uint32 GetByteLength() const override;
        virtual BYTE* GetBuffer() const override;

        static int GetByteLengthOffset() { Assert(false); return 0; }
        static int GetBufferOffset() { Assert(false); return 0; }
        static int GetSharedContentsOffset() { return offsetof(SharedArrayBuffer, sharedContents); }
        virtual bool IsArrayBuffer() override { return false; }
        virtual bool IsSharedArrayBuffer() override { return true; }
        virtual ArrayBuffer * GetAsArrayBuffer() { return nullptr; }
        virtual SharedArrayBuffer * GetAsSharedArrayBuffer() override;

        WaiterList *GetWaiterList(uint index);
        SharedContents *GetSharedContents() { return sharedContents; }

#if defined(TARGET_64)
        //maximum 2G -1  for amd64
        static const uint32 MaxSharedArrayBufferLength = 0x7FFFFFFF;
#else
        // maximum 1G to avoid arithmetic overflow.
        static const uint32 MaxSharedArrayBufferLength = 1 << 30;
#endif
        virtual bool IsValidVirtualBufferLength(uint length) const;

    protected:
        // maxLength is necessary only for WebAssemblySharedArrayBuffer to know how much it can grow
        // Must call after constructor of child class is completed. Required to be able to make correct virtual calls
        void Init(uint32 length, uint32 maxLength);
        virtual BYTE* AllocBuffer(uint32 length, uint32 maxLength);
        virtual void FreeBuffer(BYTE* buffer, uint32 length, uint32 maxLength);

        FieldNoBarrier(SharedContents *) sharedContents;

        static CriticalSection csSharedArrayBuffer;
    };

    template <> inline bool VarIsImpl<SharedArrayBuffer>(RecyclableObject* obj)
    {
        return JavascriptOperators::GetTypeId(obj) == TypeIds_SharedArrayBuffer;
    }

    class JavascriptSharedArrayBuffer : public SharedArrayBuffer
    {
    protected:
        DEFINE_VTABLE_CTOR(JavascriptSharedArrayBuffer, SharedArrayBuffer);
        DEFINE_MARSHAL_OBJECT_TO_SCRIPT_CONTEXT(JavascriptSharedArrayBuffer);

    public:
        static JavascriptSharedArrayBuffer* Create(uint32 length, DynamicType * type);
        static JavascriptSharedArrayBuffer* Create(SharedContents *sharedContents, DynamicType * type);
        virtual void Dispose(bool isShutdown) override;
        virtual void Finalize(bool isShutdown) override;

    protected:
        JavascriptSharedArrayBuffer(DynamicType * type);
        JavascriptSharedArrayBuffer(SharedContents *sharedContents, DynamicType * type);

    };

#ifdef ENABLE_WASM_THREADS
    class WebAssemblySharedArrayBuffer : public JavascriptSharedArrayBuffer
    {
    protected:
        DEFINE_VTABLE_CTOR(WebAssemblySharedArrayBuffer, JavascriptSharedArrayBuffer);
        DEFINE_MARSHAL_OBJECT_TO_SCRIPT_CONTEXT(WebAssemblySharedArrayBuffer);

    public:
        static WebAssemblySharedArrayBuffer* Create(uint32 length, uint32 maxLength, DynamicType * type);
        static WebAssemblySharedArrayBuffer* Create(SharedContents *sharedContents, DynamicType * type);

        virtual bool IsValidVirtualBufferLength(uint length) const override;
        virtual bool IsWebAssemblyArrayBuffer() override { return true; }
        _Must_inspect_result_ bool GrowMemory(uint32 newBufferLength);

    protected:
        virtual BYTE* AllocBuffer(uint32 length, uint32 maxLength) override;
        virtual void FreeBuffer(BYTE* buffer, uint32 length, uint32 maxLength) override;

    private:
        WebAssemblySharedArrayBuffer(DynamicType * type);
        WebAssemblySharedArrayBuffer(SharedContents *sharedContents, DynamicType * type);
        void ValidateBuffer();
    };

    template <> inline bool VarIsImpl<WebAssemblySharedArrayBuffer>(RecyclableObject* obj)
    {
        return VarIs<SharedArrayBuffer>(obj) && UnsafeVarTo<SharedArrayBuffer>(obj)->IsWebAssemblyArrayBuffer();
    }
#endif

    // An agent can be viewed as a worker
    struct AgentOfBuffer
    {
    public:
        AgentOfBuffer() :identity(NULL), event(NULL) {}
        AgentOfBuffer(DWORD_PTR agent, HANDLE e) :identity(agent), event(e) {}
        static bool AgentCanSuspend(ScriptContext *scriptContext);

        DWORD_PTR identity;
        HANDLE event;
    };

    typedef JsUtil::List<AgentOfBuffer, HeapAllocator> Waiters;
    class WaiterList
    {
    public:

        WaiterList();
        void Cleanup();

        bool _Requires_lock_held_(csForAccess.cs) AddAndSuspendWaiter(DWORD_PTR waiter, uint32 timeout);
        void RemoveWaiter(DWORD_PTR waiter);
        uint32 RemoveAndWakeWaiters(int32 count);

        CriticalSection * GetCriticalSectionForAccess() { return &csForAccess; }

    private:
        void InitWaiterList();
        bool Contains(DWORD_PTR agent);

        Waiters * m_waiters;

        // Below CS is used for synchronizing access in wait/wake API
        CriticalSection csForAccess;
    };
}


text:
package biz.webgate.example.ninja;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class NinjaSortFactory {

	private static Comparator<Ninja> m_NameComp = new NinjaComparator(NinjaSessionFacade.SORT_BY_NAME);
	private static Comparator<Ninja> m_ColorComp = new NinjaComparator(NinjaSessionFacade.SORT_BY_COLOR);

	//Sort Methode
	public static void sortNinjas(List<Ninja> lstNinjas, int sortOrder) {

		switch (sortOrder) {
		case NinjaSessionFacade.SORT_BY_NAME:
			Collections.sort(lstNinjas, m_NameComp);
			break;
		case NinjaSessionFacade.SORT_BY_COLOR:
			Collections.sort(lstNinjas, m_ColorComp);
			break;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef PINGTASK_HH
#define	PINGTASK_HH

#include "CommonTasks.hh"

class PingTask: public DefaultPingTask
{
public:
	PingTask(::Clock* clock, uint32_t period, AbstractTransmitter& transmitter);

protected:
	virtual void status_changed(LockStatus status);
};

#endif	/* PINGTASK_HH */


text:
<?php

namespace NS\SentinelBundle\Form\RotaVirus;

use NS\AceBundle\Form\DatePickerType;
use NS\SentinelBundle\Entity\RotaVirus;
use NS\SentinelBundle\Form\RotaVirus\Types\DischargeClassification;
use NS\SentinelBundle\Form\RotaVirus\Types\DischargeOutcome;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class OutcomeType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('dischargeOutcome',           DischargeOutcome::class,        ['required'=>false, 'label'=>'rotavirus-form.dischargeOutcome'])
            ->add('dischargeDate',              DatePickerType::class,          ['required'=>false, 'label'=>'rotavirus-form.dischargeDate'])
            ->add('dischargeClassification',    DischargeClassification::class, ['required'=>false,'label'=>'rotavirus-form.dischargeClassification'])
            ->add('dischargeClassOther',        null,               ['required'=>false, 'label'=>'rotavirus-form.dischargeClassOther'])
            ->add('comment',                    null,               ['required'=>false, 'label'=>'rotavirus-form.comment'])
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => RotaVirus::class
        ]);
    }
}


text:
import { expect } from 'chai';
import ReloadNodejsServerWebpackPlugin from '../src/ReloadNodejsServerWebpackPlugin';

describe('ReloadNodejsServerWebpackPlugin', () => {
  describe('options', () => {
    it('default options should be applied if the options are undefined', () => {
      const instance = new ReloadNodejsServerWebpackPlugin(undefined);

      expect(instance.options).not.to.be.undefined;
    });
  });
});


text:
const fs = require('fs');
const ko = require('knockout');
const koMapping = require('knockout-mapping');
const appViewModel = require('../app-view-model');

const template = fs.readFileSync(`${__dirname}/work-selector.html`, 'utf8');

function viewModel(params) {
  const vm = {};

  vm.workInfos = koMapping.fromJS(params.workInfos.map(info => Object.assign({ isSelected: false }, info)));

  vm.onSaveClick = () => {
    const workIdsToSave = vm.workInfos().filter(info => info.isSelected()).map(info => info.id());
    params.callback(workIdsToSave);
  };

  vm.onCancelClick = () => {
    params.callback(false);
  };

  return vm;
}

function register() {
  // Register the work-selector as a new knockout component:
  ko.components.register('av-work-selector', {
    viewModel: viewModel,
    template: template
  });
}

let isShown = false;

function show(params) {
  if (isShown) return;

  const overlay = {
    component: {
      name: 'av-work-selector',
      params: {
        workInfos: params.workInfos,
        callback: val => {
          isShown = false;
          appViewModel.appOverlays.remove(overlay);
          return params.callback && params.callback(val);
        }
      }
    },
    align: 'center',
    justify: 'center'
  }

  appViewModel.appOverlays.push(overlay);

  isShown = true;
}

module.exports = { register, show };


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.mediaservices.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Class for NoEncryption scheme. */
@Fluent
public final class NoEncryption {
    /*
     * Representing supported protocols
     */
    @JsonProperty(value = "enabledProtocols")
    private EnabledProtocols enabledProtocols;

    /**
     * Get the enabledProtocols property: Representing supported protocols.
     *
     * @return the enabledProtocols value.
     */
    public EnabledProtocols enabledProtocols() {
        return this.enabledProtocols;
    }

    /**
     * Set the enabledProtocols property: Representing supported protocols.
     *
     * @param enabledProtocols the enabledProtocols value to set.
     * @return the NoEncryption object itself.
     */
    public NoEncryption withEnabledProtocols(EnabledProtocols enabledProtocols) {
        this.enabledProtocols = enabledProtocols;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (enabledProtocols() != null) {
            enabledProtocols().validate();
        }
    }
}


text:
package nl.uva.larissa.repository.couchdb;

import static org.junit.Assert.*;

import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.List;

import nl.uva.larissa.CouchDbConnectorFactory;
import nl.uva.larissa.json.model.StatementResult;
import nl.uva.larissa.repository.DuplicateIdException;
import nl.uva.larissa.repository.StatementFilter;
import nl.uva.larissa.repository.StatementFilterUtil;
import nl.uva.larissa.repository.UnknownStatementException;
import nl.uva.larissa.repository.VoidingTargetException;
import nl.uva.larissa.repository.couchdb.CouchDbStatementRepository.QueryStrategy;

import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class ITMapQuery {
	static CouchDbStatementRepository repository;
	static HttpClient httpClient;

	private static String SERVER_URL = "http://localhost:5984";
	private static String DB_ID = "mapquerytest";

	@BeforeClass
	public static void beforeClass() throws MalformedURLException {

		httpClient = new StdHttpClient.Builder().url(SERVER_URL).build();

		repository = new CouchDbStatementRepository(
				new CouchDbConnectorFactory().createConnector(SERVER_URL,
						DB_ID, 20), new QueryResolver());
	}

	@AfterClass
	public static void afterClass() {
		repository.shutdown();
		httpClient.shutdown();
	}

	@Before
	public void createDb() {
		repository.create();
	}

	@After
	public void deleteDb() {
		httpClient.delete(SERVER_URL + "/" + DB_ID);
	}

	@Test
	public void testOrder() throws DuplicateIdException,
			VoidingTargetException, UnknownStatementException {

		List<DbKey> dbKeys = Arrays.asList(new DbKey("Aap@boom.bos", "Klimt"),
				new DbKey("Aap@boom.bos", "Aapt"), new DbKey("Aap@boom.bos",
						"Slingert"), new DbKey("Aap@boom.bos", "Klimt"));

		populateDb(dbKeys);

		testMoreQuery(dbKeys, true);
		testMoreQuery(dbKeys, false);
		testMoreQueryLimit2(dbKeys, true);
		testMoreQueryLimit2(dbKeys, false);
		testMoreUntil(dbKeys, true);
		testMoreUntil(dbKeys, false);
		testMoreSince(dbKeys, true);
		testMoreSince(dbKeys, false);
	}

	private void testMoreQuery(List<DbKey> dbKeys, boolean ascending) {
		String orderStr = ascending ? "ascending" : "descending";

		MapQuery query = new VerbRegistrationQuery();
		StatementFilter filter = new StatementFilter();

		filter.setLimit(1);
		filter.setAscending(ascending);
		StatementResult result = getResult(query, filter);

		assertEquals(1, result.getStatements().size());

		assertEquals(orderStr + " order (0)",
				id(dbKeys.get(ascending ? 0 : 3)), firstStatementId(result));

		String firstMore = result.getMore();

		assertFalse("there should be more", "".equals(firstMore));

		StatementFilter moreFilter;
		for (int i = 1; i < 3; i++) {
			moreFilter = StatementFilterUtil.fromMoreUrl(result.getMore());

			result = getResult(query, moreFilter);

			assertEquals(1, result.getStatements().size());
			assertEquals(orderStr + " order (" + i + ")",
					id(dbKeys.get(ascending ? i : 3 - i)),
					firstStatementId(result));

			assertFalse("there should be more (" + i + ")",
					"".equals(result.getMore()));
		}
		moreFilter = StatementFilterUtil.fromMoreUrl(result.getMore());

		result = getResult(query, moreFilter);

		assertEquals(1, result.getStatements().size());
		assertEquals(orderStr + " order (3)",
				id(dbKeys.get(ascending ? 3 : 0)), firstStatementId(result));
		assertEquals("", result.getMore());
	}

	private void testMoreQueryLimit2(List<DbKey> dbKeys, boolean ascending) {
		String orderStr = ascending ? "ascending" : "descending";

		MapQuery query = new VerbRegistrationQuery();
		StatementFilter filter = new StatementFilter();

		filter.setLimit(2);
		filter.setAscending(ascending);
		StatementResult result = getResult(query, filter);

		assertEquals(2, result.getStatements().size());

		assertEquals(orderStr + " order (0)",
				id(dbKeys.get(ascending ? 0 : 3)), statementId(result, 0));
		assertEquals(orderStr + " order (1)",
				id(dbKeys.get(ascending ? 1 : 2)), statementId(result, 1));

		String more = result.getMore();
		assertNotEquals("", more);

		filter = StatementFilterUtil.fromMoreUrl(result.getMore());

		result = getResult(query, filter);

		assertEquals(2, result.getStatements().size());

		assertEquals(orderStr + " order (2)",
				id(dbKeys.get(ascending ? 2 : 1)), statementId(result, 0));
		assertEquals(orderStr + " order (3)",
				id(dbKeys.get(ascending ? 3 : 0)), statementId(result, 1));

		more = result.getMore();
		assertEquals("", more);
	}

	private void testMoreUntil(List<DbKey> dbKeys, boolean ascending) {
		String orderStr = ascending ? "ascending" : "descending";

		MapQuery query = new VerbRegistrationQuery();
		StatementFilter filter = new StatementFilter();

		filter.setLimit(1);
		filter.setAscending(ascending);
		filter.setUntil(dbKeys.get(1).getStatement().getStored());
		StatementResult result = getResult(query, filter);

		assertEquals(1, result.getStatements().size());

		assertEquals(orderStr + " order (0)",
				id(dbKeys.get(ascending ? 0 : 1)), firstStatementId(result));

		String more = result.getMore();

		assertNotEquals("there should be more", "", more);

		result = getResult(query, StatementFilterUtil.fromMoreUrl(more));

		assertEquals(1, result.getStatements().size());
		assertEquals(orderStr + " order (1)",
				id(dbKeys.get(ascending ? 1 : 0)), firstStatementId(result));

		assertEquals("", result.getMore());
	}

	private void testMoreSince(List<DbKey> dbKeys, boolean ascending) {
		String orderStr = ascending ? "ascending" : "descending";

		MapQuery query = new VerbRegistrationQuery();
		StatementFilter filter = new StatementFilter();

		filter.setLimit(1);
		filter.setAscending(ascending);
		filter.setSince(dbKeys.get(1).getStatement().getStored());
		StatementResult result = getResult(query, filter);

		assertEquals(1, result.getStatements().size());

		assertEquals(orderStr + " order (0)",
				id(dbKeys.get(ascending ? 1 : 3)), firstStatementId(result));

		String more = result.getMore();

		assertNotEquals("there should be more", "", more);

		result = getResult(query, StatementFilterUtil.fromMoreUrl(more));

		assertEquals(1, result.getStatements().size());
		assertEquals(orderStr + " order (1)", id(dbKeys.get(2)),
				firstStatementId(result));

		more = result.getMore();

		assertNotEquals("there should be more", "", more);

		result = getResult(query, StatementFilterUtil.fromMoreUrl(more));

		assertEquals(1, result.getStatements().size());
		assertEquals(orderStr + " order (2)",
				id(dbKeys.get(ascending ? 3 : 1)), firstStatementId(result));

		more = result.getMore();

		assertEquals("", more);

	}

	private String statementId(StatementResult result, int i) {
		return result.getStatements().get(i).getId();
	}

	private String firstStatementId(StatementResult result) {
		return statementId(result, 0);
	}

	private String id(DbKey dbKey) {
		return dbKey.getStatement().getId();
	}

	private StatementResult getResult(StatementResultQuery query,
			StatementFilter filter) {
		return query.getQueryResult(repository.getConnector(), filter,
				QueryStrategy.NORMAL);
	}

	private void populateDb(List<DbKey> asList) throws DuplicateIdException,
			VoidingTargetException, UnknownStatementException {
		for (DbKey dbKey : asList) {
			repository.storeStatement(dbKey.getStatement());
		}
	}
}


text:
new Test.Unit.Runner((function() {
  function handle(selector, callback) {
    if (!callback) {
      callback = selector;
      selector = false;
    }
    return new Event.Handler("container", "test:event", selector, callback);
  }

  return {
    testHandlersDoNothingIfStartHasNotBeenCalled: function() {
      var fired = false;
      this.handler = handle(function() { fired = true });

      $("container").fire("test:event");
      this.assert(!fired);
    },

    testHandlersAreFiredWhenStartIsCalled: function() {
      var fired = false;
      this.handler = handle(function() { fired = true });

      this.handler.start();
      this.assert(!fired);
      $("container").fire("test:event");
      this.assert(fired);
    },

    testHandlersDoNotFireAfterStartingAndThenStopping: function() {
      var fired = 0;
      this.handler = handle(function() { fired++ });

      this.handler.start();
      this.assertEqual(0, fired);
      $("container").fire("test:event");
      this.assertEqual(1, fired);
      this.handler.stop();
      $("container").fire("test:event");
      this.assertEqual(1, fired);
    },

    testHandlersWithoutSelectorsPassTheTargetElementToCallbacks: function() {
      var span = $("container").down("span");
      this.handler = handle(function(event, element) {
        this.assertEqual(span, element);
      }.bind(this));

      this.handler.start();
      span.fire("test:event");
    },

    testHandlersWithSelectorsPassTheMatchedElementToCallbacks: function() {
      var link = $("container").down("a"), span = link.down("span");
      this.handler = handle("a", function(event, element) {
        this.assertEqual(link, element);
      }.bind(this));

      this.handler.start();
      span.fire("test:event");
    },

    testHandlersWithSelectorsDoNotCallTheCallbackIfNoMatchingElementIsFound: function() {
      var paragraph = $("container").down("p", 1), fired = false;
      this.handler = handle("a", function(event, element) { fired = true });

      this.handler.start();
      paragraph.fire("test:event");
      this.assert(!fired);
    },

    testHandlerCallbacksAreBoundToTheOriginalElement: function() {
      var span = $("container").down("span"), element;
      this.handler = handle(function() { element = this });

      this.handler.start();
      span.fire("test:event");
      this.assertEqual($("container"), element);
    },

    testCallingStartMultipleTimesDoesNotInstallMultipleObservers: function() {
      var fired = 0;
      this.handler = handle(function() { fired++ });

      this.handler.start();
      this.handler.start();
      $("container").fire("test:event");
      this.assertEqual(1, fired);
    },

    teardown: function() {
      try {
        this.handler.stop();
      } catch (e) {
      } finally {
        delete this.handler;
      }
    }
  }
})());


text:
	border-top-style: solid;
	border-top-width: 1px;
}


text:
package com.asakusafw.testdriver.core;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.ServiceLoader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.asakusafw.runtime.util.hadoop.InstallationUtil;

/**
 * Configures the current testing environment.
 * <p>
 * To configure testing environment, clients can implement this
 * and put the class name in
 * {@code META-INF/services/com.asakusafw.testdriver.core.TestingEnvironmentConfigurator}.
 * </p>
 * @since 0.6.0
 */
public abstract class TestingEnvironmentConfigurator {

    static {
        InstallationUtil.verifyFrameworkVersion();
    }

    static final Logger LOG = LoggerFactory.getLogger(TestingEnvironmentConfigurator.class);

    /**
     * The system property key of enabling this feature.
     */
    public static final String KEY_ENABLE = "asakusa.testdriver.configurator"; //$NON-NLS-1$

    /**
     * The default value of {@link #KEY_ENABLE}.
     */
    public static final String DEFAULT_ENABLE = "true"; //$NON-NLS-1$

    private static boolean initialized = false;

    /**
     * Initializes the testing environment.
     */
    public static synchronized void initialize() {
        if (initialized) {
            return;
        }
        initialized = true;
        if (isEnabled() == false) {
            LOG.info(Messages.getString("TestingEnvironmentConfigurator.infoDisabled")); //$NON-NLS-1$
            return;
        }
        LOG.debug("Loading testing environment configurators"); //$NON-NLS-1$
        Collection<TestingEnvironmentConfigurator> services = loadServices();
        for (TestingEnvironmentConfigurator service : services) {
            LOG.debug("Applying testing environment configurator: {}", service); //$NON-NLS-1$
            try {
                service.configure();
            } catch (RuntimeException e) {
                LOG.warn(MessageFormat.format(
                        Messages.getString("TestingEnvironmentConfigurator.warnFailedToApply"), //$NON-NLS-1$
                        service.getClass().getName()), e);
            }
        }
    }

    private static Collection<TestingEnvironmentConfigurator> loadServices() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null) {
            classLoader = TestingEnvironmentConfigurator.class.getClassLoader();
        }
        List<TestingEnvironmentConfigurator> results = new ArrayList<>();
        ServiceLoader<TestingEnvironmentConfigurator> loader =
                ServiceLoader.load(TestingEnvironmentConfigurator.class, classLoader);
        for (TestingEnvironmentConfigurator service : loader) {
            results.add(service);
        }
        // sort by its class name
        Collections.sort(results, (o1, o2) -> {
            String c1 = o1.getClass().getName();
            String c2 = o2.getClass().getName();
            return c1.compareTo(c2);
        });
        return results;
    }

    private static boolean isEnabled() {
        String value = System.getProperty(KEY_ENABLE, DEFAULT_ENABLE);
        return value.equals("true"); //$NON-NLS-1$
    }

    /**
     * Configures the current testing environment.
     */
    protected abstract void configure();
}


text:
import datetime

import mock
from nose import tools as nt
from django.test import RequestFactory
from django.db import transaction
from django.http import Http404
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Group, Permission
from django.core.exceptions import PermissionDenied

from framework.auth.core import Auth
from tests.base import AdminTestCase
from osf_tests.factories import (
    DraftRegistrationFactory,
    AuthUserFactory,
    ProjectFactory,
    UserFactory
)
from osf.models.registrations import DraftRegistration
from addons.osfstorage.models import OsfStorageFile, OsfStorageFileNode

from website.prereg.utils import get_prereg_schema

from admin_tests.utilities import setup_view, setup_form_view, setup_user_view
from admin_tests.pre_reg import utils

from admin.pre_reg.views import (
    DraftListView,
    DraftDetailView,
    DraftFormView,
    CheckoutCheckupView,
    CommentUpdateView,
    get_metadata_files,
    get_file_questions,
)
from admin.pre_reg.forms import DraftRegistrationForm
from osf.models.admin_log_entry import AdminLogEntry

class TestDraftListView(AdminTestCase):
    @mock.patch('website.archiver.tasks.archive')
    def setUp(self, mock_archive):
        super(TestDraftListView, self).setUp()
        self.user = AuthUserFactory()
        self.schema = utils.draft_reg_util()
        self.dr1 = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=self.schema,
            registration_metadata=utils.SCHEMA_DATA
        )
        self.dr1.submit_for_review(self.user, {}, save=True)
        self.dr2 = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=self.schema,
            registration_metadata=utils.SCHEMA_DATA
        )
        self.dr2.submit_for_review(self.user, {}, save=True)
        # Simply here to NOT be returned when get_queryset is called
        self.unsubmitted_prereg = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=self.schema,
            registration_metadata=utils.SCHEMA_DATA
        )
        self.unsubmitted_prereg.register(Auth(self.user), save=True)
        self.request = RequestFactory().get('/fake_path')
        self.plain_view = DraftListView
        self.view = setup_view(self.plain_view(), self.request)

        self.url = reverse('pre_reg:prereg')

    def test_get_queryset(self):
        res = list(self.view.get_queryset())
        nt.assert_equal(len(res), 2)
        nt.assert_false(self.unsubmitted_prereg in res)
        nt.assert_is_instance(res[0], DraftRegistration)

    def test_queryset_returns_in_order_date_submitted(self):
        created_first_submitted_second = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=self.schema,
            registration_metadata=utils.SCHEMA_DATA
        )

        created_second_submitted_first = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=self.schema,
            registration_metadata=utils.SCHEMA_DATA
        )

        nt.assert_greater(created_second_submitted_first.datetime_initiated, created_first_submitted_second.datetime_initiated)

        created_second_submitted_first.submit_for_review(self.user, {}, save=True)
        created_first_submitted_second.submit_for_review(self.user, {}, save=True)
        created_second_submitted_first.datetime_updated = created_first_submitted_second.datetime_updated + datetime.timedelta(1)

        assert created_second_submitted_first.datetime_updated > created_first_submitted_second.datetime_updated
        res = list(self.view.get_queryset())
        nt.assert_true(res[0] == created_first_submitted_second)

    def test_get_context_data(self):
        self.view.object_list = self.view.get_queryset()
        res = self.view.get_context_data()
        nt.assert_is_instance(res, dict)
        nt.assert_is_instance(res['drafts'], list)
        nt.assert_equal(len(res['drafts']), 2)

    def test_no_user_permissions_raises_error(self):
        request = RequestFactory().get(self.url)
        request.user = self.user

        with nt.assert_raises(PermissionDenied):
            self.plain_view.as_view()(request)

    def test_correct_view_permissions(self):
        view_permission = Permission.objects.get(codename='view_prereg')
        self.user.user_permissions.add(view_permission)
        self.user.save()

        request = RequestFactory().get(self.url)
        request.user = self.user

        response = self.plain_view.as_view()(request)
        nt.assert_equal(response.status_code, 200)

class TestDraftDetailView(AdminTestCase):
    def setUp(self):
        super(TestDraftDetailView, self).setUp()
        self.user = AuthUserFactory()
        schema = utils.draft_reg_util()
        self.dr1 = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=schema,
            registration_metadata=utils.SCHEMA_DATA
        )
        self.dr1.submit_for_review(self.user, {}, save=True)
        self.request = RequestFactory().get('/fake_path')
        self.plain_view = DraftDetailView
        self.view = setup_view(self.plain_view(), self.request, draft_pk=self.dr1._id)

        self.url = reverse('pre_reg:view_draft', kwargs={'draft_pk': self.dr1._id})

    @mock.patch('admin.pre_reg.views.DraftDetailView.checkout_files')
    def test_get_object(self, mock_files):
        res = self.view.get_object()
        nt.assert_is_instance(res, dict)
        nt.assert_equal(res['pk'], self.dr1._id)

    def test_no_user_permissions_raises_error(self):
        request = RequestFactory().get(self.url)
        request.user = self.user

        with nt.assert_raises(PermissionDenied):
            self.plain_view.as_view()(request, draft_pk=self.dr1._id)

    @mock.patch('admin.pre_reg.views.DraftDetailView.checkout_files')
    def test_correct_view_permissions(self, mock_files):
        view_permission = Permission.objects.get(codename='view_prereg')
        self.user.user_permissions.add(view_permission)
        self.user.save()

        request = RequestFactory().get(self.url)
        request.user = self.user

        response = self.plain_view.as_view()(request, draft_pk=self.dr1._id)
        nt.assert_equal(response.status_code, 200)

class TestDraftFormView(AdminTestCase):
    def setUp(self):
        super(TestDraftFormView, self).setUp()
        self.user = AuthUserFactory()
        self.dr1 = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=utils.draft_reg_util(),
            registration_metadata=utils.SCHEMA_DATA
        )
        self.dr1.submit_for_review(self.user, {}, save=True)
        self.dr1.flags  # sets flags if there aren't any yet.
        self.request = RequestFactory().get('/fake_path')
        self.plain_view = DraftFormView
        self.view = setup_view(self.plain_view(), self.request, draft_pk=self.dr1._id)

        self.post = RequestFactory().post('/fake_path')
        self.post.user = UserFactory()
        self.post_view = DraftFormView()
        self.form_data = {
            'notes': 'Far between',
            'proof_of_publication': 'approved',
        }
        self.url = reverse('pre_reg:view_draft', kwargs={'draft_pk': self.dr1._id})

    def test_dispatch_raise_404(self):
        view = setup_view(DraftFormView(), self.request, draft_pk='wrong')
        with nt.assert_raises(Http404):
            view.dispatch(self.request)

    def test_get_initial(self):
        self.view.draft = self.dr1
        self.view.get_initial()
        res = self.view.initial
        nt.assert_is_instance(res, dict)
        nt.assert_equal(res['notes'], self.dr1.notes)
        nt.assert_equal(res['assignee'], self.dr1.flags['assignee'])
        nt.assert_equal(res['payment_sent'], self.dr1.flags['payment_sent'])
        nt.assert_equal(res['proof_of_publication'],
                        self.dr1.flags['proof_of_publication'])

    def test_get_context_data(self):
        self.view.draft = self.dr1
        res = self.view.get_context_data()
        nt.assert_is_instance(res, dict)
        nt.assert_in('draft', res)
        nt.assert_is_instance(res['draft'], dict)
        nt.assert_in('IMMEDIATE', res)

    def test_form_valid_notes(self):
        form = DraftRegistrationForm(data=self.form_data)
        nt.assert_true(form.is_valid())
        view = setup_form_view(self.post_view, self.post, form,
                               draft_pk=self.dr1._id)
        view.draft = self.dr1
        count = AdminLogEntry.objects.count()
        with transaction.atomic():
            view.form_valid(form)
        nt.assert_equal(count, AdminLogEntry.objects.count())
        self.dr1.reload()
        nt.assert_equal(self.dr1.notes, self.form_data['notes'])

    @mock.patch('admin.pre_reg.views.DraftFormView.checkin_files')
    @mock.patch('admin.pre_reg.views.DraftRegistration.approve')
    def test_form_valid_approve(self, mock_approve, mock_files):
        self.form_data.update(approve_reject='approve')
        form = DraftRegistrationForm(data=self.form_data)
        nt.assert_true(form.is_valid())
        view = setup_form_view(self.post_view, self.post, form,
                               draft_pk=self.dr1._id)
        view.draft = self.dr1
        count = AdminLogEntry.objects.count()
        with transaction.atomic():
            view.form_valid(form)
        nt.assert_true(mock_approve.called)
        nt.assert_equal(count + 1, AdminLogEntry.objects.count())

    @mock.patch('admin.pre_reg.views.DraftFormView.checkin_files')
    @mock.patch('admin.pre_reg.views.DraftRegistration.reject')
    def test_form_valid_reject(self, mock_reject, mock_files):
        self.form_data.update(approve_reject='reject')
        form = DraftRegistrationForm(data=self.form_data)
        nt.assert_true(form.is_valid())
        view = setup_form_view(self.post_view, self.post, form,
                               draft_pk=self.dr1._id)
        view.draft = self.dr1
        count = AdminLogEntry.objects.count()
        with transaction.atomic():
            view.form_valid(form)
        nt.assert_true(mock_reject.called)
        nt.assert_equal(count + 1, AdminLogEntry.objects.count())

    def test_no_user_permissions_raises_error(self):
        request = RequestFactory().get(self.url)
        request.user = self.user

        with nt.assert_raises(PermissionDenied):
            self.plain_view.as_view()(request, draft_pk=self.dr1._id)

    def test_get_correct_view_permissions(self):
        view_permission = Permission.objects.get(codename='view_prereg')
        self.user.user_permissions.add(view_permission)
        self.user.save()

        request = RequestFactory().get(self.url)
        request.user = self.user

        response = self.plain_view.as_view()(request, draft_pk=self.dr1._id)
        nt.assert_equal(response.status_code, 200)

    def test_post_correct_view_permissions(self):
        view_permission = Permission.objects.get(codename='view_prereg')
        self.user.user_permissions.add(view_permission)
        self.user.save()

        request = RequestFactory().get(self.url)
        request.user = self.user

        response = self.plain_view.as_view()(request, draft_pk=self.dr1._id)
        nt.assert_equal(response.status_code, 200)

class TestCommentUpdateView(AdminTestCase):
    def setUp(self):
        super(TestCommentUpdateView, self).setUp()
        self.user = AuthUserFactory()
        self.dr1 = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=utils.draft_reg_util(),
            registration_metadata=utils.SCHEMA_DATA
        )
        self.dr1.submit_for_review(self.user, {}, save=True)
        self.request = RequestFactory().post('/fake_path', data={'blah': 'arg'})
        self.request.user = UserFactory()
        self.plain_view = CommentUpdateView
        self.view = setup_view(self.plain_view(), self.request, draft_pk=self.dr1._id)

        self.url = reverse('pre_reg:comment', kwargs={'draft_pk': self.dr1._id})

    @mock.patch('admin.pre_reg.views.json.loads')
    @mock.patch('admin.pre_reg.views.DraftRegistration.update_metadata')
    def test_post_comments(self, mock_json, mock_meta):
        count = AdminLogEntry.objects.count()
        self.view.post(self.request)
        nt.assert_equal(AdminLogEntry.objects.count(), count + 1)

    def test_no_user_permissions_raises_error(self):
        request = RequestFactory().get(self.url)
        request.user = self.user

        with nt.assert_raises(PermissionDenied):
            self.plain_view.as_view()(request, draft_pk=self.dr1._id)

class TestPreregFiles(AdminTestCase):
    def setUp(self):
        super(TestPreregFiles, self).setUp()
        self.prereg_user = AuthUserFactory()
        self.user = AuthUserFactory()
        self.node = ProjectFactory(creator=self.user)

        prereg_schema = get_prereg_schema()
        self.d_of_qs = {
            'q7': OsfStorageFileNode(node=self.node, name='7'),
            'q11': OsfStorageFileNode(node=self.node, name='11'),
            'q16': OsfStorageFileNode(node=self.node, name='16'),
            'q12': OsfStorageFileNode(node=self.node, name='12'),
            'q13': OsfStorageFileNode(node=self.node, name='13'),
            'q19': OsfStorageFileNode(node=self.node, name='19'),
            'q26': OsfStorageFileNode(node=self.node, name='26')
        }
        data = {}
        for q, f in self.d_of_qs.iteritems():
            guid = f.get_guid(create=True)._id
            f.save()
            if q == 'q26':
                data[q] = {
                    'comments': [],
                    'value': '26',
                    'extra': [
                        {
                            'data': {
                                'provider': 'osfstorage',
                                'path': f.path,
                            },
                            'fileId': guid,
                            'nodeId': self.node._id,
                        }
                    ]
                }
                continue
            data[q] = {
                'value': {
                    'uploader': {
                        'extra': [
                            {
                                'data': {
                                    'provider': 'osfstorage',
                                    'path': f.path,
                                },
                                'fileId': guid,
                                'nodeId': self.node._id,
                            }
                        ]
                    }
                }
            }
        self.draft = DraftRegistrationFactory(
            initiator=self.user,
            branched_from=self.node,
            registration_schema=prereg_schema,
            registration_metadata=data
        )

        self.prereg_user.save()
        self.admin_user = UserFactory()
        self.admin_user.is_superuser = True
        self.admin_user.groups.add(Group.objects.get(name='prereg_admin'))
        self.admin_user.groups.add(Group.objects.get(name='prereg_view'))
        self.admin_user.save()

    def test_checkout_checkin_files(self):
        self.draft.submit_for_review(self.user, {}, save=True)
        request = RequestFactory().get('/fake_path')
        view = DraftDetailView()
        view = setup_user_view(view, request, self.admin_user,
                               draft_pk=self.draft._id)
        view.checkout_files(self.draft)
        for q, f in self.d_of_qs.iteritems():
            f.refresh_from_db()
            nt.assert_equal(self.admin_user, f.checkout)

        view2 = DraftFormView()
        view2 = setup_view(view2, request, draft_pk=self.draft._id)
        view2.checkin_files(self.draft)

        for q, f in self.d_of_qs.iteritems():
            f.refresh_from_db()
            nt.assert_equal(None, f.checkout)

    def test_rejected_approved_checkouts(self):
        self.draft.submit_for_review(self.user, {}, save=True)

        # Test rejected does not checkout files
        self.draft.approval.state = 'rejected'
        self.draft.approval.save()

        request = RequestFactory().get('/fake_path')
        view = DraftDetailView()
        view = setup_user_view(view, request, self.admin_user,
                               draft_pk=self.draft._id)
        view.checkout_files(self.draft)

        for q, f in self.d_of_qs.iteritems():
            f.refresh_from_db()
            nt.assert_equal(None, f.checkout)

        # Test approved does not checkout files
        self.draft.approval.state = 'approved'
        self.draft.approval.save()

        request = RequestFactory().get('/fake_path')
        view = DraftDetailView()
        view = setup_user_view(view, request, self.admin_user,
                               draft_pk=self.draft._id)
        view.checkout_files(self.draft)

        for q, f in self.d_of_qs.iteritems():
            f.refresh_from_db()
            nt.assert_equal(None, f.checkout)

    def test_rejected_does_not_checkout_files(self):
        self.draft.submit_for_review(self.user, {}, save=True)
        self.draft.approval.state = 'rejected'
        self.draft.approval.save()

        request = RequestFactory().get('/fake_path')
        view = DraftDetailView()
        view = setup_user_view(view, request, self.admin_user,
                               draft_pk=self.draft._id)
        view.checkout_files(self.draft)

        for q, f in self.d_of_qs.iteritems():
            f.refresh_from_db()
            nt.assert_equal(None, f.checkout)

    def test_checkout_checkup(self):
        self.draft.submit_for_review(self.user, {}, save=True)
        request = RequestFactory().get('/fake_path')

        # Test Approved removes checkout
        self.draft.approval.state = 'approved'
        self.draft.approval.save()

        file_q7 = self.d_of_qs['q7']
        file_q7.checkout = self.admin_user
        file_q7.save()

        view = CheckoutCheckupView()
        view = setup_user_view(view, request, user=self.admin_user)
        view.delete(request, user=self.admin_user)
        file_q7.refresh_from_db()
        assert file_q7.checkout is None

        # Test Rejected removes checkout
        self.draft.approval.state = 'rejected'
        self.draft.approval.save()

        file_q7 = self.d_of_qs['q7']
        file_q7.checkout = self.admin_user
        file_q7.save()

        view = CheckoutCheckupView()
        view = setup_user_view(view, request, user=self.admin_user)
        view.delete(request, user=self.admin_user)
        file_q7.refresh_from_db()
        assert file_q7.checkout is None

        # Test Unapprove does not remove checkout
        self.draft.approval.state = 'unapproved'
        self.draft.approval.save()

        file_q7 = self.d_of_qs['q7']
        file_q7.checkout = self.admin_user
        file_q7.save()

        view = CheckoutCheckupView()
        view = setup_user_view(view, request, user=self.admin_user)
        view.delete(request, user=self.admin_user)
        file_q7.refresh_from_db()
        assert file_q7.checkout == self.admin_user

    def test_get_meta_data_files(self):
        for item in get_metadata_files(self.draft):
            nt.assert_in(type(item), [OsfStorageFile, OsfStorageFileNode])

    def test_get_file_questions(self):
        questions = get_file_questions('prereg-prize.json')
        nt.assert_equal(7, len(questions))
        nt.assert_list_equal(
            [
                (u'q7', u'Data collection procedures'),
                (u'q11', u'Manipulated variables'),
                (u'q12', u'Measured variables'),
                (u'q13', u'Indices'),
                (u'q16', u'Study design'),
                (u'q19', u'Statistical models'),
                (u'q26', u'Upload an analysis script with clear comments')
            ],
            questions
        )

    def test_file_id_missing(self):
        data = self.draft.registration_metadata
        data['q7']['value']['uploader']['extra'][0].pop('fileId')
        self.draft.update_metadata(data)
        for item in get_metadata_files(self.draft):
            nt.assert_in(type(item), [OsfStorageFile, OsfStorageFileNode])

    def test_file_id_missing_odd(self):
        data = self.draft.registration_metadata
        data['q26']['extra'][0].pop('fileId')
        self.draft.update_metadata(data)
        for item in get_metadata_files(self.draft):
            nt.assert_in(type(item), [OsfStorageFile, OsfStorageFileNode])

    def test_wrong_provider(self):
        data = self.draft.registration_metadata
        data['q7']['value']['uploader']['extra'][0]['data']['provider'] = 'box'
        self.draft.update_metadata(data)
        with nt.assert_raises(Http404):
            for item in get_metadata_files(self.draft):
                pass

    def test_wrong_provider_odd(self):
        data = self.draft.registration_metadata
        data['q26']['extra'][0]['data']['provider'] = 'box'
        self.draft.update_metadata(data)
        with nt.assert_raises(Http404):
            for item in get_metadata_files(self.draft):
                pass


text:
#pragma once

#include "../config.hpp"
#include "../arithmetic_types.hpp"
#include "../detail/linear/tvec1.hpp"

#ifdef AM_CONFIG_IMPLICIT_LINEAR_INTERFACE
	#include "../detail/linear/tvec1_interface.hpp"
#endif

namespace am {
namespace linear {

/**
	@addtogroup linear
	@{
*/
/**
	@addtogroup vector
	@{
*/
/**
	@defgroup vec1 1-dimensional vector
	@{
*/

#if (AM_CONFIG_VECTOR_TYPES) & AM_FLAG_TYPE_FLOAT
	/**
		1-dimensional floating-point vector.

		@sa AM_CONFIG_VECTOR_TYPES,
			AM_CONFIG_FLOAT_PRECISION
	*/
	using vec1 = detail::linear::tvec1<component_float>;
#endif

#if (AM_CONFIG_VECTOR_TYPES) & AM_FLAG_TYPE_INT
	/**
		1-dimensional signed integer vector.

		@sa AM_CONFIG_VECTOR_TYPES,
			AM_CONFIG_INT_PRECISION
	*/
	using ivec1 = detail::linear::tvec1<component_int>;
#endif

#if (AM_CONFIG_VECTOR_TYPES) & AM_FLAG_TYPE_UINT
	/**
		1-dimensional unsigned integer vector.

		@sa AM_CONFIG_VECTOR_TYPES,
			AM_CONFIG_UINT_PRECISION
	*/
	using uvec1 = detail::linear::tvec1<component_uint>;
#endif

/** @} */ // end of doc-group vec1
/** @} */ // end of doc-group vector
/** @} */ // end of doc-group linear

} // namespace linear
} // namespace am


text:
var gulp = require('gulp'), Builder = require('systemjs-builder');
var ts = require('gulp-typescript');
var clean = require('gulp-clean');
var server = require('gulp-develop-server');
var mocha = require('gulp-mocha');

var serverTS = ["**/*.ts", "!node_modules/**", '!bin/**'];

gulp.task('ts', ['clean'], function() {
    return gulp
        .src(serverTS, {base: './'})
        .pipe(ts({ module: 'commonjs', noImplicitAny: true }))
        .pipe(gulp.dest('./'));
});

gulp.task('bundle-angular-dependencies', function() {
    // optional constructor options
    // sets the baseURL and loads the configuration file
    var builder = new Builder('', 'systemjs.config.js');

    return builder
        .bundle('app/boot.js - [app/**/*.js]', 'path/to/put/angular.bundle.js', { minify: true})
        .then(function() {
            console.log('Build complete');
        })
        .catch(function(err) {
            console.log('Build error');
            console.log(err);
        });
});

gulp.task('clean', function () {
    return gulp
        .src([
            'app.js',
            '**/*.js',
            '**/*.js.map',
            '!node_modules/**',
            '!gulpfile.js',
            '!bin/**'
        ], {read: false})
        .pipe(clean())
});

gulp.task('load:fixtures', function (cb) {
    var load = require('./fixtures/load');
    return load.loadData(cb);
});

gulp.task('server:start', ['ts'], function() {
    server.listen({path: 'bin/www'}, function(error) {
        console.log(error);
    });
});

gulp.task('server:restart', ['ts'], function() {
    server.restart();
});

gulp.task('default', ['server:start'], function() {
    gulp.watch(serverTS, ['server:restart']);
});

gulp.task('test', ['ts', 'load:fixtures'], function() {
    return gulp
        .src('test/*.js', {read: false})
        // wait for dev server to start properly :(
        //.pipe(wait(600))
        .pipe(mocha())
        .once('error', function () {
            process.exit(1);
        })
        .once('end', function () {
            process.exit();
        });
});


text:
package com.zzn.aenote.http.sqlmap;

/**
 * linzz
 */

public class SqlMapNode {
	private String id;
	private SqlMapItem[] items;
	private String sqlTemplate;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public SqlMapItem[] getItems() {
		return items;
	}
	public void setItems(SqlMapItem[] items) {
		this.items = items;
	}
	public String getSqlTemplate() {
		return sqlTemplate;
	}
	public void setSqlTemplate(String sqlTemplate) {
		this.sqlTemplate = sqlTemplate;
	}

}


text:
package com.beyondtechnicallycorrect.pong.models.paddle;

import static org.mockito.Mockito.*;

import junit.framework.Assert;

import org.junit.Test;

import com.beyondtechnicallycorrect.pong.models.movement.MovementBehaviour;
import com.beyondtechnicallycorrect.pong.models.placeable.OverlappingBehaviour;
import com.beyondtechnicallycorrect.pong.models.placeable.Placeable;
import com.beyondtechnicallycorrect.pong.models.position.Position;
import com.beyondtechnicallycorrect.pong.models.velocity.Velocity;
import com.beyondtechnicallycorrect.pong.models.velocity.VelocityFactory;

public final class TestInternalPaddleImpl {

	@Test
	public void testGetX1() {
		final int X1 = 1;
		Position pos = new PositionStub(X1, 0, 0, 0);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, null, null, null, pos, null);
		Assert.assertEquals(X1, paddle.getX1());
	}

	@Test
	public void testGetX2() {
		final int X2 = 2;
		Position pos = new PositionStub(0, X2, 0, 0);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, null, null, null, pos, null);
		Assert.assertEquals(X2, paddle.getX2());
	}

	@Test
	public void testGetY1() {
		final int Y1 = 3;
		Position pos = new PositionStub(0, 0, Y1, 0);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, null, null, null, pos, null);
		Assert.assertEquals(Y1, paddle.getY1());
	}

	@Test
	public void testGetY2() {
		final int Y2 = 4;
		Position pos = new PositionStub(0, 0, 0, Y2);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, null, null, null, pos, null);
		Assert.assertEquals(Y2, paddle.getY2());
	}

	@Test
	public void testGetXAmountToMove() {
		final int X_AMOUNT = 1;
		Velocity vel = new VelocityStub(X_AMOUNT, 0, 0, 0);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, null, null, null, null, vel);
		Assert.assertEquals(X_AMOUNT, paddle.getXAmountToMove());
	}

	@Test
	public void testGetXFramesPerMove() {
		final int X_FRAMES = 2;
		Velocity vel = new VelocityStub(0, X_FRAMES, 0, 0);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, null, null, null, null, vel);
		Assert.assertEquals(X_FRAMES, paddle.getXFramesPerMove());
	}

	@Test
	public void testGetYAmountToMove() {
		final int Y_AMOUNT = 3;
		Velocity vel = new VelocityStub(0, 0, Y_AMOUNT, 0);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, null, null, null, null, vel);
		Assert.assertEquals(Y_AMOUNT, paddle.getYAmountToMove());
	}

	@Test
	public void testGetYFramesPerMove() {
		final int Y_FRAMES = 4;
		Velocity vel = new VelocityStub(0, 0, 0, Y_FRAMES);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, null, null, null, null, vel);
		Assert.assertEquals(Y_FRAMES, paddle.getYFramesPerMove());
	}

	@Test
	public void testSetVelocity() {
		final int X_AMOUNT = 1;
		final int X_FRAMES = 2;
		final int Y_AMOUNT = 3;
		final int Y_FRAMES = 4;
		VelocityFactory factory = new VelocityFactoryStub();
		InternalPaddle paddle =
				new InternalPaddleImpl(factory, null, null, null, null, null, null);

		paddle.setVelocity(X_AMOUNT, X_FRAMES, Y_AMOUNT, Y_FRAMES);

		Assert.assertEquals(
				"X amount should match",
				X_AMOUNT, paddle.getXAmountToMove());
		Assert.assertEquals(
				"X frames should match",
				X_FRAMES, paddle.getXFramesPerMove());
		Assert.assertEquals(
				"Y amount should match",
				Y_AMOUNT, paddle.getYAmountToMove());
		Assert.assertEquals(
				"Y frames should match",
				Y_FRAMES, paddle.getYFramesPerMove());
	}

	@Test
	public void testIsOverlapping_WhenBehaviourReturnsFalse_ShouldReturnFalse() {
		final boolean IS_OVERLAPPING = false;
		OverlappingBehaviour ob = new OverlappingBehaviourStub(IS_OVERLAPPING);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, ob, null, null, null, null, null);
		Placeable otherModel = new PlaceableStub();
		Assert.assertEquals(IS_OVERLAPPING, paddle.isOverlapping(otherModel));
	}

	@Test
	public void testIsOverlapping_WhenBehaviourReturnsTrue_ShouldReturnTrue() {
		final boolean IS_OVERLAPPING = true;
		OverlappingBehaviour ob = new OverlappingBehaviourStub(IS_OVERLAPPING);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, ob, null, null, null, null, null);
		Placeable otherModel = new PlaceableStub();
		Assert.assertEquals(IS_OVERLAPPING, paddle.isOverlapping(otherModel));
	}

	@Test
	public void testMove_ShouldCallMoveBehaviour() {
		MovementBehaviour mb = mock(MovementBehaviour.class);
		InstructionToVelocityConverter converter =
				new InstructionToVelocityConverterStub();
		PaddleInstructionGetter instruction = new PaddleInstructionGetterStub();
		Position pos = new PositionStub(0, 0, 0, 0);
		Velocity vel = new VelocityStub(0, 0, 0, 0);
		InternalPaddle paddle =
				new InternalPaddleImpl(
						null, null, mb, converter, instruction, pos, vel);
		paddle.move();
		verify(mb).move(pos, vel);
	}

	@Test
	public void testMove_ShouldUpdatePosition() {
		final int X1 = 1;
		final int X2 = 2;
		final int Y1 = 3;
		final int Y2 = 4;
		Position endingPos = new PositionStub(X1, X2, Y1, Y2);
		MovementBehaviour mb = new MovementBehaviourStub(endingPos);
		InstructionToVelocityConverter converter =
				new InstructionToVelocityConverterStub();
		PaddleInstructionGetter instruction = new PaddleInstructionGetterStub();
		InternalPaddle paddle =
				new InternalPaddleImpl(
						null, null, mb, converter, instruction, null, null);
		paddle.move();
		Assert.assertEquals("X1 should match", X1, paddle.getX1());
		Assert.assertEquals("X2 should match", X2, paddle.getX2());
		Assert.assertEquals("Y1 should match", Y1, paddle.getY1());
		Assert.assertEquals("Y2 should match", Y2, paddle.getY2());
	}

	@Test
	public void testMove_ShouldUseInstruction() {
		final int OLD_X_AMOUNT = 1;
		final int NEW_X_AMOUNT = -1;
		Velocity oldVel = new VelocityStub(OLD_X_AMOUNT, 1, 0, 1);
		Velocity newVel = new VelocityStub(NEW_X_AMOUNT, 1, 0, 1);
		MovementBehaviour mb = new MovementBehaviourStub();
		InstructionToVelocityConverter converter =
				new InstructionToVelocityConverterStub(newVel);
		PaddleInstructionGetter instruction = new PaddleInstructionGetterStub();
		InternalPaddle paddle =
				new InternalPaddleImpl(
						null, null, mb, converter, instruction, null, oldVel);
		paddle.move();
		Assert.assertEquals(NEW_X_AMOUNT, paddle.getXAmountToMove());
	}

	@Test
	public void test_WhenVelocityIsSet_ShouldNotUseInstructionNextMove() {
		final int OLD_X_AMOUNT = 1;
		final int NEW_X_AMOUNT = -1;
		Velocity oldVel = new VelocityStub(OLD_X_AMOUNT, 1, 0, 1);
		Velocity newVel = new VelocityStub(NEW_X_AMOUNT, 1, 0, 1);
		VelocityFactory velFactory = new VelocityFactoryStub();
		MovementBehaviour mb = new MovementBehaviourStub();
		InstructionToVelocityConverter converter =
				new InstructionToVelocityConverterStub(newVel);
		PaddleInstructionGetter instruction = new PaddleInstructionGetterStub();
		InternalPaddle paddle =
				new InternalPaddleImpl(
						velFactory, null, mb, converter, instruction, null, oldVel);
		paddle.setVelocity(OLD_X_AMOUNT, 1, 0, 1);
		paddle.move();
		Assert.assertEquals(OLD_X_AMOUNT, paddle.getXAmountToMove());
	}

	@Test
	public void test_WhenVelocityIsSet_ShouldUseInstructionAfterNextMove() {
		final int OLD_X_AMOUNT = 1;
		final int NEW_X_AMOUNT = -1;
		Velocity oldVel = new VelocityStub(OLD_X_AMOUNT, 1, 0, 1);
		Velocity newVel = new VelocityStub(NEW_X_AMOUNT, 1, 0, 1);
		VelocityFactory velFactory = new VelocityFactoryStub();
		MovementBehaviour mb = new MovementBehaviourStub();
		InstructionToVelocityConverter converter =
				new InstructionToVelocityConverterStub(newVel);
		PaddleInstructionGetter instruction = new PaddleInstructionGetterStub();
		InternalPaddle paddle =
				new InternalPaddleImpl(
						velFactory, null, mb, converter, instruction, null, oldVel);
		paddle.setVelocity(OLD_X_AMOUNT, 1, 0, 1);
		paddle.move();
		paddle.move();
		Assert.assertEquals(NEW_X_AMOUNT, paddle.getXAmountToMove());
	}

	@Test
	public void test_WhenVelocityIsSet_ShouldUseInstructionAfterNextTwoMoves() {
		final int OLD_X_AMOUNT = 1;
		final int NEW_X_AMOUNT = -1;
		Velocity oldVel = new VelocityStub(OLD_X_AMOUNT, 1, 0, 1);
		Velocity newVel = new VelocityStub(NEW_X_AMOUNT, 1, 0, 1);
		VelocityFactory velFactory = new VelocityFactoryStub();
		MovementBehaviour mb = new MovementBehaviourStub();
		InstructionToVelocityConverter converter =
				new InstructionToVelocityConverterStub(newVel);
		PaddleInstructionGetter instruction = new PaddleInstructionGetterStub();
		InternalPaddle paddle =
				new InternalPaddleImpl(
						velFactory, null, mb, converter, instruction, null, oldVel);
		paddle.setVelocity(OLD_X_AMOUNT, 1, 0, 1);
		paddle.move();
		paddle.move();
		paddle.move();
		Assert.assertEquals(NEW_X_AMOUNT, paddle.getXAmountToMove());
	}

	@Test
	public void testUnMove_ShouldCallUnMoveBehaviour() {
		MovementBehaviour mb = mock(MovementBehaviour.class);
		Position pos = new PositionStub(0, 0, 0, 0);
		Velocity vel = new VelocityStub(0, 0, 0, 0);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, mb, null, null, pos, vel);
		paddle.unMove();
		verify(mb).unMove(pos, vel);
	}

	@Test
	public void testUnMove_ShouldUpdatePosition() {
		final int X1 = 1;
		final int X2 = 2;
		final int Y1 = 3;
		final int Y2 = 4;
		Position startingPos = new PositionStub(X1, X2, Y1, Y2);
		String junkSoWeSetStartingPosition = "";
		MovementBehaviour mb =
				new MovementBehaviourStub(startingPos,
						junkSoWeSetStartingPosition);
		InternalPaddle paddle =
				new InternalPaddleImpl(null, null, mb, null, null, null, null);
		paddle.unMove();
		Assert.assertEquals("X1 should match", X1, paddle.getX1());
		Assert.assertEquals("X2 should match", X2, paddle.getX2());
		Assert.assertEquals("Y1 should match", Y1, paddle.getY1());
		Assert.assertEquals("Y2 should match", Y2, paddle.getY2());
	}

}


text:
layout: post
title: "Using Travis-CI with submodules"
excerpt: "How to fix those pesky \"Permission denied\" errors"
category: article
tags:
  - continuous-integration
  - git
published: true
---

### Update:

This issue seems to have been somewhat fixed; you can now ignore all submodules by setting the following in your `.travis.yml` file:

    git:
        submodules: false

You may still experience problems if you rely on some public submodules but want to ignore others. Hopefully, the developers will enhance this feature allowing us to list which submodules we want to include/skip.

### Original Issue

I recently started using [travis-ci](http://travis-ci.org) for continuous integration
testing with my various projects (mainly [FWRD](https://github.com/OldhamMade/FWRD)).
Now it's working, I'm really happy with the results; having the highlighted output
generated by my spec config shown in the output is a nice touch.

However, it was initially a pain to use. Firstly, there was no documentation on
how to use it with my preferred Python sandboxing system, zc.buildout. Secondly,
once I had the config correct, I got a weird error from the build:

    Using worker: ruby4.worker.travis-ci.org:travis-ruby-3
    $ cd ~/builds
    $ git clone --depth=100 --quiet git://github.com/OldhamMAde/FWRD.git OldhamMade/FWRD
    $ cd OldhamMade/FWRD
    $ git checkout -qf 84315504720c010cb6c92b352c9833739403368e
    $ git submodule init
    Submodule 'docs/build' (git@github.com:OldhamMade/FWRD.git) registered for path 'docs/build'
    $ git submodule update
    Cloning into docs/build...
    Warning: Permanently added 'github.com,201.10.10.201' (RSA) to the list of known hosts.
    Permission denied (publickey).
    fatal: The remote end hung up unexpectedly
    Clone of 'git@github.com:OldhamMade/FWRD.git' into submodule path 'docs/build' failed
    Done. Build script exited with: 1

A little help from the guys in the IRC channel led me to the fact that travis-ci
cannot download a submodule that isn't on a public url (`git://`, `https://`).
This causes a problem for me, since I manage my docs using a zc.buildout script
and the submodule I set-up points to the `gh-pages` branch in the repository.

The only way to get this to work for both instances is to change the url for the
submodule from `git@github.com:user/repo.git` to
`https://user@github.com/user/repo.git` - which will work fine with travis but
will require you to enter your github password if you wish to update/commit
your submodule.


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview
 * Settings dialog is used to change a Bluetooth device nickname.
 */

import '../../settings_shared_css.js';
import '//resources/cr_elements/cr_input/cr_input.m.js';

import {I18nBehavior, I18nBehaviorInterface} from '//resources/js/i18n_behavior.m.js';
import {html, mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getDeviceName} from 'chrome://resources/cr_components/chromeos/bluetooth/bluetooth_utils.js';
import {getBluetoothConfig} from 'chrome://resources/cr_components/chromeos/bluetooth/cros_bluetooth_config.js';

import {loadTimeData} from '../../i18n_setup.js';

const mojom = chromeos.bluetoothConfig.mojom;

/** @type {number} */
const MAX_INPUT_LENGTH = 32;

/**
 * @constructor
 * @extends {PolymerElement}
 * @implements {I18nBehaviorInterface}
 */
const SettingsBluetoothChangeDeviceNameDialogElementBase =
    mixinBehaviors([I18nBehavior], PolymerElement);

/** @polymer */
class SettingsBluetoothChangeDeviceNameDialogElement extends
    SettingsBluetoothChangeDeviceNameDialogElementBase {
  static get is() {
    return 'os-settings-bluetooth-change-device-name-dialog';
  }

  static get template() {
    return html`{__html_template__}`;
  }

  static get properties() {
    return {
      /**
       * @private {!chromeos.bluetoothConfig.mojom.PairedBluetoothDeviceProperties}
       */
      device: {
        type: Object,
        observer: 'onDeviceChanged_',
      },

      /** Used to reference the MAX_INPUT_LENGTH constant in HTML. */
      MAX_INPUT_LENGTH: {
        type: Number,
        value: MAX_INPUT_LENGTH,
      },

      /** @private */
      deviceName_: {
        type: String,
        value: '',
        observer: 'onDeviceNameChanged_',
      },

      /** @private */
      isInputInvalid_: {
        type: Boolean,
        value: false,
        reflectToAttribute: true,
      }
    };
  }

  /** @private */
  onDeviceChanged_() {
    this.deviceName_ = getDeviceName(this.device);
  }

  /** @private */
  onCancelClick_(event) {
    this.$.dialog.close();
  }

  /** @private */
  onDoneClick_() {
    getBluetoothConfig().setDeviceNickname(
        this.device.deviceProperties.id, this.deviceName_);
    this.$.dialog.close();
  }

  /**
   * Returns a formatted string containing the current number of characters
   * entered in the input compared to the maximum number of characters allowed.
   * @param {string} deviceName
   * @return {string}
   * @private
   */
  getInputCountString_(deviceName) {
    // minimumIntegerDigits is 2 because we want to show a leading zero if
    // length is less than 10.
    return this.i18n(
        'bluetoothChangeNameDialogInputCharCount',
        deviceName.length.toLocaleString(
            /*locales=*/ undefined, {minimumIntegerDigits: 2}),
        MAX_INPUT_LENGTH.toLocaleString());
  }

  /**
   * Observer for deviceName_ that sanitizes its value by truncating it to
   * MAX_INPUT_LENGTH. This method will be recursively called until deviceName_
   * is fully sanitized.
   * @param {string} newValue
   * @param {string} oldValue
   * @private
   */
  onDeviceNameChanged_(newValue, oldValue) {
    if (oldValue) {
      // If oldValue.length > MAX_INPUT_LENGTH, the user attempted to
      // enter more than the max limit, this method was called and it was
      // truncated, and then this method was called one more time.
      this.isInputInvalid_ = oldValue.length > MAX_INPUT_LENGTH;
    } else {
      this.isInputInvalid_ = false;
    }

    // Truncate the name to MAX_INPUT_LENGTH.
    this.deviceName_ = this.deviceName_.substring(0, MAX_INPUT_LENGTH);
  }

  /**
   * @return {boolean}
   * @private
   */
  isDoneDisabled_() {
    if (this.deviceName_ === getDeviceName(this.device)) {
      return true;
    }

    if (!this.deviceName_.length) {
      return true;
    }

    return false;
  }
}

customElements.define(
    SettingsBluetoothChangeDeviceNameDialogElement.is,
    SettingsBluetoothChangeDeviceNameDialogElement);


text:
package org.pac4j.oidc.logout;

import com.nimbusds.jwt.JWT;
import com.nimbusds.openid.connect.sdk.LogoutRequest;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.context.Pac4jConstants;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.exception.http.ForbiddenAction;
import org.pac4j.core.exception.http.RedirectionAction;
import org.pac4j.core.exception.http.FoundAction;
import org.pac4j.core.logout.LogoutActionBuilder;
import org.pac4j.core.profile.UserProfile;
import org.pac4j.core.http.ajax.AjaxRequestResolver;
import org.pac4j.core.http.ajax.DefaultAjaxRequestResolver;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.oidc.config.OidcConfiguration;
import org.pac4j.oidc.profile.OidcProfile;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * Logout action builder for OpenID Connect.
 *
 * @author Jerome Leleu
 * @since 2.0.0
 */
public class OidcLogoutActionBuilder implements LogoutActionBuilder {

    protected OidcConfiguration configuration;

    private AjaxRequestResolver ajaxRequestResolver = new DefaultAjaxRequestResolver();

    public OidcLogoutActionBuilder(final OidcConfiguration configuration) {
        CommonHelper.assertNotNull("configuration", configuration);
        this.configuration = configuration;
    }

    @Override
    public RedirectionAction getLogoutAction(final WebContext context, final UserProfile currentProfile, final String targetUrl) {
        final String logoutUrl = configuration.getLogoutUrl();
        if (CommonHelper.isNotBlank(logoutUrl) && currentProfile instanceof OidcProfile) {
            try {
                final URI endSessionEndpoint = new URI(logoutUrl);
                final JWT idToken = ((OidcProfile) currentProfile).getIdToken();

                LogoutRequest logoutRequest;
                if (CommonHelper.isNotBlank(targetUrl)) {
                    logoutRequest = new LogoutRequest(endSessionEndpoint, idToken, new URI(targetUrl), null);
                } else {
                    logoutRequest = new LogoutRequest(endSessionEndpoint, idToken);
                }

                if (ajaxRequestResolver.isAjax(context)) {
                    context.getSessionStore().set(context, Pac4jConstants.REQUESTED_URL, "");
                    context.setResponseHeader(HttpConstants.LOCATION_HEADER, logoutRequest.toURI().toString());
                    throw ForbiddenAction.INSTANCE;
                }

                return new FoundAction(logoutRequest.toURI().toString());
            } catch (final URISyntaxException e) {
                throw new TechnicalException(e);
            }
        }

        return null;
    }

    public AjaxRequestResolver getAjaxRequestResolver() {
        return ajaxRequestResolver;
    }

    public void setAjaxRequestResolver(final AjaxRequestResolver ajaxRequestResolver) {
        CommonHelper.assertNotNull("ajaxRequestResolver", ajaxRequestResolver);
        this.ajaxRequestResolver = ajaxRequestResolver;
    }
}


text:
class LatexChapterDecorator < Draper::Decorator

  def content
    # texto vazio, retornar mensagem genérica de texto vazio
    return I18n.t('empty_chapter') if object.content.nil? || object.content.empty?

    # .html_safe é essencial para evitar do & ser convertido para &
    TccService.apply_latex(object.content).html_safe
  end

  def title
    title = object.chapter_definition.title
    title.gsub('"', '') unless title.nil?

    title
  end

  def is_numbered_title
    object.chapter_definition.is_numbered_title
  end
end


text:
package org.bubblecloud.zigbee.api.cluster.impl.api.general;

import org.bubblecloud.zigbee.api.cluster.impl.api.core.Attribute;
import org.bubblecloud.zigbee.api.cluster.impl.api.core.ZCLCluster;
import org.bubblecloud.zigbee.api.cluster.impl.api.core.ZigBeeClusterException;
import org.bubblecloud.zigbee.api.cluster.impl.api.global.DefaultResponse;

/**
 * This class represent the Basic Cluster as defined by the document:

 * ZigBee Cluster Library public release version 075123r01ZB
 *
 * @author Stefano "Kismet" Lenzi
 * @author Francesco Furfari
 * @author Alessandro Giari
 * @version $LastChangedRevision: 799 $ ($LastChangedDate: 2013-08-06 19:00:05 +0300 (Tue, 06 Aug 2013) $)
 * @since 0.1.0
 */
public interface Basic extends ZCLCluster {

    static final short ID = 0x0000;
    static final String NAME = "Basic";
    static final String DESCRIPTION = "Attributes and commands for determining basic information about a device, setting user device information such as location, and enabling a device.";

    static final byte RESET_TO_FACTORY_DEFAULT_ID = 0x00;

    public Attribute getAttributeZCLVersion();

    public Attribute getAttributeApplicationVersion();

    public Attribute getAttributeStackVersion();

    public Attribute getAttributeHWVersion();

    public Attribute getAttributeManufacturerName();

    public Attribute getAttributeModelIdentifier();

    public Attribute getAttributeDateCode();

    public Attribute getPowerSource();

    public Attribute getAttributeLocationDescription();

    public Attribute getAttributePhysicalEnvironment();

    public Attribute getAttributeDeviceEnabled();

    public Attribute getAttributeAlarmMask();

    /**
     * @since 0.7.1
     */
    public Attribute getAttributeDisableLocalConfig();

    public DefaultResponse resetToFactoryDefault() throws ZigBeeClusterException;
}


text:
from __future__ import absolute_import
from ..request_local import request, Response, config, context

class test_context(object):
    """Given a WebTest application, performs a ``with`` statement using ``/_test_vars``.

    if ``app`` is ``None`` a new empty application is configured which responds 'HELLO'
    to every request.

    Entering the context a request for ``/_test_vars`` is performed such to setup the
    test variables, everything inside the with statement has a TurboGears context available
    which is then removed by a call to ``/`` at the end of the ``with`` block to reset
    the test variables.

    ``url`` parameter is provided to simulate the context as being for that url and
    ``environ`` parameter is provided to allow changing WSGI environ entries for the
    context.
    """
    def __init__(self, app, url=None, environ=None):
        if app is None:
            from webtest import TestApp
            from ..configuration.app_config import AppConfig
            app = TestApp(AppConfig(
                minimal=True,
                root_controller=lambda *args: Response('HELLO')
            ).make_wsgi_app())

        self._app = app
        self._environ = environ
        self._url = url

    def __enter__(self):
        self._app.get('/_test_vars')

        if self._url is not None:
            from webob.request import environ_from_url
            request.environ.update(environ_from_url(self._url))

        if self._environ is not None:
            request.environ.update(self._environ)

        return self._app

    def __exit__(self, exc_type, exc_val, exc_tb):
        try:
            config._pop_object()
        except AssertionError:
            pass

        try:
            context._pop_object()
        except AssertionError:
            pass


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Parser;

use Nelmio\Alice\Definition\Value\ListValue;
use Nelmio\Alice\Definition\Value\NestedValue;
use Nelmio\Alice\Definition\Value\ParameterValue;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Lexer\FakeLexer;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\LexerInterface;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Parser\TokenParser\Chainable\DummyChainableTokenParserAware;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Parser\TokenParser\FakeTokenParser;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\ParserInterface;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Token;
use Nelmio\Alice\FixtureBuilder\ExpressionLanguage\TokenType;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use ReflectionClass;

/**
 * @covers \Nelmio\Alice\FixtureBuilder\ExpressionLanguage\Parser\SimpleParser
 */
class SimpleParserTest extends TestCase
{
    public function testIsAParser()
    {
        $this->assertTrue(is_a(SimpleParser::class, ParserInterface::class, true));
    }

    public function testIsNotClonable()
    {
        $this->assertFalse((new ReflectionClass(SimpleParser::class))->isCloneable());
    }

    public function testCanBeInstantiatedWithALexerAndAParser()
    {
        new SimpleParser(new FakeLexer(), new FakeTokenParser());
    }

    public function testIfParserIsParserAwareThenItInjectsItselfToIt()
    {
        $decoratedParser = new DummyChainableTokenParserAware();
        $parser = new SimpleParser(new FakeLexer(), $decoratedParser);

        $this->assertSame($parser, $decoratedParser->parser);
    }

    public function testLexValueAndParsesEachTokenToReturnAValue()
    {
        $value = 'foo';

        $lexerProphecy = $this->prophesize(LexerInterface::class);
        $lexerProphecy->lex($value)->willReturn([
            $token1 = new Token('foo', new TokenType(TokenType::STRING_TYPE)),
            $token2 = new Token('bar', new TokenType(TokenType::VARIABLE_TYPE)),
        ]);
        /** @var LexerInterface $lexer */
        $lexer = $lexerProphecy->reveal();

        $tokenParserProphecy = $this->prophesize(TokenParserInterface::class);
        $tokenParserProphecy->parse($token1)->willReturn('parsed_foo');
        $tokenParserProphecy->parse($token2)->willReturn('parsed_bar');
        /** @var TokenParserInterface $tokenParser */
        $tokenParser = $tokenParserProphecy->reveal();

        $parser = new SimpleParser($lexer, $tokenParser);
        $parser->parse($value);

        $lexerProphecy->lex(Argument::any())->shouldHaveBeenCalledTimes(1);
        $tokenParserProphecy->parse(Argument::any())->shouldHaveBeenCalledTimes(2);
    }

    public function testIfTheLexProcessReturnsMultipleTokensThenTheValueReturnedWillBeAListValue()
    {
        $value = 'foo';

        $lexerProphecy = $this->prophesize(LexerInterface::class);
        $lexerProphecy->lex($value)->willReturn([
            $token1 = new Token('foo', new TokenType(TokenType::STRING_TYPE)),
            $token2 = new Token('bar', new TokenType(TokenType::VARIABLE_TYPE)),
        ]);
        /** @var LexerInterface $lexer */
        $lexer = $lexerProphecy->reveal();

        $tokenParserProphecy = $this->prophesize(TokenParserInterface::class);
        $tokenParserProphecy->parse($token1)->willReturn(new ParameterValue('parsed_foo'));
        $tokenParserProphecy->parse($token2)->willReturn('parsed_bar');
        /** @var TokenParserInterface $tokenParser */
        $tokenParser = $tokenParserProphecy->reveal();

        $parser = new SimpleParser($lexer, $tokenParser);
        $parsedValue = $parser->parse($value);

        $this->assertEquals(
            new ListValue([
                new ParameterValue('parsed_foo'),
                'parsed_bar',
            ]),
            $parsedValue
        );
    }

    public function testIfOnlyOneTokensFoundThenReturnsASimpleValue()
    {
        $value = 'foo';

        $lexerProphecy = $this->prophesize(LexerInterface::class);
        $lexerProphecy->lex($value)->willReturn([
            $token1 = new Token('foo', new TokenType(TokenType::STRING_TYPE)),
        ]);
        /** @var LexerInterface $lexer */
        $lexer = $lexerProphecy->reveal();

        $tokenParserProphecy = $this->prophesize(TokenParserInterface::class);
        $tokenParserProphecy->parse($token1)->willReturn('parsed_foo');
        /** @var TokenParserInterface $tokenParser */
        $tokenParser = $tokenParserProphecy->reveal();

        $parser = new SimpleParser($lexer, $tokenParser);
        $parsedValue = $parser->parse($value);

        $this->assertEquals(
            'parsed_foo',
            $parsedValue
        );
    }

    public function testIfATokenIsParsedIntoANestedValueThenItsValuesAreMerged()
    {
        $value = 'foo';

        $lexerProphecy = $this->prophesize(LexerInterface::class);
        $lexerProphecy->lex($value)->willReturn([
            $token1 = new Token('foo', new TokenType(TokenType::STRING_TYPE)),
            $token2 = new Token('bar', new TokenType(TokenType::VARIABLE_TYPE)),
            $token3 = new Token('baz', new TokenType(TokenType::FUNCTION_TYPE)),
        ]);
        /** @var LexerInterface $lexer */
        $lexer = $lexerProphecy->reveal();

        $tokenParserProphecy = $this->prophesize(TokenParserInterface::class);
        $tokenParserProphecy->parse($token1)->willReturn('parsed_foo');
        $tokenParserProphecy
            ->parse($token2)
            ->willReturn(
                new NestedValue([
                    'first',
                    'second',
                ])
            )
        ;
        $tokenParserProphecy->parse($token3)->willReturn('parsed_baz');
        /** @var TokenParserInterface $tokenParser */
        $tokenParser = $tokenParserProphecy->reveal();

        $expected = new ListValue([
            'parsed_foo',
            'first',
            'second',
            'parsed_baz',
        ]);

        $parser = new SimpleParser($lexer, $tokenParser);
        $actual = $parser->parse($value);

        $this->assertEquals($expected, $actual);

        $lexerProphecy->lex(Argument::any())->shouldHaveBeenCalledTimes(1);
        $tokenParserProphecy->parse(Argument::any())->shouldHaveBeenCalledTimes(3);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using NUnit.Framework;
using Paramore.Brighter;
using ToDoCore.Ports.Commands;
using ToDoCore.Ports.Mappers;
using ToDoCore.ViewModels;

namespace ToDoTests.Core.Ports.Mappers
{
    [TestFixture]
    public class BulkAddToDoMessageMapperTests
    {
        [Test]
        public void Test_Map_A_Bulk_Command_To_A_Message()
        {
            /* Given that I have a bulk command
               When I map it to a message
               I should get a message header and a JSON body
            */

            var todos = new List<AddToDoRequest>
            {
                new AddToDoRequest {Title = "First", Order = 1, Completed = false},
                new AddToDoRequest {Title = "Second", Order = 2, Completed = false},
                new AddToDoRequest {Title = "Third", Order = 3, Completed = false}
            };

            var command = new BulkAddToDoCommand(todos) ;

            var message = new BulkAddToDoMessageMapper().MapToMessage(command);

            Assert.AreEqual(message.Header.MessageType, MessageType.MT_COMMAND);
            Assert.AreEqual(message.Header.Topic, "bulkaddtodo.command");
            Assert.AreEqual(message.Body.Value, JsonConvert.SerializeObject(command));

        }

        [Test]
        public void Test_Map_A_Message_To_A_Bulk_Action_Command()
        {
            /* Given that I have a message for a bulk command
               When I map it to a command
               I should get a command with a list of bulk options
            */

            var todos = new List<AddToDoRequest>
            {
                new AddToDoRequest {Title = "First", Order = 1, Completed = false},
                new AddToDoRequest {Title = "Second", Order = 2, Completed = false},
                new AddToDoRequest {Title = "Third", Order = 3, Completed = false}
            };

            var original_command = new BulkAddToDoCommand(todos) ;

            var header = new MessageHeader(messageId: Guid.NewGuid(), topic: "bulkaddtodo.command", messageType: MessageType.MT_COMMAND);
            var body = new MessageBody(JsonConvert.SerializeObject(original_command));
            var message = new Message(header, body);

            var command = new BulkAddToDoMessageMapper().MapToRequest(message);

            Assert.AreEqual(command.ToDos.Count(), 3);
            Assert.AreEqual(command.ToDos.First().Title, "First");
            Assert.AreEqual(command.ToDos.First().Order, 1);
            Assert.AreEqual(command.ToDos.First().Completed, false);
        }
   }
}


text:
/**
 * ExtensionSetting.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201509.cm;

/**
 * A setting specifying when and which extensions should serve at
 * a given level (customer, campaign,
 *             or ad group).
 */
public class ExtensionSetting  implements java.io.Serializable {
    /* The list of feed items to add or modify.
     *                 This field can
     * be selected using the value "Extensions". */
    private com.google.api.ads.adwords.axis.v201509.cm.ExtensionFeedItem[] extensions;

    /* Any platform (desktop, mobile) restrictions for feed items
     * being served. If set to DESKTOP or
     *                 MOBILE, only those feed items with the appropriate
     * device preference or no device preference
     *                 will serve.
     *                 This field can
     * be selected using the value "PlatformRestrictions". */
    private com.google.api.ads.adwords.axis.v201509.cm.ExtensionSettingPlatform platformRestrictions;

    public ExtensionSetting() {
    }

    public ExtensionSetting(
           com.google.api.ads.adwords.axis.v201509.cm.ExtensionFeedItem[] extensions,
           com.google.api.ads.adwords.axis.v201509.cm.ExtensionSettingPlatform platformRestrictions) {
           this.extensions = extensions;
           this.platformRestrictions = platformRestrictions;
    }

    /**
     * Gets the extensions value for this ExtensionSetting.
     *
     * @return extensions   * The list of feed items to add or modify.
     *                 This field can
     * be selected using the value "Extensions".
     */
    public com.google.api.ads.adwords.axis.v201509.cm.ExtensionFeedItem[] getExtensions() {
        return extensions;
    }

    /**
     * Sets the extensions value for this ExtensionSetting.
     *
     * @param extensions   * The list of feed items to add or modify.
     *                 This field can
     * be selected using the value "Extensions".
     */
    public void setExtensions(com.google.api.ads.adwords.axis.v201509.cm.ExtensionFeedItem[] extensions) {
        this.extensions = extensions;
    }

    public com.google.api.ads.adwords.axis.v201509.cm.ExtensionFeedItem getExtensions(int i) {
        return this.extensions[i];
    }

    public void setExtensions(int i, com.google.api.ads.adwords.axis.v201509.cm.ExtensionFeedItem _value) {
        this.extensions[i] = _value;
    }

    /**
     * Gets the platformRestrictions value for this ExtensionSetting.
     *
     * @return platformRestrictions   * Any platform (desktop, mobile) restrictions for feed items
     * being served. If set to DESKTOP or
     *                 MOBILE, only those feed items with the appropriate
     * device preference or no device preference
     *                 will serve.
     *                 This field can
     * be selected using the value "PlatformRestrictions".
     */
    public com.google.api.ads.adwords.axis.v201509.cm.ExtensionSettingPlatform getPlatformRestrictions() {
        return platformRestrictions;
    }

    /**
     * Sets the platformRestrictions value for this ExtensionSetting.
     *
     * @param platformRestrictions   * Any platform (desktop, mobile) restrictions for feed items
     * being served. If set to DESKTOP or
     *                 MOBILE, only those feed items with the appropriate
     * device preference or no device preference
     *                 will serve.
     *                 This field can
     * be selected using the value "PlatformRestrictions".
     */
    public void setPlatformRestrictions(com.google.api.ads.adwords.axis.v201509.cm.ExtensionSettingPlatform platformRestrictions) {
        this.platformRestrictions = platformRestrictions;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof ExtensionSetting)) return false;
        ExtensionSetting other = (ExtensionSetting) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.extensions==null && other.getExtensions()==null) ||
             (this.extensions!=null &&
              java.util.Arrays.equals(this.extensions, other.getExtensions()))) &&
            ((this.platformRestrictions==null && other.getPlatformRestrictions()==null) ||
             (this.platformRestrictions!=null &&
              this.platformRestrictions.equals(other.getPlatformRestrictions())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getExtensions() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getExtensions());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getExtensions(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        if (getPlatformRestrictions() != null) {
            _hashCode += getPlatformRestrictions().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(ExtensionSetting.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201509", "ExtensionSetting"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("extensions");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201509", "extensions"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201509", "ExtensionFeedItem"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        elemField.setMaxOccursUnbounded(true);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("platformRestrictions");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201509", "platformRestrictions"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201509", "ExtensionSetting.Platform"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
using namespace Magnum;

namespace Ar {

class Application : public Platform::Application {
public:
	explicit Application(const Arguments& arguments);

private:
	void drawEvent() override;
};

} // namespace Ar


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class ArrayOfClusterHostRecommendation
{
  public ClusterHostRecommendation[] ClusterHostRecommendation;

  public ClusterHostRecommendation[] getClusterHostRecommendation()
  {
    return this.ClusterHostRecommendation;
  }

  public ClusterHostRecommendation getClusterHostRecommendation(int i)
  {
    return this.ClusterHostRecommendation[i];
  }

  public void setClusterHostRecommendation(ClusterHostRecommendation[] ClusterHostRecommendation)
  {
    this.ClusterHostRecommendation=ClusterHostRecommendation;
  }
}


text:
package pointer.wbc.com.billiardspointer;

import android.os.Bundle;
import android.support.v4.app.Fragment;

import pointer.wbc.com.billiardspointer.fragment.MainActivityFragment;

public class MainActivity extends BaseActivity {

    private Fragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragment = getSupportFragmentManager().findFragmentById(R.id.fragment);
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_list) {
//            Navigator.goGameList(context);
//            return true;
//        } else if (id == R.id.action_theme) {
//            boolean isLight = !Pref.getBoolean(Const.KEY_THEME, false);
//            Pref.putBoolean(Const.KEY_THEME, isLight);
//            Intent intent = new Intent(this, MainActivity.class);
//            startActivity(intent);
//            finish();
//        }
//
//        return super.onOptionsItemSelected(item);
//    }

    @Override
    public void onBackPressed() {
        if (fragment instanceof MainActivityFragment) {
            ((MainActivityFragment) fragment).onBackPressed();
        } else {
            super.onBackPressed();
        }
    }
}