text:
import tl = require("azure-pipelines-task-lib/task");
import msRestAzure = require('azure-pipelines-tasks-azure-arm-rest-v2/azure-arm-common');
import { AzureRMEndpoint } from 'azure-pipelines-tasks-azure-arm-rest-v2/azure-arm-endpoint';
import { GraphManagementClient } from 'azure-pipelines-tasks-azure-arm-rest-v2/azure-graph';

export class TaskParameters {

    public action: string;
    public resourceGroupName: string;
    public location: string;
    public csmFile: string;
    public csmParametersFile: string;
    public templateLocation: string;
    public csmFileLink: string;
    public csmParametersFileLink: string;
    public overrideParameters: string;
    public outputVariable: string;
    public subscriptionId: string;
    public endpointPortalUrl: string;
    public deploymentName: string;
    public deploymentMode: string;
    public credentials: msRestAzure.ApplicationTokenCredentials;
    public graphCredentials: msRestAzure.ApplicationTokenCredentials;
    public deploymentOutputs: string;
    public addSpnToEnvironment: boolean;
    public connectedService: string;
    public deploymentScope: string;
    public managementGroupId: string;
    public authScheme: string;

    private async getARMCredentials(connectedService: string): Promise<msRestAzure.ApplicationTokenCredentials> {
        var azureEndpoint = await new AzureRMEndpoint(connectedService).getEndpoint();
        return azureEndpoint.applicationTokenCredentials;
    }

    private async getGraphCredentials(connectedService: string): Promise<msRestAzure.ApplicationTokenCredentials> {
        var azureEndpoint = await new AzureRMEndpoint(connectedService).getEndpoint(true);
        return azureEndpoint.applicationTokenCredentials;
    }

    public async getTaskParameters() : Promise<TaskParameters>
    {
        try {

            //Deployment Scope
            this.deploymentScope = tl.getInput("deploymentScope");
            if(!this.deploymentScope){
                this.deploymentScope = "Resource Group";
            }

            var resourceGroupNameInServiceConnection;

            //Service Connection
            this.connectedService = tl.getInput("ConnectedServiceName", true);
            var endpointTelemetry = '{"endpointId":"' + this.connectedService + '"}';
            console.log("##vso[telemetry.publish area=TaskEndpointId;feature=AzureResourceManagerTemplateDeployment]" + endpointTelemetry);
            this.endpointPortalUrl = tl.getEndpointDataParameter(this.connectedService, "armManagementPortalUrl", true);
            var armServiceConnectionScope = tl.getEndpointDataParameter(this.connectedService, 'ScopeLevel', true);
            if(!!armServiceConnectionScope && armServiceConnectionScope === "Subscription"){
                var armServiceConnectionAuthScope = tl.getEndpointAuthorizationParameter(this.connectedService, 'scope', true);
                if(!!armServiceConnectionAuthScope){
                    var armServiceConnectionAuthScopeSplit = armServiceConnectionAuthScope.split("/");
                    if(!!armServiceConnectionAuthScopeSplit[4]){
                        armServiceConnectionScope = "Resource Group";
                        resourceGroupNameInServiceConnection = armServiceConnectionAuthScopeSplit[4];
                    }
                }
            }
            console.log(tl.loc("ARMServiceConnectionScope", armServiceConnectionScope));

            //Management Group Id
            if(this.deploymentScope === "Management Group"){
                this.managementGroupId = tl.getEndpointDataParameter(this.connectedService, "ManagementGroupId", false);
            }

            //Subscripion Id
            this.subscriptionId = tl.getInput("subscriptionName");
            if(!this.subscriptionId && (this.deploymentScope === "Subscription" || this.deploymentScope === "Resource Group")) {
                this.subscriptionId = tl.getEndpointDataParameter(this.connectedService, "SubscriptionId", false);
            }

            //Resource group name
            this.resourceGroupName = tl.getInput("resourceGroupName");
            if(!this.resourceGroupName && this.deploymentScope === "Resource Group"){
                this.resourceGroupName = resourceGroupNameInServiceConnection;
                if(!this.resourceGroupName){
                    throw new Error(tl.loc("ResourceGroupNameNotProvided"));
                }
            }

            this.action = tl.getInput("action");

            //Location
            this.location = tl.getInput("location");
            if(!this.location && this.deploymentScope === "Resource Group" && this.action != "DeleteRG"){
                throw new Error(tl.loc("LocationNotProvided"));
            }

            //Deployment mode
            this.deploymentMode = tl.getInput("deploymentMode");
            if(!!this.deploymentMode && this.deploymentMode === "Complete" && this.deploymentScope != "Resource Group"){
                throw new Error(tl.loc("CompleteDeploymentModeNotSupported", this.deploymentScope));
            }

            this.templateLocation = tl.getInput("templateLocation");
            if (this.templateLocation === "Linked artifact") {
                this.csmFile = tl.getPathInput("csmFile");
                this.csmParametersFile = tl.getPathInput("csmParametersFile");
            } else {
                this.csmFileLink = tl.getInput("csmFileLink");
                this.csmParametersFileLink = tl.getInput("csmParametersFileLink");
            }
            this.overrideParameters = tl.getInput("overrideParameters");
            this.outputVariable = tl.getInput("outputVariable");
            this.deploymentName = tl.getInput("deploymentName");
            this.credentials = await this.getARMCredentials(this.connectedService);
            this.authScheme = tl.getEndpointAuthorizationScheme(this.connectedService, true);
            this.graphCredentials = await this.getGraphCredentials(this.connectedService);
            this.deploymentOutputs = tl.getInput("deploymentOutputs");
            this.addSpnToEnvironment = tl.getBoolInput("addSpnToEnvironment", false);

            return this;
        } catch (error) {
            throw new Error(tl.loc("ARGD_ConstructorFailed", error.message));
        }
    }
}


text:
#ifndef MA_SOLUTIONTRANSFER_H
#define MA_SOLUTIONTRANSFER_H

/** \file maSolutionTransfer.h
  \brief MeshAdapt solution transfer interface */

#include <apf.h>
#include "maMesh.h"

namespace ma {

/** \brief user-defined solution transfer base
 \details one of these classes should be defined for
          each field the user wants transferred during
          adaptivity. Then, use ma::SolutionTransfers
          to put them together into a single object
          to give to the MeshAdapt driver functions. */
class SolutionTransfer
{
  public:
    /** \brief user-defined destructor */
    virtual ~SolutionTransfer();
    /** \brief return true if this field has
               nodes on entities of this dimension */
    virtual bool hasNodesOn(int dimension) = 0;
    /** \brief perform solution transfer on refined vertex
      \details this vertex was created while refining an
               element. Given coordinates in the parent
               element's parametric space, transfer the solution
               from the parent element to the vertex
      \param parent MeshElement for the parent.
                    can be given to apf::createElement
                    so that element interpolation can be used.
      \param xi Coordinates of the vertex in the parent
                element's parametric space */
    virtual void onVertex(
        apf::MeshElement* parent,
        Vector const& xi,
        Entity* vert);
    /** \brief perform solution transfer on refined entities
      \details when there are nodes on entities other
               than vertices, it becomes necessary to transfer
               solution to these as well.
               If this is not the case, don't override this.
      \param parent the parent element
      \param newEntities entities created during refinement.
                         this may contain some entities that
                         don't have nodes, so check them */
    virtual void onRefine(
        Entity* parent,
        EntityArray& newEntities);
    /** \brief perform solution transfer on cavity replacement
      \details this will be called for operations like edge
      collapses and edge swaps. Both the old and new cavity
      are given, and the code should transfer solution into
      into the new cavity.
      \param oldElements all elements in the old cavity
      \param newEntities newly created entities which need transfer
      */
    virtual void onCavity(
        EntityArray& oldElements,
        EntityArray& newEntities);
    /** \brief for internal MeshAdapt use */
    int getTransferDimension();
};

/** \brief Creates a default solution transfer object for a field
  \details MeshAdapt has good algorithms for transferring
  nodal fields as well as using the Voronoi system for transferring
  integration point fields. */
SolutionTransfer* createFieldTransfer(apf::Field* f);

/** \brief a meta-object that carries out a series of transfers
  \details use this class to put together solution transfer
  objects for several fields before giving them to MeshAdapt. */
class SolutionTransfers : public SolutionTransfer
{
  public:
    SolutionTransfers();
    virtual ~SolutionTransfers();
    /** \brief add another field transfer object */
    void add(SolutionTransfer* t);
    virtual bool hasNodesOn(int dimension);
    virtual void onVertex(
        apf::MeshElement* parent,
        Vector const& xi,
        Entity* vert);
    virtual void onRefine(
        Entity* parent,
        EntityArray& newEntities);
    virtual void onCavity(
        EntityArray& oldElements,
        EntityArray& newEntities);
  private:
    typedef std::vector<SolutionTransfer*> Transfers;
    Transfers transfers;
};

/** \brief MeshAdapt's automatic solution transfer system.
  \details will call ma::createFieldTransfer on all fields associated
  with the mesh and put them together. */
class AutoSolutionTransfer : public SolutionTransfers
{
  public:
    AutoSolutionTransfer(Mesh* m);
};

}

#endif

redpajama_set_name: RedPajamaGithub


text:
package io.lettuce.core.cluster.pubsub;

import static org.assertj.core.api.Assertions.assertThat;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;

import javax.inject.Inject;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import io.lettuce.core.RedisURI;
import io.lettuce.core.TestSupport;
import io.lettuce.core.api.push.PushMessage;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
import io.lettuce.core.cluster.pubsub.api.async.NodeSelectionPubSubAsyncCommands;
import io.lettuce.core.cluster.pubsub.api.async.PubSubAsyncNodeSelection;
import io.lettuce.core.cluster.pubsub.api.reactive.NodeSelectionPubSubReactiveCommands;
import io.lettuce.core.cluster.pubsub.api.reactive.PubSubReactiveNodeSelection;
import io.lettuce.core.cluster.pubsub.api.sync.NodeSelectionPubSubCommands;
import io.lettuce.core.cluster.pubsub.api.sync.PubSubNodeSelection;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.support.PubSubTestListener;
import io.lettuce.test.LettuceExtension;
import io.lettuce.test.TestFutures;
import io.lettuce.test.Wait;
import io.lettuce.test.condition.EnabledOnCommand;

/**
 * @author Mark Paluch
 */
@ExtendWith(LettuceExtension.class)
class RedisClusterPubSubConnectionIntegrationTests extends TestSupport {

    private final RedisClusterClient clusterClient;

    private final PubSubTestListener connectionListener = new PubSubTestListener();
    private final PubSubTestListener nodeListener = new PubSubTestListener();

    private StatefulRedisClusterConnection<String, String> connection;
    private StatefulRedisClusterPubSubConnection<String, String> pubSubConnection;
    private StatefulRedisClusterPubSubConnection<String, String> pubSubConnection2;

    @Inject
    RedisClusterPubSubConnectionIntegrationTests(RedisClusterClient clusterClient) {
        this.clusterClient = clusterClient;
    }

    @BeforeEach
    void openPubSubConnection() {
        connection = clusterClient.connect();
        pubSubConnection = clusterClient.connectPubSub();
        pubSubConnection2 = clusterClient.connectPubSub();

    }

    @AfterEach
    void closePubSubConnection() {
        connection.close();
        pubSubConnection.close();
        pubSubConnection2.close();
    }

    @Test
    void testRegularClientPubSubChannels() {

        String nodeId = pubSubConnection.sync().clusterMyId();
        RedisClusterNode otherNode = getOtherThan(nodeId);
        pubSubConnection.sync().subscribe(key);

        List<String> channelsOnSubscribedNode = connection.getConnection(nodeId).sync().pubsubChannels();
        assertThat(channelsOnSubscribedNode).hasSize(1);

        List<String> channelsOnOtherNode = connection.getConnection(otherNode.getNodeId()).sync().pubsubChannels();
        assertThat(channelsOnOtherNode).isEmpty();
    }

    @Test
    void testRegularClientPublish() throws Exception {

        String nodeId = pubSubConnection.sync().clusterMyId();
        RedisClusterNode otherNode = getOtherThan(nodeId);
        pubSubConnection.sync().subscribe(key);
        pubSubConnection.addListener(connectionListener);

        connection.getConnection(nodeId).sync().publish(key, value);
        assertThat(connectionListener.getMessages().take()).isEqualTo(value);

        connection.getConnection(otherNode.getNodeId()).sync().publish(key, value);
        assertThat(connectionListener.getMessages().take()).isEqualTo(value);
    }

    @Test
    void testPubSubClientPublish() throws Exception {

        String nodeId = pubSubConnection.sync().clusterMyId();
        pubSubConnection.sync().subscribe(key);
        pubSubConnection.addListener(connectionListener);

        assertThat(pubSubConnection2.sync().clusterMyId()).isEqualTo(nodeId);

        pubSubConnection2.sync().publish(key, value);
        assertThat(connectionListener.getMessages().take()).isEqualTo(value);
    }

    @Test
    void testConnectToLeastClientsNode() {

        clusterClient.reloadPartitions();
        String nodeId = pubSubConnection.sync().clusterMyId();

        StatefulRedisPubSubConnection<String, String> connectionAfterPartitionReload = clusterClient.connectPubSub();
        String newConnectionNodeId = connectionAfterPartitionReload.sync().clusterMyId();
        connectionAfterPartitionReload.close();

        assertThat(nodeId).isNotEqualTo(newConnectionNodeId);
    }

    @Test
    void testRegularClientPubSubPublish() throws Exception {

        String nodeId = pubSubConnection.sync().clusterMyId();
        RedisClusterNode otherNode = getOtherThan(nodeId);
        pubSubConnection.sync().subscribe(key);
        pubSubConnection.addListener(connectionListener);

        List<String> channelsOnSubscribedNode = connection.getConnection(nodeId).sync().pubsubChannels();
        assertThat(channelsOnSubscribedNode).hasSize(1);

        RedisCommands<String, String> otherNodeConnection = connection.getConnection(otherNode.getNodeId()).sync();
        otherNodeConnection.publish(key, value);
        assertThat(connectionListener.getChannels().take()).isEqualTo(key);
    }

    @Test
    void testGetConnectionAsyncByNodeId() {

        RedisClusterNode partition = pubSubConnection.getPartitions().getPartition(0);

        StatefulRedisPubSubConnection<String, String> node = TestFutures
                .getOrTimeout(pubSubConnection.getConnectionAsync(partition
                .getNodeId()));

        assertThat(node.sync().ping()).isEqualTo("PONG");
    }

    @Test
    void testGetConnectionAsyncByHostAndPort() {

        RedisClusterNode partition = pubSubConnection.getPartitions().getPartition(0);

        RedisURI uri = partition.getUri();
        StatefulRedisPubSubConnection<String, String> node = TestFutures
                .getOrTimeout(pubSubConnection.getConnectionAsync(uri.getHost(),
                uri.getPort()));

        assertThat(node.sync().ping()).isEqualTo("PONG");
    }

    @Test
    void testNodeIdSubscription() throws Exception {

        RedisClusterNode partition = pubSubConnection.getPartitions().getPartition(0);

        StatefulRedisPubSubConnection<String, String> node = pubSubConnection.getConnection(partition.getNodeId());
        node.addListener(nodeListener);

        node.sync().subscribe("channel");

        pubSubConnection2.sync().publish("channel", "message");

        assertThat(nodeListener.getMessages().take()).isEqualTo("message");
        assertThat(connectionListener.getMessages().poll()).isNull();
    }

    @Test
    void testNodeMessagePropagationSubscription() throws Exception {

        RedisClusterNode partition = pubSubConnection.getPartitions().getPartition(0);
        pubSubConnection.setNodeMessagePropagation(true);
        pubSubConnection.addListener(connectionListener);

        StatefulRedisPubSubConnection<String, String> node = pubSubConnection.getConnection(partition.getNodeId());
        node.sync().subscribe("channel");

        pubSubConnection2.sync().publish("channel", "message");

        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
    }

    @Test
    void testNodeHostAndPortMessagePropagationSubscription() throws Exception {

        RedisClusterNode partition = pubSubConnection.getPartitions().getPartition(0);
        pubSubConnection.setNodeMessagePropagation(true);
        pubSubConnection.addListener(connectionListener);

        RedisURI uri = partition.getUri();
        StatefulRedisPubSubConnection<String, String> node = pubSubConnection.getConnection(uri.getHost(), uri.getPort());
        node.sync().subscribe("channel");

        pubSubConnection2.sync().publish("channel", "message");

        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
    }

    @Test
    void testAsyncSubscription() throws Exception {

        pubSubConnection.setNodeMessagePropagation(true);
        pubSubConnection.addListener(connectionListener);

        PubSubAsyncNodeSelection<String, String> masters = pubSubConnection.async().masters();
        NodeSelectionPubSubAsyncCommands<String, String> commands = masters.commands();

        TestFutures.awaitOrTimeout(commands.psubscribe("chann*"));

        pubSubConnection2.sync().publish("channel", "message");

        assertThat(masters.size()).isEqualTo(2);
        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
    }

    @Test
    void testSyncSubscription() throws Exception {

        pubSubConnection.setNodeMessagePropagation(true);
        pubSubConnection.addListener(connectionListener);

        PubSubNodeSelection<String, String> masters = pubSubConnection.sync().masters();
        NodeSelectionPubSubCommands<String, String> commands = masters.commands();

        commands.psubscribe("chann*");

        pubSubConnection2.sync().publish("channel", "message");

        assertThat(masters.size()).isEqualTo(2);
        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
    }

    @Test
    void testReactiveSubscription() throws Exception {

        pubSubConnection.setNodeMessagePropagation(true);
        pubSubConnection.addListener(connectionListener);

        PubSubReactiveNodeSelection<String, String> masters = pubSubConnection.reactive().masters();
        NodeSelectionPubSubReactiveCommands<String, String> commands = masters.commands();

        commands.psubscribe("chann*").flux().then().block();

        pubSubConnection2.sync().publish("channel", "message");

        assertThat(masters.size()).isEqualTo(2);
        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
        assertThat(connectionListener.getMessages().poll()).isNull();
    }

    @Test
    void testClusterListener() throws Exception {

        BlockingQueue<RedisClusterNode> nodes = new LinkedBlockingQueue<>();
        pubSubConnection.setNodeMessagePropagation(true);
        pubSubConnection.addListener(connectionListener);
        pubSubConnection.addListener(new RedisClusterPubSubAdapter<String, String>() {

            @Override
            public void message(RedisClusterNode node, String pattern, String channel, String message) {
                nodes.add(node);
            }
        });

        PubSubNodeSelection<String, String> masters = pubSubConnection.sync().masters();
        NodeSelectionPubSubCommands<String, String> commands = masters.commands();

        commands.psubscribe("chann*");

        pubSubConnection2.sync().publish("channel", "message");

        assertThat(masters.size()).isEqualTo(2);
        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
        assertThat(connectionListener.getMessages().take()).isEqualTo("message");
        assertThat(connectionListener.getMessages().poll()).isNull();

        assertThat(nodes.take()).isNotNull();
        assertThat(nodes.take()).isNotNull();
        assertThat(nodes.poll()).isNull();
    }

    private RedisClusterNode getOtherThan(String nodeId) {
        for (RedisClusterNode redisClusterNode : clusterClient.getPartitions()) {
            if (redisClusterNode.getNodeId().equals(nodeId)) {
                continue;
            }
            return redisClusterNode;
        }

        throw new IllegalStateException("No other nodes than " + nodeId + " available");
    }
}


text:
function assembleCentersAndRadiiDeterministic()

	xs = [0.0,0.25,0.5,0.75,1.0]
	ys = [0.5,0.5,0.5,0.5,0.5]
	radii = [0.1,0.1,0.1,0.1,0.1]

	centersAndRadii = hcat(xs,ys,radii)'

	return centersAndRadii
end

function assembleCentersAndRadiiRandom(intendedNumberOfInclusions::Int64)

	# TODO: Set threshold properly:
	threshold1 = 0.000001
	threshold2 = 0.000001

	xMin = 0
	xMax = 1
	yMin = 0
	yMax = 1
	radiusMin = 0.1
	radiusMax = 0.1

	xs = Array{Float64}(0)
	ys = Array{Float64}(0)
	radii = Array{Float64}(0)

	counterMax = 100
	for counter = 1:1:counterMax

		# Choose random center coordinates:
		x = xMin + rand()*(xMax-xMin)
		y = yMin + rand()*(yMax-yMin)
		r = radiusMin + rand()*(radiusMax-radiusMin)

		xsCurrent = x + (xMax-xMin)*[-1,0,1,-1,0,1,-1,0,1]
		ysCurrent = y + (yMax-yMin)*[-1,-1,-1,0,0,0,1,1,1]
		radiiCurrent = r*ones(9)
		isActiveCurrent = falses(9)
		for i = 1:1:9
			if valueIsInInterval(xsCurrent[i],[xMin,xMax] + radiiCurrent[i]*[-1,1] + threshold1*[1,-1])&
				valueIsInInterval(ysCurrent[i],[yMin,yMax] + radiiCurrent[i]*[-1,1] + threshold1*[1,-1])

				isActiveCurrent[i] = true
			end
		end

		# Check if inclusions overlap:
		doPush = true
		breakOuterLoop = false
		for i = 1:1:length(xs)
			for j = 1:1:length(xsCurrent)
				if isActiveCurrent[j]
					if norm([xs[i],ys[i]]-[xsCurrent[j],ysCurrent[j]]) <= radii[i]+radiiCurrent[j]+threshold2
						doPush = false
						breakOuterLoop = true
						break
					end
				end
			end
			if breakOuterLoop
				break
			end
		end

		# Add current inclusions:
		if doPush
			append!(xs,xsCurrent[isActiveCurrent])
			append!(ys,ysCurrent[isActiveCurrent])
			append!(radii,radiiCurrent[isActiveCurrent])
		end

		if length(xs) >= intendedNumberOfInclusions
			println("stopped at counter = "*string(counter))
			break
		end

		if counter == counterMax
			println("stopped at counterMax = "*string(counter))
		end
	end

	centersAndRadii = hcat(xs,ys,radii)'

	return centersAndRadii
end

##############################################

equationType = "elliptic"
tMax = 0.0

##############################################

# intendedNumberOfInclusions = 10
# centersAndRadii = assembleCentersAndRadiiRandom(intendedNumberOfInclusions)
centersAndRadii = assembleCentersAndRadiiDeterministic()

AValueDomain = 1.0
AValueInclusions = 10.0

##############################################
# domain:
##############################################

domainWidth = 1.0
domainHeight = 1.0

x0 = 0.0
y0 = 0.0
dx = 1.0
dy = 1.0

gammaNode1 = GammaNode(1,[0,0])
gammaNode2 = GammaNode(2,[domainWidth,0])
gammaNode3 = GammaNode(3,[domainWidth,domainHeight])
gammaNode4 = GammaNode(4,[0,domainHeight])
gammaNodes = [gammaNode1,gammaNode2,gammaNode3,gammaNode4]
gamma1 = Gamma(1,"gammaLine",[gammaNode1.id,gammaNode2.id],[],1,()->[],"periodic",(s)->0.0,true,true)
gamma2 = Gamma(2,"gammaLine",[gammaNode2.id,gammaNode3.id],[],1,()->[],"periodic",(s)->0.0,true,true)
gamma3 = Gamma(3,"gammaLine",[gammaNode3.id,gammaNode4.id],[],1,()->[],"periodic",(s)->0.0,true,true)
gamma4 = Gamma(4,"gammaLine",[gammaNode4.id,gammaNode1.id],[],1,()->[],"periodic",(s)->0.0,true,true)
gammas = [gamma1,gamma2,gamma3,gamma4]

periodicGammasPairs =
	[PeriodicGammasPair(1,[1,3],false),
	PeriodicGammasPair(2,[2,4],false)]

uInitial = (x,y) -> 0.0
uTInitial = (x,y) -> 0.0

domainA11 = (x,y) -> AValueDomain
domainA21 = (x,y) -> 0.0
domainA12 = (x,y) -> 0.0
domainA22 = (x,y) -> AValueDomain
domainA = hcat([domainA11,domainA21],[domainA12,domainA22])
b1 = (x,y) -> 0.0
b2 = (x,y) -> 0.0
b = [b1,b2]
c = (x,y) -> 0.0
f = (x,y) -> 0.0
domainFDiv1 = (x,y) -> 0.0
domainFDiv2 = (x,y) -> 0.0
domainFDiv = [domainFDiv1,domainFDiv2]

isZeroUInitial = true
isZeroUTInitial = true

isIdentityA = false
isZeroB = true
isZeroC = true
isZeroF = true
isZeroFDiv = false

isConstantInTimeA = true
isConstantInTimeB = true
isConstantInTimeC = true
isConstantInTimeF = true
isConstantInTimeFDiv = true

domain = Domain(1,"domain",gammaNodes,gammas,periodicGammasPairs,
	uInitial,uTInitial,domainA,b,c,f,domainFDiv,
	isZeroUInitial,isZeroUTInitial,isIdentityA,isZeroB,isZeroC,isZeroF,isZeroFDiv,
	isConstantInTimeA,isConstantInTimeB,isConstantInTimeC,isConstantInTimeF,isConstantInTimeFDiv)

##############################################
# holes:
##############################################

holes = []

##############################################
# subdomains:
##############################################

subdomains = Array{Domain}(size(centersAndRadii,2))
for i = 1:1:size(centersAndRadii,2)

	x = centersAndRadii[1,i]
	y = centersAndRadii[2,i]
	r = centersAndRadii[3,i]

	numberOfPoints = 16

	gammaNodeCenter = GammaNode(1,[x,y])
	gammaNode1 = GammaNode(2,[x+r,y])
	gammaNodes = [gammaNodeCenter,gammaNode1]
	gamma1 = Gamma(1,"gammaArc",[gammaNodeCenter.id,gammaNode1.id],[2*pi],numberOfPoints,()->[],"Dirichlet",(s)->0.0,true,true)
	gammas = [gamma1]

	uInitial = (x,y) -> 0.0
	uTInitial = (x,y) -> 0.0

	subdomainsA11 = (x,y) -> AValueInclusions
	subdomainsA21 = (x,y) -> 0.0
	subdomainsA12 = (x,y) -> 0.0
	subdomainsA22 = (x,y) -> AValueInclusions
	subdomainsA = hcat([subdomainsA11,subdomainsA21],[subdomainsA12,subdomainsA22])
	b1 = (x,y) -> 0.0
	b2 = (x,y) -> 0.0
	b = [b1,b2]
	c = (x,y) -> 0.0
	f = (x,y) -> 0.0
	subdomainsFDiv1 = (x,y) -> 0.0
	subdomainsFDiv2 = (x,y) -> 0.0
	subdomainsFDiv = [subdomainsFDiv1,subdomainsFDiv2]

	isZeroUInitial = true
	isZeroUTInitial = true

	isIdentityA = false
	isZeroB = true
	isZeroC = true
	isZeroF = true
	isZeroFDiv = false

	isConstantInTimeA = true
	isConstantInTimeB = true
	isConstantInTimeC = true
	isConstantInTimeF = true
	isConstantInTimeFDiv = true

	subdomains[i] = Domain(i,"subdomain",gammaNodes,gammas,[],
		uInitial,uTInitial,subdomainsA,b,c,f,subdomainsFDiv,
		isZeroUInitial,isZeroUTInitial,isIdentityA,isZeroB,isZeroC,isZeroF,isZeroFDiv,
		isConstantInTimeA,isConstantInTimeB,isConstantInTimeC,isConstantInTimeF,isConstantInTimeFDiv)

end

##############################################

equationData = EquationData(equationType,tMax,
	domain,holes,subdomains)

##############################################


text:
COMPILER_RT_ABI fp_t __floatsitf(int a) {

    const int aWidth = sizeof a * CHAR_BIT;

    // Handle zero as a special case to protect clz
    if (a == 0)
        return fromRep(0);

    // All other cases begin by extracting the sign and absolute value of a
    rep_t sign = 0;
    unsigned aAbs = (unsigned)a;
    if (a < 0) {
        sign = signBit;
        aAbs = ~(unsigned)a + 1U;
    }

    // Exponent of (fp_t)a is the width of abs(a).
    const int exponent = (aWidth - 1) - __builtin_clz(aAbs);
    rep_t result;

    // Shift a into the significand field and clear the implicit bit.
    const int shift = significandBits - exponent;
    result = (rep_t)aAbs << shift ^ implicitBit;

    // Insert the exponent
    result += (rep_t)(exponent + exponentBias) << significandBits;
    // Insert the sign bit and return
    return fromRep(result | sign);
}

#endif


text:
int buffer_putflush(buffer* b,const char* x,unsigned int len) {
  if (buffer_put(b,x,len)<0) return -1;
  if (buffer_flush(b)<0) return -1;
  return 0;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#484e61">

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textColor="#fff"
            android:textSize="24sp"/>
    </RelativeLayout>

    <ListView
        android:id="@+id/lv_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>


text:
/**
 * @fileoverview Tests for no-use-ignored-vars rule.
 * @author Toru Nagashima
 */
"use strict"

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const RuleTester = require("eslint").RuleTester
const rule = require("../../../lib/rules/no-use-ignored-vars")

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

const ruleTester = new RuleTester()

ruleTester.run("no-use-ignored-vars", rule, {
    valid: [
        "var foo; doSomething(foo)",
        "var _1; doSomething(_1)",
        "var _foo;",
        "function a(foo) { doSomething(foo) }",
        "function a(_1) { doSomething(_1) }",
        "function a(_foo) { }",
        "function a(obj) { for (_key in obj) return true; return false; }",
        "for (var _key in obj) { }",
        {
            code: "var _foo; doSomething(_foo)",
            options: ["x"],
        },
    ],
    invalid: [
        {
            code: "var _foo; doSomething(_foo)",
            errors: [
                "Unexpected a use of '_foo'. This name is matched to ignored pattern.",
            ],
        },
        {
            code: "var _bar; doSomething(_bar)",
            errors: [
                "Unexpected a use of '_bar'. This name is matched to ignored pattern.",
            ],
        },
        {
            code: "function a(_foo) { doSomething(_foo) }",
            errors: [
                "Unexpected a use of '_foo'. This name is matched to ignored pattern.",
            ],
        },
        {
            code: "var x; doSomething(x)",
            options: ["x"],
            errors: [
                "Unexpected a use of 'x'. This name is matched to ignored pattern.",
            ],
        },
    ],
})


text:
// Copyright NVIDIA Corporation 2010-2011
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include <dp/sg/renderer/rix/gl/Config.h>
#include <dp/sg/renderer/rix/gl/TransparencyManager.h>
#include <dp/sg/renderer/rix/gl/inc/ResourceManager.h>
#include <dp/gl/RenderTarget.h>
#include <dp/sg/xbar/SceneTree.h>
#include <dp/sg/xbar/DrawableManager.h>
#include <dp/culling/Manager.h>

#include <dp/sg/ui/SceneRenderer.h>

#include <dp/util/Reflection.h>

namespace dp
{
  namespace sg
  {
    namespace renderer
    {
      namespace rix
      {
        namespace gl
        {
          DEFINE_PTR_TYPES( SceneRenderer );

          /** \brief SceneRenderer is an OpenGL 3.0 based renderer. The OpenGL context used during the first render call
                    must not be changed for successive calls. It is necessary to remove all references to this object before
                    the attached OpenGL context gets destroyed. Deleting this object after destroying the corresponding OpenGL
                    context will result in a crash during resource cleanup. OpenGL resources like VBOs, display lists and
                    textures will be shared between multiple SceneRenderer objects if the corresponding OpenGL contexts
                    are being shared.
          **/
          class SceneRenderer : public dp::sg::ui::SceneRenderer
          {
          protected:
            DP_SG_RDR_RIX_GL_API SceneRenderer( const dp::gl::RenderTargetSharedPtr &renderTarget = dp::gl::RenderTargetSharedPtr() );

          public:
            /** \brief Create an instance of SceneRenderer
                \param renderTarget Default RenderTarget to use.
                \return An instance of a SceneRenderer object.
            **/
            static DP_SG_RDR_RIX_GL_API SceneRendererSharedPtr create( const char *renderEngine = 0,
                                                                       dp::fx::Manager shaderManagerType = dp::fx::MANAGER_SHADERBUFFER,
                                                                       dp::culling::Mode cullingMode = dp::culling::MODE_AUTO,
                                                                       TransparencyMode transparencyMode = TM_ORDER_INDEPENDENT_CLOSEST_LIST,
                                                                       const dp::gl::RenderTargetSharedPtr &renderTarget = dp::gl::RenderTargetSharedPtr() );
            DP_SG_RDR_RIX_GL_API virtual ~SceneRenderer();

            // HACK HACK HACK
            void setDepthPass( bool depthPass ) { m_depthPass = depthPass; }
            bool getDepthPass( ) const { return m_depthPass; }

            virtual void setRenderEngine( std::string const& renderEngine ) = 0;
            virtual std::string const& getRenderEngine() const = 0;

            virtual dp::sg::renderer::rix::gl::TransparencyMode getTransparencyMode() const = 0;
            virtual void setTransparencyMode( dp::sg::renderer::rix::gl::TransparencyMode mode ) = 0;
            virtual dp::sg::renderer::rix::gl::TransparencyManagerSharedPtr const & getTransparencyManager() const = 0;

          protected:
            /** \brief Delete all primitive caches. Call this function only if an OpenGL context is active since resources need
            to be deleted.
            **/
            DP_SG_RDR_RIX_GL_API virtual void deletePrimitiveCaches() = 0;

            DP_SG_RDR_RIX_GL_API virtual dp::sg::xbar::DrawableManager *createDrawableManager( const ResourceManagerSharedPtr &resourceManager ) const = 0;
            DP_SG_RDR_RIX_GL_API virtual dp::sg::xbar::DrawableManager* getDrawableManager() const = 0;

          protected:
            bool m_depthPass;
          };

        } // namespace gl
      } // namespace rix
    } // namespace renderer
  } // namespace sg
} // namespace dp


text:
from hashlib import md5
from django.conf import settings
from django.db import router
from django.core import paginator
from django.core.exceptions import FieldDoesNotExist
from django.core.cache import cache

from djangae.contrib.pagination.decorators import _field_name_for_ordering
from gcloudc.db.backends.datastore.query import extract_ordering

# TODO: it would be nice to be able to define a function which is given the queryset and returns
# the cache time.  That would allow different cache times for different queries.
CACHE_TIME = getattr(settings, "DJANGAE_PAGINATION_CACHE_TIME", 30 * 60)

class PaginationOrderingRequired(RuntimeError):
    pass

def _marker_cache_key(query_id, page_number):
    cache_key = "_PAGE_MARKER_{}:{}".format(query_id, page_number)
    return cache_key

def _count_cache_key(query_id):
    cache_key = "_PAGE_COUNTER_{}".format(query_id)
    return cache_key

def _update_known_count(query_id, count):
    cache_key = _count_cache_key(query_id)

    ret = cache.get(cache_key)
    if ret and ret > count:
        return

    cache.set(cache_key, count, CACHE_TIME)

def _get_known_count(query_id):
    cache_key = _count_cache_key(query_id)
    ret = cache.get(cache_key)
    if ret:
        return ret
    return 0

def _store_marker(query_id, page_number, marker_value):
    """
        For a model and query id, stores the marker value for previously
        queried page number.

        This stores the last item on the page identified by page number,
        not the marker that starts the page. i.e. there is a marker for page 1
    """

    cache_key = _marker_cache_key(query_id, page_number)
    cache.set(cache_key, marker_value, CACHE_TIME)

def _get_marker(query_id, page_number):
    """
        For a query_id, returns the marker at the end of the
        previous page. Returns a tuple of (marker, pages) where pages is
        the number of pages we had to go back to find the marker (this is the
        number of pages we need to skip in the result set)
    """

    counter = page_number - 1
    pages_skipped = 0

    while counter > 0:
        cache_key = _marker_cache_key(query_id, counter)
        ret = cache.get(cache_key)

        if ret:
            return ret, pages_skipped

        counter -= 1
        pages_skipped += 1

    # If we get here then we couldn't find a stored marker anywhere
    return None, pages_skipped

def queryset_identifier(queryset):
    """ Returns a string that uniquely identifies this query excluding its low and high mark"""

    db_alias = router.db_for_read(queryset.model)
    sql_and_params = u"%s:%s" % queryset.query.sql_with_params()
    cache_key = u"%s:%s" % (db_alias, sql_and_params)
    cache_key = cache_key.encode('utf-8')

    hasher = md5()
    hasher.update(cache_key)
    return hasher.hexdigest()

class Paginator(paginator.Paginator):
    """
        A paginator that works with the @paginated_model class decorator to efficiently
        return paginated sets on the appengine datastore
    """

    def __init__(
        self,
        object_list,
        per_page,
        readahead=10,
        allow_empty_first_page=True,
        **kwargs
    ):
        if not object_list.ordered:
            object_list.order_by("pk")  # Just order by PK by default

        self.original_orderings = extract_ordering(object_list.query)
        self.field_required = _field_name_for_ordering(self.original_orderings[:])
        self.readahead = readahead
        self.allow_empty_first_page = allow_empty_first_page

        try:
            object_list.model._meta.get_field(self.field_required)
        except FieldDoesNotExist:
            raise PaginationOrderingRequired(
                "No pagination ordering specified for {}. Field required: {}".format(
                    self.original_orderings,
                    self.field_required,
                )
            )

        # Wipe out the existing ordering
        object_list = object_list.order_by()

        # Add our replacement ordering
        # A single negated ordering can use the same field (we just flip the query), this
        # normalisation happens in _field_name_for_ordering, so we do the same here.
        if len(self.original_orderings) == 1 and self.original_orderings[0].startswith("-"):
            object_list = object_list.order_by("-" + self.field_required)
        else:
            object_list = object_list.order_by(self.field_required)

        self.queryset_id = queryset_identifier(object_list)
        super(Paginator, self).__init__(
            object_list,
            per_page,
            allow_empty_first_page=allow_empty_first_page,
            **kwargs
        )

    @property
    def count(self):
        return _get_known_count(self.queryset_id)

    def validate_number(self, number):
        """
        Validates the given 1-based page number.
        """
        try:
            number = int(number)
        except (TypeError, ValueError):
            raise paginator.PageNotAnInteger('That page number is not an integer')
        if number < 1:
            raise paginator.EmptyPage('That page number is less than 1')

        return number

    def page(self, number):
        """
        Returns a Page object for the given 1-based page number.
        """
        number = self.validate_number(number)
        bottom = (number - 1) * self.per_page
        top = bottom + self.per_page

        marker_value, pages = _get_marker(
            self.queryset_id,
            number
        )

        if marker_value:
            if len(self.original_orderings) == 1 and self.original_orderings[0].startswith("-"):
                qs = self.object_list.all().filter(**{"{}__lt".format(self.field_required): marker_value})
            else:
                qs = self.object_list.all().filter(**{"{}__gt".format(self.field_required): marker_value})
            bottom = pages * self.per_page  # We have to skip the pages here
            top = bottom + self.per_page
        else:
            qs = self.object_list

        results = list(qs[bottom:top + (self.per_page * self.readahead)])

        next_page = results[top:]
        next_page_counter = number + 1
        while next_page:
            if len(next_page) > self.per_page-1:
                index = self.per_page-1
            else:
                index = len(next_page)-1
            _store_marker(
                self.queryset_id,
                next_page_counter,
                getattr(next_page[index], self.field_required)
            )
            next_page_counter += 1
            next_page = next_page[self.per_page:]

        if not results and not self.allow_empty_first_page:
            raise paginator.EmptyPage("That page contains no results")

        known_count = ((number - 1) * self.per_page) + len(results)
        _update_known_count(self.queryset_id, known_count)

        page = self._get_page(results[:self.per_page], number, self)

        if len(page.object_list) > self.per_page-1:
            index = self.per_page-1
        else:
            index = len(page.object_list)-1

        if results:
            _store_marker(
                self.queryset_id,
                number,
                getattr(page.object_list[index], self.field_required)
            )

        return page


text:
package com.piticlistudio.playednext.company.model.entity.datasource;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Test cases for RealmCompany
 * Created by jorge.garcia on 13/02/2017.
 */
public class RealmCompanyTest {

    RealmCompany data = new RealmCompany(50, "name");

    @Test
    public void getId() throws Exception {

        // Act
        data.setId(100);

        assertEquals(100, data.getId());
    }

    @Test
    public void getName() throws Exception {
        assertEquals("name", data.getName());
    }

}


text: <?php echo $this->system_library->settings['blog_title']; ?>


text:
Template.visitorInfo.helpers({
	user() {
		const user = Template.instance().user.get();
		if (user && user.userAgent) {
			var ua = new UAParser();
			ua.setUA(user.userAgent);

			user.os = ua.getOS().name + ' ' + ua.getOS().version;
			if (['Mac OS', 'iOS'].indexOf(ua.getOS().name) !== -1) {
				user.osIcon = 'icon-apple';
			} else {
				user.osIcon = 'icon-' + ua.getOS().name.toLowerCase();
			}
			user.browser = ua.getBrowser().name + ' ' + ua.getBrowser().version;
			user.browserIcon = 'icon-' + ua.getBrowser().name.toLowerCase();
		}

		return user;
	},

	room() {
		return ChatRoom.findOne({ _id: this.rid });
	},

	joinTags() {
		return this.tags.join(', ');
	},

	customFields() {
		let fields = [];
		let livechatData = {};
		const user = Template.instance().user.get();
		if (user) {
			livechatData = _.extend(livechatData, user.livechatData);
		}

		let data = Template.currentData();
		if (data && data.rid) {
			let room = RocketChat.models.Rooms.findOne(data.rid);
			if (room) {
				livechatData = _.extend(livechatData, room.livechatData);
			}
		}

		if (!_.isEmpty(livechatData)) {
			for (let _id in livechatData) {
				if (livechatData.hasOwnProperty(_id)) {
					let customFields = Template.instance().customFields.get();
					if (customFields) {
						let field = _.findWhere(customFields, { _id: _id });
						if (field && field.visibility !== 'hidden') {
							fields.push({ label: field.label, value: livechatData[_id] });
						}
					}
				}
			}
			return fields;
		}
	},

	createdAt() {
		if (!this.createdAt) {
			return '';
		}
		return moment(this.createdAt).format('L LTS');
	},

	lastLogin() {
		if (!this.lastLogin) {
			return '';
		}
		return moment(this.lastLogin).format('L LTS');
	},

	editing() {
		return Template.instance().editing.get();
	},

	editDetails() {
		const instance = Template.instance();
		const user = instance.user.get();
		return {
			visitorId: user ? user._id : null,
			roomId: this.rid,
			save() {
				instance.editing.set(false);
			},
			cancel() {
				instance.editing.set(false);
			}
		};
	},

	roomOpen() {
		const room = ChatRoom.findOne({ _id: this.rid });

		return room.open;
	}
});

Template.visitorInfo.events({
	'click .edit-livechat'(event, instance) {
		event.preventDefault();

		instance.editing.set(true);
	},
	'click .close-livechat'(event) {
		event.preventDefault();

		swal({
			title: t('Closing_chat'),
			type: 'input',
			inputPlaceholder: t('Please_add_a_comment'),
			showCancelButton: true,
			closeOnConfirm: false
		}, (inputValue) => {
			if (!inputValue) {
				swal.showInputError(t('Please_add_a_comment_to_close_the_room'));
				return false;
			}

			if (s.trim(inputValue) === '') {
				swal.showInputError(t('Please_add_a_comment_to_close_the_room'));
				return false;
			}

			Meteor.call('livechat:closeRoom', this.rid, inputValue, function(error/*, result*/) {
				if (error) {
					return handleError(error);
				}
				swal({
					title: t('Chat_closed'),
					text: t('Chat_closed_successfully'),
					type: 'success',
					timer: 1000,
					showConfirmButton: false
				});
			});
		});
	}
});

Template.visitorInfo.onCreated(function() {
	this.visitorToken = new ReactiveVar(null);
	this.customFields = new ReactiveVar([]);
	this.editing = new ReactiveVar(false);
	this.user = new ReactiveVar();

	Meteor.call('livechat:getCustomFields', (err, customFields) => {
		if (customFields) {
			this.customFields.set(customFields);
		}
	});

	var currentData = Template.currentData();

	if (currentData && currentData.rid) {
		this.autorun(() => {
			var room = ChatRoom.findOne(currentData.rid);
			if (room && room.v && room.v.token) {
				this.visitorToken.set(room.v.token);
			} else {
				this.visitorToken.set();
			}
		});

		this.subscribe('livechat:visitorInfo', currentData.rid);
	}

	this.autorun(() => {
		this.user.set(Meteor.users.findOne({ 'profile.token': this.visitorToken.get() }));
	});
});


text:
import importlib

from oslo_config import cfg
from oslo_config import generator as gn

from jor import utils

__all__ = ['get_conf', 'get_config_file']

LOG = utils.get_log(__name__)

DYNAMIC_SECTION_PROJECTS = {
    'cinder': 'jor.getconf.dynamic_section.cinder'
}

def get_conf(conf_file=None, config_file=None):
    """Get CONF object for specific project.
    """
    conf = cfg.ConfigOpts()
    gn.register_cli_opts(conf)
    oslo_args = ['--config-file', conf_file]
    conf(oslo_args)
    groups = gn._get_groups(gn._list_opts(conf.namespace))

    # Make new CONF
    new_conf = cfg.ConfigOpts()
    project_args = ['--config-file', config_file]
    new_conf(project_args)
    all_namespaces = []
    for k, v in groups.items():
        group = cfg.OptGroup(k)
        try:
            namespaces = v.get('namespaces', [])
        except Exception:
            namespaces = v
        list_opts = []
        for namespace in namespaces:
            all_namespaces.append(namespace[0])
            list_opts.extend(namespace[1])
        new_conf.register_group(group)
        if k == 'DEFAULT':
            LOG.info("Force register DEFAULT group to easier access "
                    "configuration values in DEFAULT group.")
            try:
                new_conf.register_opts(list_opts)
            except cfg.DuplicateOptError:
                pass
        LOG.info("Register group %s into new_conf.", group.name)
        new_conf.register_opts(list_opts, group=group)
    projects = []
    for namespace in all_namespaces:
        sp = namespace.split('.')
        LOG.info("Get project name from namespaces.")
        if 'oslo' in namespace:
            LOG.info("Support getting project name for Oslo projects.")
            projects.append(".".join(sp[:2]))
        else:
            projects.append(sp[0])

    for project in projects:
        LOG.info("Autoload all dynamic section.")
        try:
            get_name_module = DYNAMIC_SECTION_PROJECTS[project]
        except KeyError:
            LOG.info("%s project does not have dynamic section or "
                    "not is not supported now.")
            continue
        dynamic = importlib.import_module(get_name_module)
        dynamic.register_dynamic_section(new_conf)

    return new_conf, set(projects)

def get_ne_default(conf=None):
    """Get not equal default value option.
    """
    ne_dict = []
    if isinstance(conf, cfg.ConfigOpts):
        for name, group in conf._groups.items():
            for option, opt in group._opts.items():
                if conf[name][option] != opt['opt'].default:
                    ne_dict.append((name, option))
    return ne_dict

def get_config_file(conf=None):
    """Parsing config file following ini format.
    """
    _list = []
    if conf:
        section_options = conf._namespace._parsed[0]
        for name, section in section_options.items():
            for option, value in section.items():
                _list.append((name, option, value[0]))
    return _list


text:
<?php declare(strict_types=1);

namespace BFITech\ZapOAuth;

/**
 * Error class.
 */
class OAuthError extends \Exception {

	/** Missing input data. */
	const INCOMPLETE_DATA = 0x0100;

	/** Attempt to connect to unregistered service. */
	const SERVICE_UNKNOWN = 0x0101;

	/** Provider doesn't return HTTP 200. */
	const SERVICE_ERROR = 0x0102;

	/** Access URL not obtained, OAuth1.0. */
	const ACCESS_URL_MISSING =  0x0103;

	/** Token missing from parsed URL. */
	const TOKEN_MISSING = 0x0104;
}


text:
clear all
close all
clc

% Lecture 16 practical:

%%
%--------------------------------------------------------------------------
% Numerical integration
%--------------------------------------------------------------------------

addpath('./ncm'); % tell MATLAB to look in this folder for functions

%% Let's start with a default example from MATLAB

ezplot(@humps,[0,1]);

%%

quadgui(@humps,0,1,1e-4);

%% Setup the integrand

f = @(x) sin(x); % use an anonymous function

quadgui( f, 0, pi, 1.e-1 );

%%

tic
Q = quad( f, 0, pi, 1.e-8 ); % old method (note orange line under function name)
toc

tic
I = integral( f, 0, pi, 'AbsTol', 1.e-8 ); % new method
toc

%% what about with lower tolerance?

quadgui( f, 0, pi, 1.e-3 );

%% do not have to use anonymous function

quadgui('cos(x)', 0, (9/2)*pi, 1.e-6 );

% Notice how weird the function looks when you first use the midpoint rule
% to split it up into rectangles.

%% You can really do almost any type of integral

f = @(x) 1./sqrt(1+x.^4);

quadgui( f, 0, 1 );

%% another example

quadgui( 't^(8/3)*(1-t)^(10/3)' ,0, 1, 1.e-8 );

%% another example

f= @(x) sin(x)./x;

quadgui( f, 0, pi, 1.0e-4 );

%% what happened?

% We divided by zero and eventually we should reach a recursion limit.
% This is because there is a "singularity" in the function at x=0.

% One solution is
quadgui( f, realmin, pi, 1.0e-4 );

%% another option is to make a smarter function

quadgui( @sinc, 0, pi, 1.0e-4 ); % then call this anonymous function

%% What about if your integral depends on other parameters?

% Well we need to build more complicated functions then.

f = @(t,z,w) t.^(z-1) .* (1-t).^(w-1);

z = 8/3;
w = 10/3;
tol = 1.0e-5;

quadgui( f, 0, 1, tol, z, w); % all values passed after tol will be given to the function f

%%
%
% NOTE: Example in this practical are taken from the Quadrature Chapter
% (chapter 6) in https://www.mathworks.com/moler/chapters.html


text:
import sys
import requests

reload(sys)
sys.setdefaultencoding('utf-8')

# requests api参照: https://github.com/kennethreitz/requests

url = "http://www.baidu.com"
data = requests.get(url)
print "请求返回状态码: %s, 返回内容: %s" % (data.status_code, data.content)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome()

browser.get('http://www.baidu.com')
assert "百度" in browser.title
print browser.title

browser.quit()


text:
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script.  Only    //
// add custom code in the designated areas or it will be overwritten during  //
// the next update.                                                          //
//-----------------------------------NOTICE----------------------------------//

//--BEGIN FILE HEAD CUSTOM CODE--//

//--END CUSTOM CODE--//

#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/BSLagBoneController.h"
using namespace Niflib;

//Definition of TYPE constant
const Type BSLagBoneController::TYPE("BSLagBoneController", &NiTimeController::TYPE );

BSLagBoneController::BSLagBoneController() : linearVelocity(0.0f), linearRotation(0.0f), maximumDistance(0.0f) {
	//--BEGIN CONSTRUCTOR CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

BSLagBoneController::~BSLagBoneController() {
	//--BEGIN DESTRUCTOR CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

const Type & BSLagBoneController::GetType() const {
	return TYPE;
}

NiObject * BSLagBoneController::Create() {
	return new BSLagBoneController;
}

void BSLagBoneController::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) {
	//--BEGIN PRE-READ CUSTOM CODE--//

	//--END CUSTOM CODE--//

	NiTimeController::Read( in, link_stack, info );
	NifStream( linearVelocity, in, info );
	NifStream( linearRotation, in, info );
	NifStream( maximumDistance, in, info );

	//--BEGIN POST-READ CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

void BSLagBoneController::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const {
	//--BEGIN PRE-WRITE CUSTOM CODE--//

	//--END CUSTOM CODE--//

	NiTimeController::Write( out, link_map, missing_link_stack, info );
	NifStream( linearVelocity, out, info );
	NifStream( linearRotation, out, info );
	NifStream( maximumDistance, out, info );

	//--BEGIN POST-WRITE CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

std::string BSLagBoneController::asString( bool verbose ) const {
	//--BEGIN PRE-STRING CUSTOM CODE--//

	//--END CUSTOM CODE--//

	stringstream out;
	out << NiTimeController::asString();
	out << "  Linear Velocity:  " << linearVelocity << endl;
	out << "  Linear Rotation:  " << linearRotation << endl;
	out << "  Maximum Distance:  " << maximumDistance << endl;
	return out.str();

	//--BEGIN POST-STRING CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

void BSLagBoneController::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info ) {
	//--BEGIN PRE-FIXLINKS CUSTOM CODE--//

	//--END CUSTOM CODE--//

	NiTimeController::FixLinks( objects, link_stack, missing_link_stack, info );

	//--BEGIN POST-FIXLINKS CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

std::list<NiObjectRef> BSLagBoneController::GetRefs() const {
	list<Ref<NiObject> > refs;
	refs = NiTimeController::GetRefs();
	return refs;
}

std::list<NiObject *> BSLagBoneController::GetPtrs() const {
	list<NiObject *> ptrs;
	ptrs = NiTimeController::GetPtrs();
	return ptrs;
}

/***Begin Example Naive Implementation****

float BSLagBoneController::GetLinearVelocity() const {
	return linearVelocity;
}

void BSLagBoneController::SetLinearVelocity( float value ) {
	linearVelocity = value;
}

float BSLagBoneController::GetLinearRotation() const {
	return linearRotation;
}

void BSLagBoneController::SetLinearRotation( float value ) {
	linearRotation = value;
}

float BSLagBoneController::GetMaximumDistance() const {
	return maximumDistance;
}

void BSLagBoneController::SetMaximumDistance( float value ) {
	maximumDistance = value;
}

****End Example Naive Implementation***/

//--BEGIN MISC CUSTOM CODE--//

//--END CUSTOM CODE--//


text:
package lib;

import javax.swing.JFrame;

import java.awt.Graphics;
import java.awt.Color;
import java.awt.image.BufferedImage;

public class PlotWindow extends JFrame
{
    static final int SIZE = 600;
    BufferedImage bufferedImage = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_RGB);
    static PlotWindow plotWindow;
    static double lx, rx, ty, by;

    private PlotWindow(int lx, int ty, int rx, int by)
    {
        PlotWindow.lx = (double)lx / 100;
        PlotWindow.ty = (double)ty / 100;
        PlotWindow.rx = (double)rx / 100;
        PlotWindow.by = (double)by / 100;
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(SIZE, SIZE);
        setVisible(true);
    }

    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawImage(bufferedImage, 0, 0, null);
    }

    public static void create(int lx, int ty, int rx, int by)
    {
        plotWindow = new PlotWindow(lx, ty, rx, by);
    }

    public static int setRGBColor(int x, int y, Color c)
    {
        plotWindow.setRGBColor(x, y, c.getRGB());
        return 0;
    }

    void setRGBColor(int x, int y, int c)
    {
        bufferedImage.setRGB(x, y, c);
        if (x == SIZE - 1 && y == SIZE - 1)
            repaint();
    }

    public static Complex toComplex(int x, int y)
    {
        double xscale = (double)x / SIZE, yscale = (double)y / SIZE;
        return new Complex(xscale * (rx-lx) + lx, yscale * (ty-by) + by);
    }
}


text:
require 'rails_helper'

describe Friendship do
  let(:user){FactoryGirl.create(:user)}

  context "validations" do
    it {should validate_presence_of :user}
    it {should validate_presence_of :friend}
  end

  context "methods" do
    context "#current_friend_ids" do
      it "returns a list of current friends" do
        expect(Friendship.current_friend_ids(user)).to be_an_instance_of(Array)
      end
    end

    it "returns a list of pending friend requests" do
       expect(Friendship.current_friend_request_ids(user)).to be_an_instance_of(Array)
    end
  end
end


text:
package org.apache.isis.core.metamodel.facets.all.i18n;

import org.apache.isis.applib.services.i18n.TranslationService;
import org.apache.isis.core.metamodel.facetapi.FacetAbstract;
import org.apache.isis.core.metamodel.facetapi.IdentifiedHolder;
import org.apache.isis.core.metamodel.facets.all.named.NamedFacet;

public class NamedFacetTranslated extends FacetAbstract implements NamedFacet {

    final TranslationService translationService;
    String context;
    String originalText;

    public NamedFacetTranslated(
            final String context, final String originalText,
            final TranslationService translationService,
            final IdentifiedHolder facetHolder) {
        super(NamedFacet.class, facetHolder, Derivation.NOT_DERIVED);
        this.context = context;
        this.originalText = originalText;
        this.translationService = translationService;

        if(translationService.getMode().isWrite()) {
            // force PoWriter to be called to capture this text that needs translating
            translateText();
        }
    }

    @Override
    public String value() {
        return translateText();
    }

    private String translateText() {
        return translationService.translate(context, originalText);
    }

    @Override
    public boolean escaped() {
        final NamedFacet underlyingFacet = (NamedFacet) getUnderlyingFacet();
        return underlyingFacet != null && underlyingFacet.escaped();
    }
}


text:
$().ready(function() {
    // console.log('in layout.js');
});


text:
.class final Landroid/app/Instrumentation$EmptyRunnable;
.super Ljava/lang/Object;
.source "Instrumentation.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/Instrumentation;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1a
    name = "EmptyRunnable"
.end annotation

# direct methods
.method private constructor <init>()V
    .registers 1

    .prologue
    .line 1883
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/app/Instrumentation$EmptyRunnable;)V
    .registers 2

    .prologue
    invoke-direct {p0}, Landroid/app/Instrumentation$EmptyRunnable;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .registers 1

    .prologue
    .line 1884
    return-void
.end method


text:
using namespace std;
namespace fs = boost::filesystem;

namespace dsa {

string_ string_from_file(const string_ &file_path) {
  std::vector<uint8_t> vec{};

  if (fs::exists(file_path) && fs::is_regular_file(file_path)) {
    size_t size = fs::file_size(file_path);

    if (size) {
      fs::ifstream ifs(file_path, std::ios::in | std::ios::binary);
      if (ifs) {
        vec.resize(static_cast<size_t>(size));
        ifs.read(reinterpret_cast<char *>(&vec.front()),
                 static_cast<size_t>(size));
        ifs.close();
      } else {
        LOG_ERROR(__FILENAME__,
                  LOG << "Unable to open " << file_path << " file to read");
      }
    }
  } else {
    LOG_FINE(__FILENAME__, LOG << "there is no file to read " << file_path);
  }

  string_ content(vec.begin(), vec.end());

  return content;
}

void string_to_file(const string_ &data, const string_ &file_path) {
  try {
    fs::ofstream ofs(file_path,
                     std::ios::out | std::ios::trunc | std::ios::binary);
    if (ofs) {
      ofs << data;
      ofs.close();
    } else {
      LOG_ERROR(__FILENAME__,
                LOG << "Unable to open " << file_path << " file to write");
    }
  } catch (const fs::filesystem_error &ex) {
    LOG_ERROR(__FILENAME__, LOG << "Write failed for " << file_path << " file");
  }
}

string_ string_from_storage(const string_ &key, StorageBucket &storage_bucket) {
  string_ data;
  bool callback_called = false;
  auto read_callback = [&](string_ storage_key, std::vector<uint8_t> vec,
                           BucketReadStatus read_status) {
    string_ content(vec.begin(), vec.end());
    data = content;
    callback_called = true;
  };
  storage_bucket.read(key, read_callback);
  if (!callback_called) {
    LOG_FATAL(__FILENAME__,
              LOG << "Storage does not support synchronize reading");
  }
  return data;
}
void string_to_storage(const string_ &data, const string_ &key,
                       StorageBucket &storage_bucket) {
  auto content =
      new RefCountBytes(&data.c_str()[0], &data.c_str()[strlen(data.c_str())]);

  storage_bucket.write(key, std::forward<RefCountBytes *>(content));
}

std::vector<uint8_t> get_random_byte_array(int len) {
  if (!IS_RAND_INITIALIZED) {
    RAND_poll();
    IS_RAND_INITIALIZED = 1;
  }
  std::vector<uint8_t> buffer(len);
  RAND_bytes(buffer.data(), len);
  return buffer;
}
static char get_random_char(std::vector<uint8_t>::iterator &current,
                            const std::vector<uint8_t>::iterator &end) {
  while (current != end) {
    char n = static_cast<char>(*current++ & 0x7F);
    if ((n >= '0' && n <= '9') || (n >= 'A' && n <= 'Z') ||
        (n >= 'a' && n <= 'z')) {
      return n;
    }
  }
  return 0;
}
string_ generate_random_string(int len) {
  string_ randStr;
  auto bytes = get_random_byte_array(4 * len);
  auto it = bytes.begin();
  for (int i = 0; i < len; ++i) {
    auto next_char = get_random_char(it, bytes.end());
    while (next_char <= 0) {
      // just in case bytes doesn't have enough valid char
      bytes = get_random_byte_array(2 * len);
      next_char = get_random_char(it, bytes.end());
    }
    randStr.push_back(next_char);
  }
  return randStr;
}

string_ get_master_token_from_storage(StorageBucket &storage_bucket,
                                      const string_ &key,
                                      bool force_to_generate_one) {
  string_ token = string_from_storage(key, storage_bucket);
  if (token.length() == 48) return std::move(token);

  if (force_to_generate_one) {
    token = generate_random_string(48);
    string_to_storage(token, key, storage_bucket);
  } else {
    return "";
  }

  return std::move(token);
}
}  // namespace dsa


text:
#pragma once

#if ENABLE(DFG_JIT)

#include "Structure.h"
#include <wtf/HashMap.h>

namespace JSC { namespace DFG {

// This object is a key for finding a property's type. It's a tuple of Structure* and UniquedStringImpl*.

class PropertyTypeKey {
public:
    PropertyTypeKey()
        : m_structure(nullptr)
        , m_uid(nullptr)
    {
    }

    PropertyTypeKey(Structure* structure, UniquedStringImpl* uid)
        : m_structure(structure)
        , m_uid(uid)
    {
    }

    PropertyTypeKey(WTF::HashTableDeletedValueType)
        : m_structure(nullptr)
        , m_uid(deletedUID())
    {
    }

    explicit operator bool() const { return m_structure && m_uid; }

    Structure* structure() const { return m_structure; }
    UniquedStringImpl* uid() const { return m_uid; }

    bool operator==(const PropertyTypeKey& other) const
    {
        return m_structure == other.m_structure
            && m_uid == other.m_uid;
    }

    bool operator!=(const PropertyTypeKey& other) const
    {
        return !(*this == other);
    }

    unsigned hash() const
    {
        return WTF::PtrHash<Structure*>::hash(m_structure) + WTF::PtrHash<UniquedStringImpl*>::hash(m_uid);
    }

    bool isHashTableDeletedValue() const
    {
        return !m_structure && m_uid == deletedUID();
    }

    void dumpInContext(PrintStream& out, DumpContext* context) const
    {
        out.print(pointerDumpInContext(m_structure, context), "+", m_uid);
    }

    void dump(PrintStream& out) const
    {
        dumpInContext(out, nullptr);
    }

private:
    static UniquedStringImpl* deletedUID()
    {
        return bitwise_cast<UniquedStringImpl*>(static_cast<intptr_t>(1));
    }

    Structure* m_structure;
    UniquedStringImpl* m_uid;
};

struct PropertyTypeKeyHash {
    static unsigned hash(const PropertyTypeKey& key) { return key.hash(); }
    static bool equal(const PropertyTypeKey& a, const PropertyTypeKey& b) { return a == b; }
    static const bool safeToCompareToEmptyOrDeleted = true;
};

} } // namespace JSC::DFG

namespace WTF {

template<typename T> struct DefaultHash;
template<> struct DefaultHash<JSC::DFG::PropertyTypeKey> {
    typedef JSC::DFG::PropertyTypeKeyHash Hash;
};

template<typename T> struct HashTraits;
template<> struct HashTraits<JSC::DFG::PropertyTypeKey> : SimpleClassHashTraits<JSC::DFG::PropertyTypeKey> {
    static const bool emptyValueIsZero = false;
};

} // namespace WTF

#endif // ENABLE(DFG_JIT)


text:
[return](../README.md) to notes.

# Javascript Notes

## Basics
Wikipedia describes [Javascript](http://en.wikipedia.org/wiki/JavaScript)), often abbreviated as JS, as a high-level, dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted programming language. Alongside HTML and CSS, JavaScript is one of the three core technologies of World Wide Web content production.

## Books
[Javascript: The Good Parts](http://shop.oreilly.com/product/9780596517748) is a good introduction.

### Distnictions
[Method vs. Function Invocation Pattern](https://stackoverflow.com/a/27099595/1134881) (pages 28-29).

## [Node and Jest](./node/README.md)
Node provides a runtime environment for Javascript such that it can run on a server.
Jest is a handy automated test tool for javascript that works with node.

[Node](./javascript/README.md)
Wikipedia describes [Node.js](http://en.wikipedia.org/wiki/Node.js) as an open-source, cross-platform JavaScript run-time environment for executing JavaScript code server-side.

## [AngularJS](http://en.wikipedia.org/wiki/AngularJS)


text:
using MeTLLib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace MeTLLibTests
{

    ///
    ///This is a test class for ClientConnection_QuizQuestionAvailableEventArgsTest and is intended
    ///to contain all ClientConnection_QuizQuestionAvailableEventArgsTest Unit Tests
    ///
    [TestClass()]
    public class ClientConnection_QuizQuestionAvailableEventArgsTest
    {

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        ///
        ///A test for QuizQuestionAvailableEventArgs Constructor
        ///
        [TestMethod()]
        public void ClientConnection_QuizQuestionAvailableEventArgsConstructorTest()
        {
            ClientConnection.QuizQuestionAvailableEventArgs target = new ClientConnection.QuizQuestionAvailableEventArgs();
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
    }
}


text:
[![npm version](https://img.shields.io/npm/v/circular-iterator.svg)](https://www.npmjs.com/package/circular-iterator)
![License](https://img.shields.io/npm/l/circular-iterator.svg)

[![Build Status](https://img.shields.io/travis/alvaropinot/circular-iterator.svg)](https://travis-ci.org/alvaropinot/circular-iterator.svg)
[![Coverage](https://img.shields.io/codeclimate/coverage/github/alvaropinot/circular-iterator.svg)](https://codeclimate.com/github/alvaropinot/circular-iterator/coverage)
[![Code Climate](https://img.shields.io/codeclimate/github/alvaropinot/circular-iterator.svg)](https://codeclimate.com/github/alvaropinot/circular-iterator)
![dependencies](https://img.shields.io/david/alvaropinot/circular-iterator.svg)
![dev dependencies](https://img.shields.io/david/dev/alvaropinot/circular-iterator.svg)

# circular-iterator
Circular iteration over any array, the fancy way.

## Installation
You can install circular-iterator using npm.

```bash
npm install --save circular-iterator
```

## Usage
Just require the module.

```javascript
const circularIterator = require('circular-iterator');
const iterator = circularIterator([1, 2, 3]);
console.log(iterator.next().value); //1
console.log(iterator.next().value); //2
console.log(iterator.next().value); //3
console.log(iterator.next().value); //1
```

[Try it in your browser](https://tonicdev.com/npm/circular-iterator)

### ES5
Provided ES5 distribution was transformed with [regenerator](https://github.com/facebook/regenerator) tool.

```javascript
const circularIterator = require('circular-iterator/es5');
```

or
```javascript
const circularIterator = require('circular-iterator/es5-with-runtime');
```
> Include regenerator `runtime`

### Use like a Snippet
`circular-interator` is a very simple piece of code well done and without dependencies. Just copy-paste [circularIterator](https://github.com/alvaropinot/circular-iterator/blob/master/index.js#L3) is needed.

## Example
A fancy players turns controller.
```javascript
const circularIterator = require('circular-iterator');

// Some players
const players = [
  {
    name: 'Player 1'
  },
  {
    name: 'Player 2'
  },
  {
    name: 'Player 3'
  }
];

// Create an iterator with our players.
const turnController = circularIterator(players);

let actualPlayer = turnController.next().value;
// It's Player 1 turn.
console.log('%s is your turn!', actualPlayer.name);

// Timer is done! Let's see who's next.
actualPlayer = turnController.next().value;
// It's Player 2 turn.
console.log('%s is your turn!', actualPlayer.name);

// Timer is done! Let's see who's next.
actualPlayer = turnController.next().value;
// It's Player 3 turn.
console.log('%s is your turn!', actualPlayer.name);

// Timer is done! Let's see who's next.
actualPlayer = turnController.next().value;
// It's Player 1 turn again :D
console.log('%s is your turn!', actualPlayer.name);
```

### Outputs
```
Player 1 is your turn!
Player 2 is your turn!
Player 3 is your turn!
Player 1 is your turn!
```

## Credits

### author
* Alvaro Pinot <> [@alvaropinot](https://github.com/alvaropinot)

### contributors
* [@bySabi](https://github.com/bySabi)

## License

[MIT][mit-license]

[mit-license]:./LICENSE


text:
<!--
   This file is part of the X12Parser library that provides tools to
   manipulate X12 messages using Ruby native syntax.

   http://x12parser.rubyforge.org

   Copyright (C) 2009 APP Design, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

   $Id: G84.xml 78 2009-05-12 22:27:26Z ikk $
-->

<Segment name="G84" comment="To specify summary details of total items in terms of quantity or amount">
  <Field name="Quantity" type="double" required="y" min="1" max="15" comment="Numeric value of quantity"/>
  <Field name="TotalInvoiceAmount" type="double" required="y" min="1" max="10" comment="Amount of invoice (including charges, less allowances) before terms discount (if discount is applicable)"/>
  <Field name="TotalDepositDollarAmount" type="double" required="y" min="1" max="6" comment="Sum of deposit amounts separately identified"/>
</Segment>


text:
"use strict";

const opsgenie = require('../../');
require('../configure');

let create_incident_json = {
    "message": "Some Message",
    "serviceId": "Server_ID"
};

opsgenie.incident.create(create_incident_json, function (error, alert) {
    if (error) {
        console.error(error);
    } else {
        console.log("Create Incident Response");
        console.log(alert);
    }
});


text:
using Entitas;
using Entitas.CodeGeneration.Attributes;

[Context("Test"), Unique]
public sealed class UniqueStandardComponent : IComponent {
    public string value;
}


text:
EFFECT.Mat = Material("effects/blood_core")

local function DecalMaker ( Particle, Pos, Norm )
	util.Decal("BeerSplash", Pos + Norm, Pos - Norm);

	Particle:SetEndSize(math.random(14, 20));
	Particle:SetEndAlpha(0);
	Particle:SetDieTime(3);
end

function EFFECT:Init ( Data )
	self.Barfer = Data:GetEntity()
	self.DieTime = CurTime() + math.Rand(.25, 1.5)

	if !self.Barfer or !self.Barfer:IsValid() or !self.Barfer:IsPlayer() then return false; end

	self.Emitter = ParticleEmitter(self.Barfer:EyePos());

	sound.Play(Sound("npc/zombie/zombie_pain3.wav"), self.Barfer:EyePos(), 75, 100);
end

function EFFECT:Think()
	if !self.Barfer or !self.Barfer:IsValid() or !self.Barfer:IsPlayer() or CurTime() > self.DieTime then self.Emitter:Finish(); return false; end

	local SpawnPos = self.Barfer:EyePos() + self.Barfer:EyeAngles():Forward() * 10;
	local Dir = self.Barfer:GetAimVector();

	local Particle = self.Emitter:Add("effects/blood_core", SpawnPos);

	Particle:SetVelocity((Dir + VectorRand() * 0.1) * math.Rand(200, 300));
	Particle:SetDieTime(20);

	Particle:SetStartAlpha(255);
	Particle:SetEndAlpha(100);

	Particle:SetStartSize(math.random(15, 20));
	Particle:SetEndSize(math.random(10, 15));

	Particle:SetColor(128, 80, 0);
	Particle:SetCollide(true);
	Particle:SetGravity(Vector(0, 0, -450));
	Particle:SetRollDelta(math.random(-10, 10));
	Particle:SetCollideCallback(DecalMaker);

	return true;
end

function EFFECT:Render() end


text: Added support for QRadar V3.


text:
// Code generated by informer-gen. DO NOT EDIT.

package v1alpha1

import (
	internalinterfaces "github.com/knative/observability/pkg/client/informers/externalversions/internalinterfaces"
)

// Interface provides access to all the informers in this group version.
type Interface interface {
	// ClusterLogSinks returns a ClusterLogSinkInformer.
	ClusterLogSinks() ClusterLogSinkInformer
	// ClusterMetricSinks returns a ClusterMetricSinkInformer.
	ClusterMetricSinks() ClusterMetricSinkInformer
	// LogSinks returns a LogSinkInformer.
	LogSinks() LogSinkInformer
	// MetricSinks returns a MetricSinkInformer.
	MetricSinks() MetricSinkInformer
}

type version struct {
	factory          internalinterfaces.SharedInformerFactory
	namespace        string
	tweakListOptions internalinterfaces.TweakListOptionsFunc
}

// New returns a new Interface.
func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {
	return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}
}

// ClusterLogSinks returns a ClusterLogSinkInformer.
func (v *version) ClusterLogSinks() ClusterLogSinkInformer {
	return &clusterLogSinkInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}

// ClusterMetricSinks returns a ClusterMetricSinkInformer.
func (v *version) ClusterMetricSinks() ClusterMetricSinkInformer {
	return &clusterMetricSinkInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}

// LogSinks returns a LogSinkInformer.
func (v *version) LogSinks() LogSinkInformer {
	return &logSinkInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}

// MetricSinks returns a MetricSinkInformer.
func (v *version) MetricSinks() MetricSinkInformer {
	return &metricSinkInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}


text:
<?php

Yii::import('translate.widgets.configurationStatus.*');

/**
 *
 * @author Louis A. DaPrato <l.daprato@gmail.com>
 *
 */
class InstallableWidget extends CWidget
{

	public $component;

	public $url = 'install';

	public $buttonText = 'Install';

	public $loadingText = 'Installing...';

	public $cancelText = 'Cancel';

	public $confirmText = 'Confirm';

	public $closeText = 'Close';

	public $statusCssClass = 'status';

	public $buttonHtmlOptions = array();

	public $dialogTitle = 'Installer Dialog';

	public $dialogOptions = array(
		'autoOpen' => false,
		'modal' => true,
		'width' => 'auto',
		'height' => 'auto'
	);

	public $installerOptions = array();

	public $progressBarOptions = array();

	private $_installableModel;

	public static function actions()
	{
		return array(
			'install' => 'translate.widgets.configurationStatus.actions.InstallAction',
		);
	}

	public function init()
	{
		$this->_installableModel = new InstallableModel($this->component);

		$this->attachBehavior('LDPublishAssetsBehavior', array('class' => 'ext.LDPublishAssetsBehavior.LDPublishAssetsBehavior', 'assetsDir' => dirname(__FILE__).DIRECTORY_SEPARATOR.'assets'));

		$this->_installableModel->validate(null, false);
	}

	public function run($return = false)
	{
		// Set all default values now instead of in view file just in case we need a generated value after running this widget.
		$id = $this->getId();
		$this->installerOptions['component'] = $this->getModel()->getComponentID();
		$this->installerOptions['url'] = $this->url;
		$this->installerOptions['loadingText'] = $this->loadingText;
		$this->installerOptions['cancelText'] = $this->cancelText;
		$this->installerOptions['confirmText'] = $this->confirmText;
		$this->installerOptions['closeText'] = $this->closeText;

		if(!isset($this->installerOptions['statusId']))
		{
			$this->installerOptions['statusId'] = 'status_'.$id;
		}

		if(!isset($this->installerOptions['dialogId']))
		{
			$this->installerOptions['dialogId'] = 'dialog_'.$id;
		}

		if(!isset($this->installerOptions['progressBarId']))
		{
			$this->installerOptions['progressBarId'] = isset($this->progressBarOptions['id']) ? $this->progressBarOptions['id'] : 'progress_'.$id;
		}

		$this->dialogOptions['title'] = $this->dialogTitle;

		$this->buttonHtmlOptions['onClick'] = 'jQuery("#'.$id.'").tInstaller("install");';

		if(!isset($this->progressBarOptions['id']))
		{
			$this->progressBarOptions['id'] = $this->installerOptions['progressBarId'];
		}
		$this->progressBarOptions['value'] = 100;
		$this->installerOptions['progressBarSelector'] = 'div#'.$this->progressBarOptions['id'];

		return $this->render('installer',
				array(
					'id' => $id,
					'buttonText' => $this->buttonText,
					'statusCssClass' => $this->statusCssClass,
					'installerOptions' => $this->installerOptions,
					'buttonHtmlOptions' => $this->buttonHtmlOptions,
					'dialogOptions' => $this->dialogOptions,
					'progressBarOptions' => $this->progressBarOptions,
					'assetsUrl' => $this->getAssetsUrl()
				),
				$return
		);
	}

	public function getModel()
	{
		return $this->_installableModel;
	}

	public static function getStatusMessage($status)
	{
		switch($status)
		{
			case ConfigurationStatusModel::OK;
				return TranslateModule::translate('OK');
			case ConfigurationStatusModel::HAS_WARNINGS;
				return TranslateModule::translate('Has Warnings');
			case ConfigurationStatusModel::HAS_ERRORS;
				return TranslateModule::translate('Has Errors');
			default:
				return TranslateModule::translate('Unknown');
		}
	}

	public static function getStatusClass($status)
	{
		switch($status)
		{
			case ConfigurationStatusModel::OK;
				return 'attributeConfigNoError';
			case ConfigurationStatusModel::HAS_WARNINGS;
				return 'attributeConfigWarning';
			case ConfigurationStatusModel::HAS_ERRORS;
				return 'attributeConfigError';
			default:
				return 'attributeConfigError';
		}
	}

	/**
	 * Displays a summary of validation errors for one or several models.
	 * @param mixed $model the models whose input errors are to be displayed. This can be either
	 * a single model or an array of models.
	 * @param string $header a piece of HTML code that appears in front of the errors
	 * @param string $footer a piece of HTML code that appears at the end of the errors
	 * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
	 * A special option named 'firstError' is recognized, which when set true, will
	 * make the error summary to show only the first error message of each attribute.
	 * If this is not set or is false, all error messages will be displayed.
	 * This option has been available since version 1.1.3.
	 * @return string the error summary. Empty if no errors are found.
	 * @see CModel::getErrors
	 * @see errorSummaryCss
	 */
	public static function errorSummary($model, $attribute = null, $header = null, $footer = null, $htmlOptions = array())
	{
		$content = '';
		if(!is_array($model))
		{
			$model = array($model);
		}
		if(isset($htmlOptions['firstError']))
		{
			$firstError = $htmlOptions['firstError'];
			unset($htmlOptions['firstError']);
		}
		else
		{
			$firstError = false;
		}
		foreach($model as $m)
		{
			foreach($m->getErrors($attribute) as $errors)
			{
				foreach((array)$errors as $error)
				{
					if($error != '')
					{
						$content .= "
$error
\n";
					}
					if($firstError)
					{
						break;
					}
				}
			}
		}
		if($content !== '')
		{
			if($header === null)
			{
				$header = '
'.TranslateModule::translate('Please fix the following input errors:').'
';
			}
			if(!isset($htmlOptions['class']))
			{
				$htmlOptions['class'] = CHtml::$errorSummaryCss;
			}
			return CHtml::tag('div', $htmlOptions, $header."\n
\n$content
".$footer);
		}
		return '';
	}

}


text:
package org.kaazing.gateway.client.impl.wseb;

interface UpstreamHandlerFactory {
    UpstreamHandler createUpstreamHandler();
}


text:
<?php
/**
 * Pages sidebar
 */

echo elgg_view('page/elements/comments_block', array(
	'subtypes' => array('page', 'page_top'),
	'owner_guid' => elgg_get_page_owner_guid(),
));

echo elgg_view('page/elements/tagcloud_block', array(
	'subtypes' => array('page', 'page_top'),
	'owner_guid' => elgg_get_page_owner_guid(),
));


text:
- Original: [Release electron v13.0.0-beta.12 - electron/electron](https://github.com/electron/electron/releases/tag/v13.0.0-beta.12)

Note: This is a beta release. Please file new issues for any bugs you find in it.

This release is published to npm under the beta tag and can be installed via `npm install electron@beta`, or `npm install electron@13.0.0-beta.12`.

> Note: これはベータ リリースです。なにかバグを見つけた場合は issue 報告してください。
>
> 本リリースは `beta` タグの [npm](https://www.npmjs.com/package/electron) として公開しており `npm install electron@beta` または `npm i electron@13.0.0-beta.12` でインストールできます。

## Fixes

- Fixed `postData` parameter missing from `new-window` event. [#28542](https://github.com/electron/electron/pull/28542) (Also in [12](https://github.com/electron/electron/pull/28543))
  - `new-window` イベントから (送信されるデータに) `postData` パラメーターが欠けている問題を修正しました
  - これまで省略されていたパラメーターを追加したとのこと、設計的に省略は意図的ではなく偶然だったと予想されている
- Fixed a bug where, when a JumpList task description exceeded 260 characters, the JumpList was empty, despite valid entries. [#28526](https://github.com/electron/electron/pull/28526) (Also in [11](https://github.com/electron/electron/pull/28524), [12](https://github.com/electron/electron/pull/28525))
  - JumpList のタスク説明が 260 文字を超えると有効なエントリーにもかかわらず JumpList が空になる問題を修正しました
  - JumpList における `description` は 260 文字制限を仕様として API リファレンスにもその旨が記載された
- Fixed an issue where errors thrown in functions passed over the `contextBridge` could be displayed incorrectly. [#28446](https://github.com/electron/electron/pull/28446) (Also in [12](https://github.com/electron/electron/pull/28447))
  - `contextBridge` を介して渡された関数内でスローされたエラーが正しく表示されない可能性のある問題を修正しました
  - 例外を明示的にハンドリングしてスローされたエラー情報の取得とコンテキストを考慮した再送信を実装することで修正
- Fixed failing to request file:// resources when web security is disabled. [#28557](https://github.com/electron/electron/pull/28557)
  - Web セキュリティーが無効化されていると file:// リソースのリクエストに失敗する問題を修正しました
  - この状態で `file://` を処理するには明示的な許可が必要なのでそのように対応して修正
- Fixed the handler set with `setWindowOpenHandler` not being invoked when a link was middle-clicked or shift-clicked. [#28536](https://github.com/electron/electron/pull/28536)
  - リンクが中クリックまたは Shift (キー付きで) クリックされた際に `setWindowOpenHandler` が呼び出されないハンドラー設定の問題を修正しました
  - これらの操作はリンク先を別ウィンドウ (タブ) で開くことが期待されているのにハンドラー設定の問題によりそうなっていなかったので修正
- Support `wasm-eval` csp behind `WebAssemblyCSP` flag. [#28569](https://github.com/electron/electron/pull/28569) (Also in [12](https://github.com/electron/electron/pull/28575))
  - `WebAssemblyCSP` フラグの後ろ盾となる `wasm-eval` CSP (Content Security Policy) をサポートしました
  - WASM で `eval` を利用するための CSP がサポートされた
- Transparent windows cannot be maximized using the Windows system menu or by double clicking the title bar. [#28527](https://github.com/electron/electron/pull/28527)
  - Windows のシステム メニュー (の最大化) を利用またはタイトル バーをダブル クリックしても透過ウィンドウは最大化しません
  - 透過ウィンドウの最大化は Electron API のみへ許可する仕様となった


text:
import {Pipe, PipeTransform} from '@angular/core';
import {UploadFile} from '../../shared/models/upload-file';

export const FaFileTypes = [
  {reg: /\.(jpe?g|gif|png|bmp|webp)$/i, type: 'image', icon: 'fa-file-image-o', showImage: true},
  {reg: /\.xlsx?$/i, type: 'excel', icon: 'fa-file-excel-o', showBase: true},
  {reg: /\.docx?$/i, type: 'word', icon: 'fa-file-word-o', showBase: true},
  {reg: /\.pptx?$/i, type: 'powerpoint', icon: 'fa-file-powerpoint-o', showBase: true},
  {reg: /\.pdf$/i, type: 'pdf', icon: 'fa-file-pdf-o', showPdf: true},
  {reg: /\.(txt)$/i, type: 'text', icon: 'fa-file-text-o'},
  {reg: /\.(zip|rar|7z)$/i, type: 'archive', icon: 'fa-file-archive-o'},
  {reg: /\.(wav|mp3)$/i, type: 'audio', icon: 'fa-file-audio-o'},
  {reg: /\.(avi|mp4)$/i, type: 'video', icon: 'fa-file-video-o', showVideo: true}
];
export const defaultFaIcon = 'fa-file-o';

@Pipe({
  name: 'faFileIcon'
})
export class FaFileIconPipe implements PipeTransform {

  transform(uploadFile: UploadFile): string {
    if (uploadFile && uploadFile.fileName) {
      const ft = FaFileTypes.find(it => it.reg.test(uploadFile.fileName));
      return ft && ft.icon || defaultFaIcon;
    }
    return defaultFaIcon;
  }

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace Backlog4net.Internal.Json.CustomFields
{
    public class ListItemSettingJsonImpl : ListItemSetting
    {
        internal class JsonConverter : InterfaceConverter<ListItemSetting, ListItemSettingJsonImpl> { }

        [JsonProperty]
        public long Id { get; private set; }

        [JsonProperty]
        public string Name { get; private set; }

        [JsonProperty]
        public bool AllowInput { get; private set; }

        [JsonProperty]
        public int DisplayOrder { get; private set; }
    }
}


text:
cask 'megasync' do
  version :latest
  sha256 :no_check

  # mega.nz is the official download host per the vendor homepage
  url 'https://mega.nz/MEGAsyncSetup.dmg'
  name 'MEGAsync'
  homepage 'https://mega.co.nz'
  license :gratis

  app 'MEGAsync.app'

  caveats do
    <<-EOS.undent
      #{token} only works if called from /Applications, so you may need to install it with
        brew cask install --appdir=/Applications #{token}

      Alternatively, you can create an extra link in /Applications, after installing
        ln -s '#{staged_path}/MEGAsync.app' '/Applications/MEGAsync.app'
    EOS
  end
end


text:
module Data.Functor.Compose (
    Compose(..),
   ) where

import Control.Applicative
import Data.Foldable (Foldable(foldMap))
import Data.Traversable (Traversable(traverse))

-- | Right-to-left composition of functors.
-- The composition of applicative functors is always applicative,
-- but the composition of monads is not always a monad.
newtype Compose f g a = Compose { getCompose :: f (g a) }

instance (Functor f, Functor g) => Functor (Compose f g) where
    fmap f (Compose x) = Compose (fmap (fmap f) x)

instance (Foldable f, Foldable g) => Foldable (Compose f g) where
    foldMap f (Compose t) = foldMap (foldMap f) t

instance (Traversable f, Traversable g) => Traversable (Compose f g) where
    traverse f (Compose t) = Compose <$> traverse (traverse f) t

instance (Applicative f, Applicative g) => Applicative (Compose f g) where
    pure x = Compose (pure (pure x))
    Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)

instance (Alternative f, Applicative g) => Alternative (Compose f g) where
    empty = Compose empty
    Compose x <|> Compose y = Compose (x <|> y)


text:
using System;

class Program
{
    static void Main(string[] args)
    {
        string firstName, middleName, lastName, bankName, IBAN, BIC;
        ulong firstCreditCardNumber = 5530792034082446, secondCreditCardNumber = 6011925190861841, thirdCreditCardNumber = 4161161926511509;
        float balance;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme.Search" parent="AppTheme">
        <item name="colorBackgroundSearchToolbar">@color/colorBackgroundSearchToolbar</item>
        <item name="colorBackgroundSearch">@color/colorBackgroundSearch</item>
        <item name="colorPrimaryDark">@color/colorSearchPrimaryDark</item>
        <item name="android:colorPrimaryDark">@color/colorSearchPrimaryDark</item>
        <item name="android:statusBarColor">@color/colorSearchPrimaryDark</item>
        <item name="android:windowLightStatusBar">true</item>
    </style>

</resources>


text:
/*
 * File:   FTServiceInterface.cpp
 * Author: rmartins
 *
 * Created on November 11, 2010, 11:10 AM
 */

#include "FTServiceInterface.h"

FTServiceInterface::FTServiceInterface() {
}

FTServiceInterface::FTServiceInterface(const FTServiceInterface& orig) {
}

FTServiceInterface::~FTServiceInterface() {
}


text:
<TITLE>NWChem availability</TITLE>

  At the time of writing the current version of NWChem was 1.2
alpha.  We do not plan to distribute the alpha or beta versions of
NWChem except to formal collaborators with specific needs.  When the
distribution policy changes it will be widely announced.  Until then,
if

 you have an existing collaboration with EMSL staff, or

 you are interested in developing parallel computational chemistry
software within or around NWChem, and

 have independent access to parallel computing resources, and

 are able to share the results of your work with others,

then please contact your collaborators at PNNL or nwchem-support@emsl.pnl.gov for more
information.

Return to NWChem home page

<ADDRESS>Prepared by RJ Harrison: Email: nwchem-support@emsl.pnl.gov.</ADDRESS>