text:
package com.hazelcast.internal.partition.impl;

import com.hazelcast.instance.Node;
import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.internal.partition.InternalPartition;
import com.hazelcast.internal.partition.NonFragmentedServiceNamespace;
import com.hazelcast.internal.partition.PartitionReplicaVersionManager;
import com.hazelcast.internal.partition.operation.PartitionReplicaSyncRequest;
import com.hazelcast.internal.util.counters.MwCounter;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.spi.ExecutionService;
import com.hazelcast.spi.Operation;
import com.hazelcast.spi.ServiceNamespace;
import com.hazelcast.spi.ServiceNamespaceAware;
import com.hazelcast.spi.TaskScheduler;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.PartitionSpecificRunnable;
import com.hazelcast.spi.properties.GroupProperty;
import com.hazelcast.spi.properties.HazelcastProperties;
import com.hazelcast.util.scheduler.EntryTaskScheduler;
import com.hazelcast.util.scheduler.EntryTaskSchedulerFactory;
import com.hazelcast.util.scheduler.ScheduleType;
import com.hazelcast.util.scheduler.ScheduledEntry;
import com.hazelcast.util.scheduler.ScheduledEntryProcessor;
import com.hazelcast.version.Version;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import static com.hazelcast.internal.util.counters.MwCounter.newMwCounter;
import static java.util.Collections.newSetFromMap;

/**
 *
 * Maintains the version values for the partition replicas and manages the replica-related operations for partitions
 *
 */
public class PartitionReplicaManager implements PartitionReplicaVersionManager {

    private final Node node;
    private final NodeEngineImpl nodeEngine;
    private final ILogger logger;
    private final InternalPartitionServiceImpl partitionService;
    private final PartitionStateManager partitionStateManager;

    private final PartitionReplicaVersions[] replicaVersions;
    /** Replica sync requests that have been sent to the target and awaiting response */
    private final Set<ReplicaFragmentSyncInfo> replicaSyncRequests;
    private final EntryTaskScheduler<ReplicaFragmentSyncInfo, Void> replicaSyncTimeoutScheduler;
    @Probe
    private final Semaphore replicaSyncProcessLock;
    @Probe
    private final MwCounter replicaSyncRequestsCounter = newMwCounter();

    private final long partitionMigrationTimeout;
    private final int maxParallelReplications;

    private volatile Version clusterVersion;

    PartitionReplicaManager(Node node, InternalPartitionServiceImpl partitionService) {
        this.node = node;
        this.nodeEngine = node.nodeEngine;
        this.logger = node.getLogger(getClass());
        this.partitionService = partitionService;

        int partitionCount = partitionService.getPartitionCount();
        partitionStateManager = partitionService.getPartitionStateManager();

        HazelcastProperties properties = node.getProperties();
        partitionMigrationTimeout = properties.getMillis(GroupProperty.PARTITION_MIGRATION_TIMEOUT);
        maxParallelReplications = properties.getInteger(GroupProperty.PARTITION_MAX_PARALLEL_REPLICATIONS);
        replicaSyncProcessLock = new Semaphore(maxParallelReplications);

        replicaVersions = new PartitionReplicaVersions[partitionCount];
        for (int i = 0; i < replicaVersions.length; i++) {
            replicaVersions[i] = new PartitionReplicaVersions(i);
        }

        ExecutionService executionService = nodeEngine.getExecutionService();
        TaskScheduler globalScheduler = executionService.getGlobalTaskScheduler();

        // The reason behind this scheduler to have POSTPONE type is as follows:
        // When a node shifts up in the replica table upon a node failure, it sends a sync request to the partition owner and
        // registers it to the replicaSyncRequests. If another node fails before the already-running sync process completes,
        // the new sync request is simply scheduled to a further time. Again, before the already-running sync process completes,
        // if another node fails for the third time, the already-scheduled sync request should be overwritten with the new one.
        // This is because this node is shifted up to a higher level when the third node failure occurs and its respective sync
        // request will inherently include the backup data that is requested by the previously scheduled sync request.
        replicaSyncTimeoutScheduler = EntryTaskSchedulerFactory.newScheduler(globalScheduler,
                new ReplicaSyncTimeoutProcessor(), ScheduleType.POSTPONE);

        replicaSyncRequests = newSetFromMap(new ConcurrentHashMap<ReplicaFragmentSyncInfo, Boolean>(partitionCount));
    }

    /**
     * This method is called on a backup node (replica). Given all conditions are satisfied, this method initiates a replica sync
     * operation and registers it to replicaSyncRequest. The operation is scheduled for a future execution if :
     *

     *
the {@code delayMillis} is greater than 0

     *
if a migration is not allowed (during repartitioning or a node joining the cluster)

     *
the partition is currently migrating

     *
another sync request has already been sent

     *
the maximum number of parallel synchronizations has already been reached

     *

     *
     * @param partitionId  the partition which is being synchronized
     * @param namespaces namespaces of partition replica fragments
     * @param replicaIndex the index of the replica which is being synchronized
     * @throws IllegalArgumentException if the replica index is not between 0 and {@link InternalPartition#MAX_REPLICA_COUNT}
     */
    public void triggerPartitionReplicaSync(int partitionId, Collection<ServiceNamespace> namespaces, int replicaIndex) {
        assert replicaIndex >= 0 && replicaIndex < InternalPartition.MAX_REPLICA_COUNT
                : "Invalid replica index! partitionId=" + partitionId + ", replicaIndex=" + replicaIndex;

        Address target = checkAndGetPrimaryReplicaOwner(partitionId, replicaIndex);
        if (target == null) {
            return;
        }

        if (!partitionService.isMigrationAllowed()) {
            logger.finest("Cannot send sync replica request for partitionId=" + partitionId + ", replicaIndex=" + replicaIndex
                    + ", namespaces=" + namespaces + ". Sync is not allowed.");
            return;
        }

        InternalPartitionImpl partition = partitionStateManager.getPartitionImpl(partitionId);
        if (partition.isMigrating()) {
            logger.finest("Cannot send sync replica request for partitionId=" + partitionId + ", replicaIndex=" + replicaIndex
                    + ", namespaces=" + namespaces + ". Partition is already migrating.");
            return;
        }

        sendSyncReplicaRequest(partitionId, namespaces, replicaIndex, target);
    }

    /** Checks preconditions for replica sync - if we don't know the owner yet, if this node is the owner or not a replica */
    Address checkAndGetPrimaryReplicaOwner(int partitionId, int replicaIndex) {
        final InternalPartitionImpl partition = partitionStateManager.getPartitionImpl(partitionId);
        final Address target = partition.getOwnerOrNull();
        if (target == null) {
            logger.info("Sync replica target is null, no need to sync -> partitionId=" + partitionId + ", replicaIndex="
                    + replicaIndex);
            return null;
        }

        Address thisAddress = nodeEngine.getThisAddress();
        if (target.equals(thisAddress)) {
            if (logger.isFinestEnabled()) {
                logger.finest("This node is now owner of partition, cannot sync replica -> partitionId=" + partitionId
                        + ", replicaIndex=" + replicaIndex + ", partition-info="
                        + partitionStateManager.getPartitionImpl(partitionId));
            }
            return null;
        }

        if (!partition.isOwnerOrBackup(thisAddress)) {
            if (logger.isFinestEnabled()) {
                logger.finest("This node is not backup replica of partitionId=" + partitionId
                        + ", replicaIndex=" + replicaIndex + " anymore.");
            }
            return null;
        }
        return target;
    }

    /**
     * Send the sync request to {@code target} if the max number of parallel sync requests has not been made and the target
     * was not removed while the cluster was not active. Also cancel any currently scheduled sync requests for the given
     * partition and schedule a new sync request that is to be run in the case of timeout
     */
    private void sendSyncReplicaRequest(int partitionId, Collection<ServiceNamespace> syncNamespaces,
            int replicaIndex, Address target) {
        if (node.clusterService.isMemberRemovedInNotJoinableState(target)) {
            return;
        }

        if (!tryToAcquireReplicaSyncPermit()) {
            if (logger.isFinestEnabled()) {
                logger.finest("Cannot send sync replica request for partitionId=" + partitionId + ", replicaIndex=" + replicaIndex
                        + ", namespaces=" + syncNamespaces + ". No permits available!");
            }
            return;
        }

        Collection<ServiceNamespace> namespaces = registerSyncInfoFor(partitionId, syncNamespaces, replicaIndex, target);
        if (namespaces.isEmpty()) {
            releaseReplicaSyncPermit();
            return;
        }

        if (logger.isFinestEnabled()) {
            logger.finest("Sending sync replica request for partitionId=" + partitionId + ", replicaIndex=" + replicaIndex
                    + ", namespaces=" + namespaces);

        }
        replicaSyncRequestsCounter.inc();

        PartitionReplicaSyncRequest syncRequest = new PartitionReplicaSyncRequest(partitionId, namespaces, replicaIndex);
        nodeEngine.getOperationService().send(syncRequest, target);
    }

    private Collection<ServiceNamespace> registerSyncInfoFor(int partitionId,
            Collection<ServiceNamespace> requestedNamespaces, int replicaIndex, Address target) {

        // namespaces arg may not support removal
        Collection<ServiceNamespace> namespaces = new ArrayList<ServiceNamespace>(requestedNamespaces);
        Iterator<ServiceNamespace> iter = namespaces.iterator();
        while (iter.hasNext()) {
            ServiceNamespace namespace = iter.next();
            ReplicaFragmentSyncInfo syncInfo = new ReplicaFragmentSyncInfo(partitionId, namespace, replicaIndex, target);
            if (!replicaSyncRequests.add(syncInfo)) {
                logger.finest("Cannot send sync replica request for " + syncInfo + ". Sync is already in progress!");
                iter.remove();
                continue;
            }

            replicaSyncTimeoutScheduler.schedule(partitionMigrationTimeout, syncInfo, null);
        }
        return namespaces;
    }

    @Override
    public ServiceNamespace getServiceNamespace(Operation operation) {
        if (operation instanceof ServiceNamespaceAware) {
            return ((ServiceNamespaceAware) operation).getServiceNamespace();
        }
        return NonFragmentedServiceNamespace.INSTANCE;
    }

    @Override
    // Caution: Returning version array without copying for performance reasons. Callers must not modify this array!
    public long[] incrementPartitionReplicaVersions(int partitionId, ServiceNamespace namespace, int backupCount) {
        PartitionReplicaVersions replicaVersion = replicaVersions[partitionId];
        return replicaVersion.incrementAndGet(namespace, backupCount);
    }

    @Override
    public void updatePartitionReplicaVersions(int partitionId, ServiceNamespace namespace,
                                               long[] versions, int replicaIndex) {
        PartitionReplicaVersions partitionVersion = replicaVersions[partitionId];
        if (!partitionVersion.update(namespace, versions, replicaIndex)) {
            // this partition backup is behind the owner or dirty.
            triggerPartitionReplicaSync(partitionId, Collections.singleton(namespace), replicaIndex);
        }
    }

    @Override
    public boolean isPartitionReplicaVersionStale(int partitionId, ServiceNamespace namespace,
                                                  long[] versions, int replicaIndex) {
        return replicaVersions[partitionId].isStale(namespace, versions, replicaIndex);
    }

    // called in operation threads
    public boolean isPartitionReplicaVersionDirty(int partitionId, ServiceNamespace namespace) {
        return replicaVersions[partitionId].isDirty(namespace);
    }

    @Override
    // Caution: Returning version array without copying for performance reasons. Callers must not modify this array!
    public long[] getPartitionReplicaVersions(int partitionId, ServiceNamespace namespace) {
        return replicaVersions[partitionId].get(namespace);
    }

    // called in operation threads
    public void setPartitionReplicaVersions(int partitionId, ServiceNamespace namespace,
                                            long[] versions, int replicaOffset) {
        replicaVersions[partitionId].set(namespace, versions, replicaOffset);
    }

    // called in operation threads
    public void clearPartitionReplicaVersions(int partitionId, ServiceNamespace namespace) {
        replicaVersions[partitionId].clear(namespace);
    }

    /**
     * Set the new replica versions for the partition with the {@code partitionId} and reset any ongoing replica
     * synchronization request for this partition and replica index.
     *
     * @param partitionId the partition ID
     * @param replicaIndex the index of the replica
     * @param versions the new replica versions for the partition
     */
    // called in operation threads
    public void finalizeReplicaSync(int partitionId, int replicaIndex, ServiceNamespace namespace, long[] versions) {
        PartitionReplicaVersions replicaVersion = replicaVersions[partitionId];
        replicaVersion.clear(namespace);
        replicaVersion.set(namespace, versions, replicaIndex);
        clearReplicaSyncRequest(partitionId, namespace, replicaIndex);
    }

    /**
     * Resets the state of the replica synchronization request for the given partition and replica. This will cancel the
     * scheduled synchronization, clear the ongoing sync flag and release a synchronization permit.
     *
     * @param partitionId  the partition being synchronized
     * @param namespace namespace
     * @param replicaIndex the index of the replica being synchronized
     */
    // called in operation threads
    public void clearReplicaSyncRequest(int partitionId, ServiceNamespace namespace, int replicaIndex) {
        ReplicaFragmentSyncInfo syncInfo = new ReplicaFragmentSyncInfo(partitionId, namespace, replicaIndex, null);
        if (!replicaSyncRequests.remove(syncInfo)) {
            return;
        }

        if (logger.isFinestEnabled()) {
            logger.finest("Clearing sync replica request for partitionId=" + partitionId + ", replicaIndex="
                    + replicaIndex + ", namespace=" + namespace);
        }
        releaseReplicaSyncPermit();
        replicaSyncTimeoutScheduler.cancelIfExists(syncInfo, null);
    }

    void cancelReplicaSyncRequestsTo(Address deadAddress) {
        Iterator<ReplicaFragmentSyncInfo> iter = replicaSyncRequests.iterator();
        while (iter.hasNext()) {
            ReplicaFragmentSyncInfo syncInfo = iter.next();
            if (deadAddress.equals(syncInfo.target)) {
                iter.remove();
                replicaSyncTimeoutScheduler.cancel(syncInfo);
                releaseReplicaSyncPermit();
            }
        }
    }

    void cancelReplicaSync(int partitionId) {
        Iterator<ReplicaFragmentSyncInfo> iter = replicaSyncRequests.iterator();
        while (iter.hasNext()) {
            ReplicaFragmentSyncInfo syncInfo = iter.next();
            if (syncInfo.partitionId == partitionId) {
                iter.remove();
                replicaSyncTimeoutScheduler.cancel(syncInfo);
                releaseReplicaSyncPermit();
            }
        }
    }

    public boolean tryToAcquireReplicaSyncPermit() {
        return replicaSyncProcessLock.tryAcquire();
    }

    public void releaseReplicaSyncPermit() {
        replicaSyncProcessLock.release();
    }

    /**
     * @return copy of ongoing replica-sync operations
     */
    List<ReplicaFragmentSyncInfo> getOngoingReplicaSyncRequests() {
        return new ArrayList<ReplicaFragmentSyncInfo>(replicaSyncRequests);
    }

    /**
     * @return copy of scheduled replica-sync requests
     */
    List<ScheduledEntry<ReplicaFragmentSyncInfo, Void>> getScheduledReplicaSyncRequests() {
        final List<ScheduledEntry<ReplicaFragmentSyncInfo, Void>>
                entries = new ArrayList<ScheduledEntry<ReplicaFragmentSyncInfo, Void>>();
        for (ReplicaFragmentSyncInfo syncInfo : replicaSyncRequests) {
            ScheduledEntry<ReplicaFragmentSyncInfo, Void> entry = replicaSyncTimeoutScheduler.get(syncInfo);
            if (entry != null) {
                entries.add(entry);
            }
        }
        return entries;
    }

    void reset() {
        replicaSyncRequests.clear();
        replicaSyncTimeoutScheduler.cancelAll();
        // this is not sync with possibly running sync process
        // permit count can exceed allowed parallelization count.
        replicaSyncProcessLock.drainPermits();
        replicaSyncProcessLock.release(maxParallelReplications);
    }

    void scheduleReplicaVersionSync(ExecutionService executionService) {
        long definedBackupSyncCheckInterval = node.getProperties().getSeconds(GroupProperty.PARTITION_BACKUP_SYNC_INTERVAL);
        long backupSyncCheckInterval = definedBackupSyncCheckInterval > 0 ? definedBackupSyncCheckInterval : 1;

        executionService.scheduleWithRepetition(new AntiEntropyTask(),
                backupSyncCheckInterval, backupSyncCheckInterval, TimeUnit.SECONDS);
    }

    @Override
    public Collection<ServiceNamespace> getNamespaces(int partitionId) {
        return replicaVersions[partitionId].getNamespaces();
    }

    public void retainNamespaces(int partitionId, Set<ServiceNamespace> namespaces) {
        PartitionReplicaVersions versions = replicaVersions[partitionId];
        versions.retainNamespaces(namespaces);
    }

    void setClusterVersion(Version newVersion) {
        this.clusterVersion = newVersion;
    }

    private class ReplicaSyncTimeoutProcessor implements ScheduledEntryProcessor<ReplicaFragmentSyncInfo, Void> {

        @Override
        public void process(EntryTaskScheduler<ReplicaFragmentSyncInfo, Void> scheduler,
                Collection<ScheduledEntry<ReplicaFragmentSyncInfo, Void>> entries) {

            for (ScheduledEntry<ReplicaFragmentSyncInfo, Void> entry : entries) {
                ReplicaFragmentSyncInfo syncInfo = entry.getKey();
                if (replicaSyncRequests.remove(syncInfo)) {
                    releaseReplicaSyncPermit();
                }
            }
        }
    }

    private class AntiEntropyTask implements Runnable {
        @Override
        public void run() {
            if (!node.nodeEngine.isRunning() || !node.getNodeExtension().isStartCompleted()
                    || !partitionService.isMigrationAllowed()) {
                return;
            }

            for (InternalPartition partition : partitionStateManager.getPartitions()) {
                if (!partition.isLocal()) {
                    continue;
                }

                PartitionSpecificRunnable r = new PartitionPrimaryReplicaAntiEntropyTask(nodeEngine, partition.getPartitionId());
                nodeEngine.getOperationService().execute(r);
            }
        }
    }
}


text:
package AST;

public class MethodDec extends Member{
    Qualifier qualifier;
    ReturnType returnType;
    Id id;
    FormalParamDec fParamDec;
    StatementList sList;

    public MethodDec(Qualifier qualifier, ReturnType returnType, Id id, FormalParamDec fParamDec, StatementList sList){
        this.qualifier = qualifier;
        this.returnType = returnType;
        this.id = id;
        this.fParamDec = fParamDec;
        this.sList = sList;
    }
    public StatementList getList(){
        return sList;
    }

    public void genK(PW pw, boolean putParenthesis){
        pw.add();
        qualifier.genK(pw, putParenthesis);
        returnType.genK(pw, putParenthesis);
        id.genK(pw, putParenthesis);
        pw.print("(");
        if(fParamDec != null)
            fParamDec.genK(pw, putParenthesis);
        pw.print(") ");
        pw.println("{");
        sList.genK(pw, putParenthesis);
        pw.printlnIdent("}");
        pw.sub();
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef BOOST_ASIO_TS_EXECUTOR_HPP
#define BOOST_ASIO_TS_EXECUTOR_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/handler_type.hpp>
#include <boost/asio/async_result.hpp>
#include <boost/asio/associated_allocator.hpp>
#include <boost/asio/execution_context.hpp>
#include <boost/asio/is_executor.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/executor_work_guard.hpp>
#include <boost/asio/system_executor.hpp>
#include <boost/asio/executor.hpp>
#include <boost/asio/dispatch.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio/defer.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/packaged_task.hpp>
#include <boost/asio/use_future.hpp>

#endif // BOOST_ASIO_TS_EXECUTOR_HPP


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
local CoreGui = game:GetService("CoreGui")
local ContextActionService = game:GetService("ContextActionService")
local TweenService = game:GetService("TweenService")

local RobloxGui = CoreGui:WaitForChild("RobloxGui")
local Utility = require(RobloxGui.Modules.Settings.Utility)

local INPUT_TYPE_ROW_HEIGHT = 30
local ACTION_ROW_HEIGHT = 20
local ROW_PADDING = 5
local COLUMN_PADDING = 5

local CORE_SECURITY_COLUMN_COLOR = Color3.new(0.1, 0, 0)
local DEV_SECURITY_COLUMN_COLOR = Color3.new(0, 0, 0)

local EXPAND_ROTATE_IMAGE_TWEEN_OUT = TweenInfo.new(0.150, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)
local EXPAND_ROTATE_IMAGE_TWEEN_IN = TweenInfo.new(0.150, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)

local ROW_PULSE = TweenInfo.new(0.5, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut, 0, true, 0)
local CONTAINER_SCROLL = TweenInfo.new(0.25, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)

local container = nil
local boundInputTypeRows = {}
local boundInputTypesByRows = {}
local boundInputTypeActionRows = {}
local boundActionInfoByRows = {}
local inputTypesByActionRows = {}
local inputTypesByHeaders = {}
local headersByInputTypes = {}
local inputTypesExpanded = {}

local rowTypePrecedence = {
	BoundInputType = 3,
	TableHeader = 2,
	BoundAction = 1
}

local function sortByInputType(a, b)
	return tostring(a) < tostring(b)
end

local function getInputType(x)
	if x.Name == "BoundAction" then
		return inputTypesByActionRows[x]
	elseif x.Name == "BoundInputType" then
		return boundInputTypesByRows[x]
	elseif x.Name == "TableHeader" then
		return inputTypesByHeaders[x]
	end
end

local function sortActionRows(a, b)
	if a.Name == "BoundAction" and b.Name == "BoundAction" then
		local actionA = boundActionInfoByRows[a]
		local actionB = boundActionInfoByRows[b]
		if actionA and actionB then
			local rowInputTypeA = inputTypesByActionRows[a]
			local rowInputTypeB = inputTypesByActionRows[b]
			if rowInputTypeA ~= rowInputTypeB then
				return sortByInputType(rowInputTypeA, rowInputTypeB)
			end
			if actionA.isCore and not actionB.isCore then
				return true
			elseif not actionA.isCore and actionB.isCore then
				return false
			end
			local stackOrderA = actionA.stackOrder
			local stackOrderB = actionB.stackOrder
			if stackOrderA and stackOrderB then
				return stackOrderA > stackOrderB --descending sort
			else
				return true
			end
		else
			return true
		end
	else
		local inputTypeA = getInputType(a)
		local inputTypeB = getInputType(b)
		if a.Name == b.Name then
			return sortByInputType(inputTypeA, inputTypeB)
		end
		if inputTypeA == inputTypeB then
			return rowTypePrecedence[a.Name] > rowTypePrecedence[b.Name]
		end
		return sortByInputType(inputTypeA, inputTypeB)
	end
	return true
 end

local function createEmptyRow(name, height)
	local row = Utility:Create("Frame") {
		Name = name,
		BackgroundTransparency = 1,
		ZIndex = 6,
		Size = UDim2.new(1, 0, 0, height or 0)
	}
	local columnList = Utility:Create("UIListLayout") {
		FillDirection = Enum.FillDirection.Horizontal,
		SortOrder = Enum.SortOrder.LayoutOrder,
		Padding = UDim.new(0, COLUMN_PADDING),
		Parent = row
	}
	return row
end

local function createButtonRow(name, height)
	local row = Utility:Create("TextButton") {
		Name = name,
		BackgroundTransparency = 1,
		ZIndex = 6,
		Text = "",
		Size = UDim2.new(1, 0, 0, height or 0),
	}
	local columnList = Utility:Create("UIListLayout") {
		FillDirection = Enum.FillDirection.Horizontal,
		SortOrder = Enum.SortOrder.LayoutOrder,
		Padding = UDim.new(0, COLUMN_PADDING),
		Parent = row
	}
	return row
end

local function createEmptyColumn(row, columnName)
	local column = Utility:Create("Frame") {
		Name = columnName,
		BackgroundColor3 = Color3.new(0, 0, 0),
		BackgroundTransparency = 0.75,
		BorderSizePixel = 0,
		Size = UDim2.new(1, 0, 1, 0),
		ZIndex = 6,
		ClipsDescendants = true,
		Parent = row
	}

	return column
end

local function createImageColumn(row, columnName, image, aspectRatio, imageSize)
	local column = createEmptyColumn(row, columnName)

	local aspectRatioConstraint = Utility:Create("UIAspectRatioConstraint") {
		AspectRatio = aspectRatio or 1,
		Parent = column
	}

	local imageLabel = Utility:Create("ImageLabel") {
		Name = "ColumnImage",
		BackgroundTransparency = 1,
		Position = UDim2.new(0.5, 0, 0.5, 0),
		Size = UDim2.new(imageSize or 1, 0, imageSize or 1, 0),
		AnchorPoint = Vector2.new(0.5, 0.5),
		ZIndex = 6,
		Image = image,
		Parent = column
	}

	return column
end

local function createTextColumn(row, columnName, text)
	local column = createEmptyColumn(row, columnName)

	local textLabel = Utility:Create("TextLabel") {
		Name = "ColumnText",
		BackgroundTransparency = 1,
		Position = UDim2.new(0.5, 0, 0.5, 0),
		Size = UDim2.new(1, -10, 1, -10),
		AnchorPoint = Vector2.new(0.5, 0.5),
		ZIndex = 6,
		Text = text,
		TextSize = 18,
		TextColor3 = Color3.new(1, 1, 1),
		TextXAlignment = Enum.TextXAlignment.Left,
		Font = Enum.Font.SourceSans,
		Parent = column
	}

	return column
end

local function createActionColumns(row, backgroundColor)
	local x = 0

	local insetWidth = ACTION_ROW_HEIGHT + (COLUMN_PADDING * 2)
	local insetCol = createEmptyColumn(row, "Inset")
	insetCol.LayoutOrder = 0
	insetCol.BackgroundTransparency = 1
	insetCol.Size = UDim2.new(0, insetWidth, 1, 0)
	x = x + insetWidth + COLUMN_PADDING

	local priorityWidth = 80
	local priorityCol = createTextColumn(row, "Priority", "Priority")
	priorityCol.LayoutOrder = 1
	priorityCol.BackgroundColor3 = backgroundColor
	priorityCol.Size = UDim2.new(0, priorityWidth, 1, 0)
	x = x + priorityWidth + COLUMN_PADDING

	local securityWidth = 80
	local securityCol = createTextColumn(row, "Security", "Security")
	securityCol.LayoutOrder = 2
	securityCol.BackgroundColor3 = backgroundColor
	securityCol.Size = UDim2.new(0, securityWidth, 1, 0)
	x = x + securityWidth + COLUMN_PADDING

	local nameCol = createTextColumn(row, "ActionName", "Action Name")
	nameCol.LayoutOrder = 3
	nameCol.BackgroundColor3 = backgroundColor
	nameCol.Size = UDim2.new(1/4, 0, 1, 0)

	local inputTypesCol = createTextColumn(row, "InputTypes", "Input Types")
	inputTypesCol.LayoutOrder = 4
	inputTypesCol.BackgroundColor3 = backgroundColor
	inputTypesCol.Size = UDim2.new(3/4, -x - COLUMN_PADDING, 1, 0)

	return insetCol, priorityCol, securityCol, nameCol, inputTypesCol
end

local function updateContainerCanvas()
	local y = 0
	for _, v in pairs(container:GetChildren()) do
		if v:IsA("GuiObject") and v.Visible then
			y = y + v.AbsoluteSize.Y + ROW_PADDING
		end
	end
	container.CanvasSize = UDim2.new(0, 0, 0, y)
end

local function scrollContainerToRow(row)
	local scrollOffset = row.AbsolutePosition.Y - container.AbsolutePosition.Y
	local newCanvasPosition = container.CanvasPosition + Vector2.new(0, scrollOffset)
	TweenService:Create(container, CONTAINER_SCROLL, { CanvasPosition = newCanvasPosition }):Play()
end

local ActionBindingsTab = {}

function ActionBindingsTab.initializeGui(tabFrame)
	local scrollingFrame = Utility:Create("ScrollingFrame") {
		Position = UDim2.new(0.5, 0, 0.5, 0),
		Size = UDim2.new(1, -10, 1, -10),
		AnchorPoint = Vector2.new(0.5, 0.5),
		BorderSizePixel = 0,
		ScrollBarThickness = 4,
		BackgroundTransparency = 1,
		ZIndex = 6,
		Parent = tabFrame
	}
	container = scrollingFrame

	local listLayout = Utility:Create("UIListLayout") {
		Padding = UDim.new(0, ROW_PADDING),
		Parent = scrollingFrame
	}
	listLayout:SetCustomSortFunction(sortActionRows)
	listLayout.SortOrder = Enum.SortOrder.Custom

	ActionBindingsTab.updateGuis()

	ContextActionService.BoundActionAdded:connect(function(actionName, createTouchButton, actionInfo, isCore)
		actionInfo.isCore = isCore
		ActionBindingsTab.updateActionRows(actionName, actionInfo)
	end)
	ContextActionService.BoundActionRemoved:connect(function(actionName, actionInfo, isCore)
		actionInfo.isCore = isCore
		ActionBindingsTab.removeActionRows(actionName, actionInfo)
	end)
end

function ActionBindingsTab.updateBoundInputTypeRow(inputType)
	local existingRow = boundInputTypeRows[inputType]
	if not existingRow then
		local row = createButtonRow("BoundInputType", INPUT_TYPE_ROW_HEIGHT)

		local expandImageCol = createImageColumn(row, "ExpandImage", "rbxasset://textures/ui/Icons/DownIndicatorIcon@1080.png", 1, 0.35)
		expandImageCol.ColumnImage.Rotation = -90

		local inputTypeCol = createTextColumn(row, "InputType", tostring(inputType))
		inputTypeCol.Size = UDim2.new(1, -INPUT_TYPE_ROW_HEIGHT - COLUMN_PADDING, 1, 0)
		inputTypeCol.ColumnText.Font = Enum.Font.SourceSansBold

		local tableHeaderRow = createEmptyRow("TableHeader", ACTION_ROW_HEIGHT)
		tableHeaderRow.Visible = false
		local _, priorityCol, securityCol, nameCol, inputTypesCol = createActionColumns(tableHeaderRow, DEV_SECURITY_COLUMN_COLOR)
		priorityCol.ColumnText.Font = Enum.Font.SourceSansBold
		securityCol.ColumnText.Font = Enum.Font.SourceSansBold
		nameCol.ColumnText.Font = Enum.Font.SourceSansBold
		inputTypesCol.ColumnText.Font = Enum.Font.SourceSansBold

		boundInputTypeRows[inputType] = row
		boundInputTypesByRows[row] = inputType
		inputTypesByHeaders[tableHeaderRow] = inputType
		headersByInputTypes[inputType] = tableHeaderRow

		tableHeaderRow.Parent = container
		row.Parent = container

		TweenService:Create(inputTypeCol, ROW_PULSE, { BackgroundColor3 = Color3.new(0.5, 0.5, 0.5) }):Play()

		inputTypesExpanded[inputType] = false
		row.MouseButton1Click:connect(function()
			inputTypesExpanded[inputType] = not inputTypesExpanded[inputType]

			local inputTypeActionRows = boundInputTypeActionRows[inputType]
			if not inputTypesExpanded[inputType] then
				TweenService:Create(expandImageCol.ColumnImage, EXPAND_ROTATE_IMAGE_TWEEN_OUT, { Rotation = -90 }):Play()
				tableHeaderRow.Visible = false
				if inputTypeActionRows then
					for _, actionRow in pairs(inputTypeActionRows) do
						actionRow.Visible = false
					end
				end
			else
				TweenService:Create(expandImageCol.ColumnImage, EXPAND_ROTATE_IMAGE_TWEEN_IN, { Rotation = 0 }):Play()
				tableHeaderRow.Visible = true
				if inputTypeActionRows then
					for _, actionRow in pairs(inputTypeActionRows) do
						actionRow.Visible = true
					end
				end
			end

			updateContainerCanvas()
			if inputTypesExpanded[inputType] then
				TweenService:Create(inputTypeCol, ROW_PULSE, { BackgroundColor3 = Color3.new(0.5, 0.5, 0.5) }):Play()
				scrollContainerToRow(row)
			end
		end)
	end
end

function ActionBindingsTab.updateActionRowForInputType(actionName, actionInfo, inputType)
	local inputTypeActionRows = boundInputTypeActionRows[inputType]
	if not inputTypeActionRows then
		inputTypeActionRows = {}
		boundInputTypeActionRows[inputType] = inputTypeActionRows
	end

	local existingRow = inputTypeActionRows[actionName]
	if not existingRow then
		local row = createEmptyRow("BoundAction", ACTION_ROW_HEIGHT)
		row.Visible = inputTypesExpanded[inputType]

		local inputTypeNames = {}
		for i, inputType in pairs(actionInfo.inputTypes) do
			inputTypeNames[i] = tostring(inputType)
		end

		local insetCol, priorityCol, securityCol, nameCol, inputTypesCol = createActionColumns(row, actionInfo.isCore and CORE_SECURITY_COLUMN_COLOR or DEV_SECURITY_COLUMN_COLOR)
		priorityCol.ColumnText.Text = actionInfo.priorityLevel or "Default"
		securityCol.ColumnText.Text = actionInfo.isCore and "Core" or "Developer"
		nameCol.ColumnText.Text = actionName
		inputTypesCol.ColumnText.Text = table.concat(inputTypeNames, ", ")

		if actionInfo.isCore then
			priorityCol.ColumnText.Font = Enum.Font.SourceSansItalic
			securityCol.ColumnText.Font = Enum.Font.SourceSansItalic
			nameCol.ColumnText.Font = Enum.Font.SourceSansItalic
			inputTypesCol.ColumnText.Font = Enum.Font.SourceSansItalic
		end

		inputTypeActionRows[actionName] = row
		inputTypesByActionRows[row] = inputType
		boundActionInfoByRows[row] = actionInfo
		row.Parent = container

		if row.Visible then
			TweenService:Create(nameCol, ROW_PULSE, { BackgroundColor3 = Color3.new(0.5, 0.5, 0.5) }):Play()
		else
			local inputTypeRow = boundInputTypeRows[inputType]
			if inputTypeRow then
				TweenService:Create(inputTypeRow.InputType, ROW_PULSE, { BackgroundColor3 = Color3.new(0.5, 0.5, 0.5) }):Play()
			end
		end
	end
end

function ActionBindingsTab.updateActionRows(actionName, actionInfo)
	for _, inputType in pairs(actionInfo.inputTypes) do
		ActionBindingsTab.updateBoundInputTypeRow(inputType)
		ActionBindingsTab.updateActionRowForInputType(actionName, actionInfo, inputType)
	end
	updateContainerCanvas()
end

function ActionBindingsTab.removeActionRows(actionName, actionInfo)
	for _, inputType in pairs(actionInfo.inputTypes) do
		local inputTypeActionRows = boundInputTypeActionRows[inputType]
		if inputTypeActionRows then
			local row = inputTypeActionRows[actionName]
			row:Destroy()
			inputTypeActionRows[actionName] = nil

			--The following code looks weird. It's because Lua has no way to determine
			--if a table is explicitly empty in both the array and dictionary parts.
			--This does it though.
			local isEmpty = true
			for _, __ in pairs(inputTypeActionRows) do
				isEmpty = false
				break
			end

			if isEmpty then
				local inputTypeRow = boundInputTypeRows[inputType]
				if inputTypeRow then
					inputTypeRow:Destroy()
					boundInputTypeRows[inputType] = nil
				end
				local tableHeaderRow = headersByInputTypes[inputType]
				if tableHeaderRow then
					headersByInputTypes[tableHeaderRow] = nil
					tableHeaderRow:Destroy()
					headersByInputTypes[inputType] = nil
				end
			end
		end
	end

	updateContainerCanvas()
	container.UIListLayout:ApplyLayout()
end

function ActionBindingsTab.updateGuis()
	local boundCoreActions = ContextActionService:GetAllBoundCoreActionInfo()
	for actionName, actionInfo in pairs(boundCoreActions) do
		actionInfo.isCore = true
		ActionBindingsTab.updateActionRows(actionName, actionInfo)
	end
	local boundActions = ContextActionService:GetAllBoundActionInfo()
	for actionName, actionInfo in pairs(boundActions) do
		actionInfo.isCore = false
		ActionBindingsTab.updateActionRows(actionName, actionInfo)
	end
	updateContainerCanvas()
end

return ActionBindingsTab


text:
namespace orbit_client_model_internal {

std::string FormatTimeWithUnderscores(absl::Time time) {
  return absl::FormatTime("%Y_%m_%d_%H_%M_%S", time, absl::LocalTimeZone());
}

}  // namespace orbit_client_model_internal

namespace orbit_client_model {

namespace {
inline constexpr std::string_view kFileOrbitExtension = ".orbit";
}

namespace capture_serializer {

std::string GenerateCaptureFileName(std::string_view process_name, absl::Time time,
                                    std::string_view suffix) {
  return absl::StrCat(std::filesystem::path(process_name).stem().string(), "_",
                      orbit_client_model_internal::FormatTimeWithUnderscores(time), suffix,
                      kFileOrbitExtension);
}

void IncludeOrbitExtensionInFile(std::string& file_name) {
  const std::string extension = std::filesystem::path(file_name).extension().string();
  if (extension != kFileOrbitExtension) {
    file_name.append(kFileOrbitExtension);
  }
}

}  // namespace capture_serializer

}  // namespace orbit_client_model


text:
module Esi
  class Response
    extend Forwardable

    attr_reader :original_response, :call, :data
    def_delegators :original_response, :status, :body, :headers
    def_delegators :data, :each

    def initialize(response, call = nil)
      @original_response = response
      @data = normalize_response_body
      @call = call
    end

    def merge(other_response)
      @data += other_response.data
      self
    end

    def to_h
      data.is_a?(Array) ? data.map { |e| e.try(:to_h) || e } : e.to_h
    end

    def to_json(pretty: true)
      MultiJson.dump(data, pretty: pretty)
    end

    def cached_until
      @cached_until ||= headers[:expires] ? Time.parse(headers[:expires]) : nil
    end

    def save
      File.write(log_directroy.join("#{Time.now.to_i}.json"), to_json) if should_log_response?
      self
    end

    def log_directory
      call.class.to_s.split('::').last.underscore
      dir = Pathname.new(Esi.config.response_log_path).join(call_name)
      FileUtils.mkdir_p(dir)
      dir
    end

    def should_log_response?
      return false if call.nil?
      return false if Esi.config.response_log_path.blank? || !Dir.exist?(Esi.config.response_log_path)
      true
    end

    def method_missing(method, *args, &block)
      data.send(method, *args, &block)
    end

    private

    def normalize_response_body
      MultiJson.load(body.presence || '{}', symbolize_keys: true, object_class: OpenStruct)
    end
  end
end


text:
package rds

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// ParameterGroup is a nested struct in rds response
type ParameterGroup struct {
	Engine             string      `json:"Engine" xml:"Engine"`
	UpdateTime         string      `json:"UpdateTime" xml:"UpdateTime"`
	EngineVersion      string      `json:"EngineVersion" xml:"EngineVersion"`
	ParameterGroupName string      `json:"ParameterGroupName" xml:"ParameterGroupName"`
	ParameterGroupType int         `json:"ParameterGroupType" xml:"ParameterGroupType"`
	ParameterGroupDesc string      `json:"ParameterGroupDesc" xml:"ParameterGroupDesc"`
	CreateTime         string      `json:"CreateTime" xml:"CreateTime"`
	ForceRestart       int         `json:"ForceRestart" xml:"ForceRestart"`
	ParamCounts        int         `json:"ParamCounts" xml:"ParamCounts"`
	ParameterGroupId   string      `json:"ParameterGroupId" xml:"ParameterGroupId"`
	ParamDetail        ParamDetail `json:"ParamDetail" xml:"ParamDetail"`
}


text:
package main.scala.sandBox

/**
 * Created by cusgadmin on 6/9/15.
 */

import breeze.linalg._
import breeze.plot._
import main.scala.ioTools.ReadCsv
import main.scala.overlapping.containers.TSInstant
import org.apache.spark.{SparkConf, SparkContext}
import org.joda.time.DateTime
import main.scala.overlapping._
import main.scala.overlapping.spatial.QuadTree
import main.scala.overlapping.timeSeries._
import org.apache.spark.SparkContext._

object TryQuadTree {

  implicit def signedDistMillis = (t1: TSInstant, t2: TSInstant) => (t2.timestamp.getMillis - t1.timestamp.getMillis).toDouble

  implicit def signedDistLong = (t1: Long, t2: Long) => (t2 - t1).toDouble

  def main(args: Array[String]): Unit = {

    val nPartitions = 8

    //implicit val config = TSConfig(deltaTMillis, d, N, paddingMillis.toDouble)

    val conf = new SparkConf().setAppName("Counter").setMaster("local[*]")
    implicit val sc = new SparkContext(conf)

    val MAX_LAT = 40.85
    val MIN_LAT = 40.66

    val MAX_LON = -73.90
    val MIN_LON = -74.05

    val nX = 100
    val nY = 100
    val deltaX = (MAX_LON - MIN_LON) / nX.toDouble
    val deltaY = (MAX_LAT - MIN_LAT) / nY.toDouble

    val inSampleFilePath = "/users/cusgadmin/traffic_data/new_york_taxi_data/earnings_table_1_short.csv"

    val (inSampleData_, d, nSamples) = ReadCsv.geoTS(inSampleFilePath)

    def hasher(x: Double, y: Double): (Int, Int) = {
      (((x - MIN_LON) / deltaX).toInt, ((y - MIN_LAT) / deltaY).toInt)
    }

    val inSampleData = inSampleData_
      .filter({case ((_, x: Double, y: Double), _) => (x >= MIN_LON) && (x <= MAX_LON) && (y >= MIN_LAT) && (y <= MAX_LAT)})

    val countMap = inSampleData
      .map({case ((_, x, y), _) => (hasher(x, y), 1L)})
      .reduceByKey(_ + _)
      .collect()

    val countMatrix = DenseMatrix.zeros[Double](nX, nY)
    for(((i, j), c) <- countMap){
      countMatrix(i, j) = c
    }

    val qt = new QuadTree(MIN_LON, MIN_LAT, MAX_LON, MAX_LAT, countMatrix, 50000L)

    val f1 = Figure()
    f1.subplot(0) += image(countMatrix)

    val leafLocations = qt.getLeafLocations()

    val leafLongitudes = DenseVector(leafLocations.map(_._1))
    val leafLatitudes  = DenseVector(leafLocations.map(_._2))

    val f2 = Figure()
    val p = f2.subplot(0)
    p += plot(leafLongitudes, leafLatitudes, '.')

    //inSampleData_.collect().foreach(println)

  }
}


text:
<?php
namespace SkinnyTest\TestBot\Error;

use Skinny\Error\Debugger;

class DebuggerTestCase extends Debugger
{
}


text:
<?php

class Model_gadget extends \Fuel\Core\Model_Crud {

    protected static $_table_name = "gadget";

    //プライマリキー
    protected static $_primary_key = "gadget_id";
}


text:
module Azure::TimeSeriesInsights::Mgmt::V2017_11_15
  module Models
    #
    # The sku determines the capacity of the environment, the SLA (in
    # queries-per-minute and total capacity), and the billing rate.
    #
    class Sku

      include MsRestAzure

      # @return [SkuName] The name of this SKU. Possible values include: 'S1',
      # 'S2'
      attr_accessor :name

      # @return [Integer] The capacity of the sku. This value can be changed to
      # support scale out of environments after they have been created.
      attr_accessor :capacity

      #
      # Mapper for Sku class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'Sku',
          type: {
            name: 'Composite',
            class_name: 'Sku',
            model_properties: {
              name: {
                client_side_validation: true,
                required: true,
                serialized_name: 'name',
                type: {
                  name: 'Enum',
                  module: 'SkuName'
                }
              },
              capacity: {
                client_side_validation: true,
                required: true,
                serialized_name: 'capacity',
                constraints: {
                  InclusiveMaximum: 10,
                  InclusiveMinimum: 1
                },
                type: {
                  name: 'Number'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
import java.io.*;
import java.util.*;

class CheckIfWordIsValidAfterSubstitutions
{
    public static void main(String[] args)
    {
        System.out.println("=== Check If Word is Valid After Substitutions ===");
        Solution solution = new Solution();
        String[] input = {"aabcbc", "abcabcababcc", "abccba", "cababc", "aabcbcabc"};
        for (String S : input) {
            System.out.println("S = "+S);
            System.out.println("isValid = "+solution.isValid(S));
        }
    }
}

class Solution
{
    public boolean isValid(String S) {
        boolean ret = false;
        if (S != null && S.length() <= 3) {
            if (S.equals("abc")) {
                return true;
            } else {
                return false;
            }
        }

        int idx = S.indexOf("abc");
        if (idx < 0) {
            return false;
        }

        //System.out.println("idx = "+idx);
        //System.out.println("S.length() = "+S.length());

        String a = S.substring(0, idx);
        String b = (idx+3 < S.length())?S.substring(idx+3, S.length()):"";

        //System.out.println("a+b="+a+b);

        return isValid(a+b);
    }
}


text:
Tree component
==============

This component renders a tree graph as SVG.


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlusArithmeticExpressionOperator.cs" company="CODE Insiders LTD">
//
// Copyright 2013-2015 CODE Insiders LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CodeInsiders.SharpQL.Operators
{
    using System;

    public class PlusArithmeticExpressionOperator : ArithmeticExpressionOperator
    {
        public PlusArithmeticExpressionOperator(Expression leftOperand, Expression rightOperand)
            : base(leftOperand, rightOperand) {
            if (leftOperand == null) {
                throw new ArgumentNullException("leftOperand");
            }
            if (rightOperand == null) {
                throw new ArgumentNullException("rightOperand");
            }
        }

        public override void Build(SqlFragment parent, TSqlVisitor visitor) {
            visitor.PlusArithmeticExpressionOperator(parent, this);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2016 Jorge Ruesga

     Licensed under the Apache License, ServerVersion 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
 -->
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="com.ruesga.rview.gerrit.model.Features" />
        <variable name="isSelected" type="Boolean" />
        <variable name="model" type="com.ruesga.rview.gerrit.model.RevisionInfo" />
        <variable name="unresolvedComments" type="java.util.Map<Integer, com.ruesga.rview.model.UnresolvedComment>" />
    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/selector_item"
            app:bindSelected="@{safeUnbox(isSelected)}"
            android:padding="8dp"
            android:minHeight="?attr/listPreferredItemHeightSmall"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            tools:ignore="UselessParent">

            <com.ruesga.rview.widget.StyleableTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingRight="3dp"
                android:paddingLeft="3dp"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:revisionNumber="@{model}"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="?android:attr/textColorPrimary"
                android:textSize="12sp" />

            <com.ruesga.rview.widget.StyleableTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:minWidth="@dimen/dropdown_min_width"
                android:paddingRight="3dp"
                android:paddingLeft="3dp"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:revisionCommit="@{model}"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="?android:attr/textColorSecondary"
                android:textSize="12sp" />

            <com.ruesga.rview.widget.StyleableTextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:paddingRight="3dp"
                android:paddingLeft="3dp"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                android:maxLines="1"
                android:ellipsize="end"
                app:prettyDateTime="@{model.created}"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="?android:attr/textColorSecondary"
                android:textSize="12sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingStart="8dp"
            android:paddingEnd="8dp"
            android:paddingBottom="4dp"
            android:minHeight="?attr/listPreferredItemHeightSmall"
            android:gravity="bottom"
            android:orientation="horizontal"
            app:bindToFeature="@{Features.UNRESOLVED_COMMENTS}"
            app:bindToBoolean="@{Boolean.TRUE}"
            tools:ignore="UselessParent">
            <com.ruesga.rview.widget.StyleableTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="3dp"
                android:paddingStart="3dp"
                android:paddingRight="3dp"
                android:paddingEnd="3dp"
                app:revisionKind="@{model}"
                android:textAllCaps="true"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="?android:attr/textColorSecondary"
                android:textSize="9sp"
                tools:ignore="SmallSp" />
            <com.ruesga.rview.widget.StyleableTextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:paddingLeft="3dp"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                android:paddingRight="3dp"
                android:maxLines="1"
                android:ellipsize="end"
                app:unresolvedComments="@{unresolvedComments[model.number]}"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="?android:attr/textColorSecondary"
                android:textSize="9sp"
                tools:ignore="RtlSymmetry,SmallSp" />
        </LinearLayout>
    </FrameLayout>
</layout>


text:
#include <sys/socket.h>

#include <memory>
#include <string>
#include <vector>
#include <thread>
#include <iostream>

#include "InetAddress.h"
#include "ServerSocket.h"

using namespace BsdSockets;

/** Echo everything on socket until a line starting with "quit" */
class EchoHandler {
public:
  /** Create with theSocket to echo on and greeting string
   *
   * @param theSocket to echo on
   * @param greeting to echo at the beginning
   */
  EchoHandler(Socket::Ptr theSocket, const std::string& greeting)
    : socket(theSocket)
  {
    try {
      send(greeting);
      send("Any line beginning with \"quit\" will terminate this echo client.\n");
    } catch (...) {
      // Do nothing on error
    }
  }

  /** Run the echo without escaping any exceptions */
  void operator() () {
    try {
      while(true) {
	if(readCurrent()) {
	  break;
	}
      }
    } catch(...) {
      // Do nothing on error
    }
  }

private:
  /** Read the next data, when ready, and deal with
   *
   * @return true if we are done, otherwise false to continue
   */
  bool readCurrent() {
    const int bufferLen = 1024;
    char buffer[bufferLen];

    const ssize_t readLength = socket->blockingReceive(buffer, bufferLen - 1);
    if(0 == readLength) {
      return false;
    }

    return actOn(std::string(buffer, readLength));
  }

  /** Act on the buffer
   *
   * @param buffer to process
   *
   * @return true if we are done, otherwise false to continue
   */
  bool actOn(const std::string& buffer) {
    if(0 == buffer.find("quit")) {
      send("Goodbye!\n");
      return true;
    }

    send(buffer);
    return false;
  }

  /** Send a string message over the socket
   *
   * @param message to send
   */
  void send(const std::string& message) {
    socket->send(message.c_str(), message.length() + 1);
  }

private:
  /** Timeout for this socket */
  static const int timeout_ms = 500;

  /** Socket to echo */
  Socket::Ptr socket;
};

/** Opens a ServerSocket to accept connections to echo everything back on.
 */
class EchoServer {
public:
  /** Create bound to address
   *
   * @param address to open EchoServer
   */
  EchoServer(Address::Ptr address)
    : serverSocket(ServerSocket::open(address))
  {
  }

  /** Run the echo without escaping any exceptions */
  void operator()() {
    try {
      // Loop over all incoming
      while(true) {
	acceptCurrent();
      }
    } catch(...) {
      // Do nothing on error
    }

    // We never expect to get here, but if we do....

    // Loop over all threads to make sure they are done
    for(std::thread& acceptedThread : acceptedThreads) {
      try {
	acceptedThread.join();
      } catch (...) {
	// Do nothing on error
      }
    }
  }

private:
  /** Accept the next socket and spin off an EchoHandler */
  void acceptCurrent() {
    const int id = acceptedThreads.size() + 1;
    acceptedThreads.push_back(serverSocket->acceptInNewThread(
      [=](Socket::Ptr accepted) {
	const std::string greeting = std::string("Welcome, Connection #") + std::to_string(id) + "\n";
	EchoHandler e(accepted, greeting);
	e();
      }));
  }

private:
  /** Timeout for this socket */
  static const int timeout_ms = 500;

  /** Socket we accept connections on */
  ServerSocket::Ptr serverSocket;

  /** All threads we have created so that we could join them, if appropriate */
  std::vector<std::thread> acceptedThreads;
};

int main(int argc, char** argv) {
  InetAddress::Ptr addr = InetAddress::create(SocketType::STREAM, "11111", "127.0.0.1");

  // Run this server socket in its own thread so we could do something else...
  // This is superfluous for the example...
  std::thread serverThread(
  [=]() {
      EchoServer server(addr);
      server();
  });

  // Wait for server to return
  serverThread.join();

  return 0;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="20dp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    android:paddingBottom="20dp">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingRight="10dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:text="Beer name:"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Brewery:"
            android:gravity="right" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:gravity="right"
            android:text="ABV:"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:gravity="right"
            android:text="IBU:"/>

    </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/beer_info_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="(name)"/>
        <TextView
            android:id="@+id/beer_info_brewery"
            android:layout_marginTop="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="(brewery)" />
        <TextView
            android:id="@+id/beer_info_abv"
            android:layout_marginTop="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="(abv)"/>

        <TextView
            android:id="@+id/beer_info_ibu"
            android:layout_marginTop="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="(ibu)"/>

    </LinearLayout>
</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using SylphyHorn.Serialization;
using SylphyHorn.Services;
using SylphyHorn.UI.Pages;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace SylphyHorn
{
	/// <summary>
	/// 既定の Application クラスを補完するアプリケーション固有の動作を提供します。
	/// </summary>
	sealed partial class App
	{
		/// <summary>
		/// 単一アプリケーション オブジェクトを初期化します。これは、実行される作成したコードの最初の行であるため、main() または WinMain() と論理的に等価です。
		/// </summary>
		public App()
		{
			WindowsAppInitializer.InitializeAsync(WindowsCollectors.Metadata | WindowsCollectors.Session);

			this.InitializeComponent();

			this.Suspending += this.HandleSuspending;
			this.UnhandledException += this.HandleUnhandledException;
		}

		/// <summary>
		/// アプリケーションがエンド ユーザーによって正常に起動されたときに呼び出されます。他のエントリ
		/// ポイントは、アプリケーションが特定のファイルを開くために起動されたときなどに使用されます。
		/// </summary>
		/// <param name="e">起動の要求とプロセスの詳細を表示します。</param>
		protected override async void OnLaunched(LaunchActivatedEventArgs e)
		{
#if DEBUG
			if (System.Diagnostics.Debugger.IsAttached)
			{
				this.DebugSettings.EnableFrameRateCounter = true;
			}
#endif

			var rootFrame = Window.Current.Content as Frame;
			if (rootFrame == null)
			{
				// ウィンドウにコンテンツが表示されていない場合
				// アプリケーションの初期化を実行

				// ナビゲーション コンテキストとして動作するフレームを作成し、最初のページに移動
				rootFrame = new Frame();
				rootFrame.NavigationFailed += this.HandleNavigationFailed;

				//if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
				//{
				//	// ToDo: 初期化・状態復元
				//}

				Window.Current.Content = rootFrame;
			}

			if (!LocalStorageProvider.Instance.IsLoaded)
			{
				await LocalStorageProvider.Instance.LoadAsync();
			}

			// デスクトップ クライアントに UI が起動したことを通知する
			// (= キー入力の一時停止をオンにして設定に書き込む)
			Settings.General.SuspendKeyDetection.Value = true;
			await LocalStorageProvider.Instance.SaveAsync();

			if (rootFrame.Content == null)
			{
				// ナビゲーション スタックが復元されない場合は、最初のページに移動
				rootFrame.Navigate(typeof(MainPage), e.Arguments);
			}

			Window.Current.Activate();
		}

		/// <summary>
		/// アプリケーションの実行が中断されたときに呼び出されます。アプリケーションが終了されるか、メモリの内容がそのままで再開されるかにかかわらず、アプリケーションの状態が保存されます。
		/// </summary>
		/// <param name="sender">中断要求の送信元。</param>
		/// <param name="e">中断要求の詳細。</param>
		private async void HandleSuspending(object sender, SuspendingEventArgs e)
		{
			using (e.GetDeferral())
			{
				Settings.General.SuspendKeyDetection.Value = false;
				await LocalStorageProvider.Instance.SaveAsync();
			}
		}

		/// <summary>
		/// 特定のページへの移動が失敗したときに呼び出されます。
		/// </summary>
		/// <param name="sender">移動に失敗したフレーム。</param>
		/// <param name="e">ナビゲーション エラーの詳細。</param>
		private void HandleNavigationFailed(object sender, NavigationFailedEventArgs e)
		{
			throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
		}

		private void HandleUnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			// ToDo: 不慮の事故で死んだとき何かしたい
		}
	}
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              tools:context="com.tigerpenguin.lab.bitmapmemory.part3.OtherActivity"
              tools:ignore="MergeRootFrame">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/otherActivity"/>

</LinearLayout>


text:
package org.vafer.jdeb.utils;

import java.util.Map;

/**
 * Resolve variables based on a Map.
 *
 * ATTENTION: don't use outside of jdeb
 *
 * @author Torsten Curdt <tcurdt@vafer.org>
 */

public final class MapVariableResolver implements VariableResolver {

    private final Map<String, String> map;

    public MapVariableResolver( final Map<String, String> pMap ) {
        map = pMap;
    }

    public String get( final String pKey ) {
        return map.get(pKey);
    }

}


text:
const util = require('util')
  , Field = require('./field');

function MultiSelectField(fieldDefinition, form) {
  MultiSelectField.super_.call(this, fieldDefinition, form[fieldDefinition.name]);
}

util.inherits(MultiSelectField, Field);

MultiSelectField.prototype.validate = function() {
  const error = MultiSelectField.super_.prototype.validate.call(this);
  if (error) return error;

  if (!this.value) return;

  if (!Array.isArray(this.value)) {
    return { error: 'value', message: `${this.definition.title} must be an Array` }
  }

  const invalid = this.value.some(value => {
    const choices = this.definition.choices.filter(choice => {
      return choice.title === value;
    }, this);

    return choices.length === 0;
  })

  if (invalid) {
    return { error: 'value', message: `${this.definition.title} must be one of: ${this.definition.choices.map(choice => choice.title)}` }
  }
};

module.exports = MultiSelectField;


text:
FROM gcr.io/oss-fuzz-base/base-builder
RUN apt-get update && apt-get install -y make libssl-dev binutils libgcc-9-dev
RUN git clone --depth 1 https://chromium.googlesource.com/chromiumos/third_party/tpm2
WORKDIR tpm2
RUN cp /src/tpm2/fuzz/build.sh /src/


text:
using Lucene.Net.Index;
using Lucene.Net.QueryParsers.Flexible.Core.Nodes;
using Lucene.Net.QueryParsers.Flexible.Standard.Nodes;
using Lucene.Net.QueryParsers.Flexible.Standard.Processors;
using Lucene.Net.Search;

namespace Lucene.Net.QueryParsers.Flexible.Standard.Builders
{

    /// <summary>
    /// Builds a <see cref="PrefixQuery"/> object from a <see cref="PrefixWildcardQueryNode"/>
    /// object.
    /// </summary>
    public class PrefixWildcardQueryNodeBuilder : IStandardQueryBuilder
    {
        public PrefixWildcardQueryNodeBuilder()
        {
            // empty constructor
        }

        public virtual Query Build(IQueryNode queryNode)
        {
            PrefixWildcardQueryNode wildcardNode = (PrefixWildcardQueryNode)queryNode;

            string text = wildcardNode.Text.Subsequence(0, wildcardNode.Text.Length - 1).ToString(); // LUCENENET: Checked 2nd Subsequence parameter
            PrefixQuery q = new PrefixQuery(new Term(wildcardNode.GetFieldAsString(), text));

            MultiTermQuery.RewriteMethod method = (MultiTermQuery.RewriteMethod)queryNode.GetTag(MultiTermRewriteMethodProcessor.TAG_ID);
            if (method != null)
            {
                q.MultiTermRewriteMethod = method;
            }

            return q;
        }
    }
}


text:
namespace Envoy {
namespace Extensions {
namespace Common {
namespace DynamicForwardProxy {

SINGLETON_MANAGER_REGISTRATION(dns_cache_manager);

DnsCacheSharedPtr DnsCacheManagerImpl::getCache(
    const envoy::extensions::common::dynamic_forward_proxy::v3::DnsCacheConfig& config) {
  const auto& existing_cache = caches_.find(config.name());
  if (existing_cache != caches_.end()) {
    if (!Protobuf::util::MessageDifferencer::Equivalent(config, existing_cache->second.config_)) {
      throw EnvoyException(
          fmt::format("config specified DNS cache '{}' with different settings", config.name()));
    }

    return existing_cache->second.cache_;
  }

  DnsCacheSharedPtr new_cache = std::make_shared<DnsCacheImpl>(context_, config);
  caches_.emplace(config.name(), ActiveCache{config, new_cache});
  return new_cache;
}

DnsCacheSharedPtr DnsCacheManagerImpl::lookUpCacheByName(absl::string_view cache_name) {
  ASSERT(context_.mainThreadDispatcher().isThreadSafe());
  const auto& existing_cache = caches_.find(cache_name);
  if (existing_cache != caches_.end()) {
    return existing_cache->second.cache_;
  }

  return nullptr;
}

DnsCacheManagerSharedPtr DnsCacheManagerFactoryImpl::get() {
  return context_.singletonManager().getTyped<DnsCacheManager>(
      SINGLETON_MANAGER_REGISTERED_NAME(dns_cache_manager),
      [this] { return std::make_shared<DnsCacheManagerImpl>(context_); });
}

} // namespace DynamicForwardProxy
} // namespace Common
} // namespace Extensions
} // namespace Envoy


text:
		<title>Test Page for CriticalCSS</title>
		<link href="./all-pseudo.css" rel="stylesheet" />

Hi

This is some content

This is pretty far down


text:
using namespace std;

class KineticExample {
private:
  emkStage stage;
  emkLayer layer;
  emkRect rect;

  emkAnimation<KineticExample> anim;

public:
  KineticExample()
    : stage(578, 200, "container")
    , rect(289, 100, 200, 20, "green", "black", 4)
  {
    rect.SetOffset(100, 10);
    layer.Add(rect);
    stage.Add(layer);

    stage.On("contentMousemove", this, &KineticExample::DoRectRotation);
  }

  void DoRectRotation() {
    rect.DoRotate(10);
    layer.BatchDraw();
  }
};

extern "C" int emkMain()
{
  KineticExample * example = new KineticExample();
  return (int) example;
}


text:
import io
import tarfile

text = 'This is the data to write to the archive.'
data = text.encode('utf-8')

with tarfile.open('addfile_string.tar', mode='w') as out:
    info = tarfile.TarInfo('made_up_file.txt')
    info.size = len(data)
    out.addfile(info, io.BytesIO(data))

print('Contents:')
with tarfile.open('addfile_string.tar', mode='r') as t:
    for member_info in t.getmembers():
        print(member_info.name)
        f = t.extractfile(member_info)
        print(f.read().decode('utf-8'))


text:
This is a Julia package that implements several light-weight Bayesian models, primarily for supporting the research on Bayesian inference and estimation.

**Note:** This package is still in the *experimental* stage, and is primarily for support internal research purpose. Also, it has not been registered at the official registry [METADATA.jl](https://github.com/JuliaLang/METADATA.jl).

## Setup

As it has not been officially registered, you may not use `Pkg.add` to install the package. Instead, you should check it out directly as

```bash
# enter the directory that hosts the Julia repositories
cd ~/.julia/v0.4

# clone the package
git clone https://github.com/lindahua/LightBayes.jl.git LightBayes

# run the tests to make sure it works
cd LightBayes
julia test/runtests.jl
```

## API

This package introduces an abstract type:

```julia
# The base type for all likelihood models,
# which connect the parameters with observations
abstract LikelihoodModel
```

Here, we assume that both the parameter space and observation space are always vector spaces.

#### Methods for Prior

Prior distributions are simply using the distributions in the [Distributions](https://github.com/JuliaStats/Distributions.jl) package. However, for those distributions that may serve as a *prior* here, we introduce additional methods:

```julia
# Let pri be a prior distribution

# compute the unnormalized log-pdf for given parameters
# θ can be either a single parameter or an array of
# multiple parameters
logupdf(pri, θ)
logupdf!(r, pri, θ)

# compute the log-partition value
logpar(pri)

# compute the posterior distribution, given sufficient
# statistics collected from observations
posterior(pri, sstats)

# find the mode of the posterior distribution
# This is useful for MAP estimation
posterior_mode(pri, sstats)
posterior_mode!(r, pri, sstats)

# sample from the posterior distribution
posterior_rand(pri, sstats)
posterior_rand!(r, pri, sstats)
```

#### Methods for Likelihood Model

```julia
# Let md be a likelihood model

# return a distribution, given parameter
d = withparams(md, θ)

# get the number of samples in X, w.r.t. md
n = nsamples(md, X)

# compute sufficient statistics, given observed data
ss = suffstats(md, X)
ss = suffstats(md, X, inds)

# to get a posterior given data, one can write
post = posterior(pri, suffstats(md, X))
```

## Models

Currently, we implement the following likelihood models

```julia
# x ~ N(θ, σ^2), where σ^2 is fixed a priori
# conjugate prior type: IsoNormal
immutable IsoGaussModel <: LikelihoodModel
    σ::Float64
end

```


text:
package pointofsale;

public class PointOfSale {

	private Display display;
	private Store store;

	public PointOfSale(Display display, Store store) {
		this.display = display;
		this.store = store;
	}

	public void onBarcode(String barcode) {

		if (barcode == null || barcode.equals("")) {
			display.show("No code received");
		} else {
			Item item = store.getItem(barcode);

			if(item != null) {
				display.show(item.getPrice());
			} else {
				display.show("Not found in store");
			}
		}
	}

}


text:
package com.kotcrab.vis.runtime.component;

import com.artemis.Component;

/** @author Kotcrab */
public class PhysicsSprite extends Component {
	public float originalRotation;

	public PhysicsSprite () {
	}

	public PhysicsSprite (float originalRotation) {
		this.originalRotation = originalRotation;
	}
}


text:
from msrest.paging import Paged

class SBTopicPaged(Paged):
    """
    A paging container for iterating over a list of SBTopic object
    """

    _attribute_map = {
        'next_link': {'key': 'nextLink', 'type': 'str'},
        'current_page': {'key': 'value', 'type': '[SBTopic]'}
    }

    def __init__(self, *args, **kwargs):

        super(SBTopicPaged, self).__init__(*args, **kwargs)


text:
require_relative '../errors/debug_code_generator_error.rb'

module DebugCodeGenerator
    require_relative "#{File.dirname(File.realpath(__FILE__))}/../utils/dijkstra_algorithm.rb"

    #For debugging we use DEVS
    K = 1000
    FLOW_DEFAULT_PRIORITY = 0
    FLOW_DEFAULT_GENERATION_PERIOD = ExponentialDistribution.new 1.0 / (100*K) # distribution period in seconds
    FLOW_DEFAULT_GENERATION_SIZE = NormalDistribution.new 4.0*K, 1.0*K  # (in bytes)

    def generate_output(file_name)
        @id_currently_flow = 0
        @identifiers.each do |identifier|
            case identifier.value
            when HaikunetHost
                mac_value = host_value_of identifier, 'mac'
                ips_value = host_value_of identifier, 'ipAddresses'

                # We are going to define that a host exist in the topology if the mac is already defined.
                next if is_defined_in_topology mac_value, ips_value

                # If we are here, that means that the host does not exist in the topology. This means that
                # we need some extra info to define it.
                vlan_value = host_value_of identifier, 'vlan'
                element_id_value = host_value_of identifier, 'elementId'
                port_value = host_value_of identifier, 'port'
                my_host = @initial_topology.add_host "#{mac_value}/#{vlan_value}", ips_value, mac_value

                switch = @initial_topology.get_element_by_id element_id_value
                raise_semantic_error "the switch #{element_id_value} is not defined in the initial topology!." unless switch

                @initial_topology.add_full_duplex_link  "Link#{mac_value.gsub ':', ''}_to_#{element_id_value.gsub ':', ''}",
                                                my_host,
                                                0,
                                                element_id_value,
                                                port_value.to_i
            when HaikunetFlow
                flow_params = get_flow_params identifier
                flow_params['src'].each do |src_mac|
                  flow_params['dst'].each do |dst_mac|
                    @initial_topology.add_flow  "Flow#{@id_currently_flow}",
                                        FLOW_DEFAULT_PRIORITY,
                                        [(find_path_between src_mac, dst_mac)],
                                        FLOW_DEFAULT_GENERATION_PERIOD,
                                        FLOW_DEFAULT_GENERATION_SIZE
                    @id_currently_flow += 1
                  end
                end
            when HaikunetIntent
                #Should read the action, and implement an automatic checker given the output
                #of Scilab
            end
        end
        topology_generator = Topologygenerator.new({
            "source" => "OBJECT",
            "directory_concrete_builders" => "#{File.dirname(File.realpath(__FILE__))}/../haikunet_builders/debug_builders",
            "output_directory" => "#{ENV['HOME']}/.haikunet/debug/#{file_name}",
            "uri_resource" => @initial_topology
        })
        topology_generator.generate
    end

    def host_value_of(host_identifier, property)
        identifier = host_identifier.value.params.select{ |identifier| identifier.name == property }.first
        raise DebugCodeGeneratorError, "Property #{property} was not found in host identifier and is needed to create the simulation." if identifier.nil?
        identifier.value
    end

    def get_flow_params(flow_identifier)
        src = value_from 'src', flow_identifier.value.params
        src_mac = get_macs_from src
        dst = value_from 'dst', flow_identifier.value.params
        dst_mac = get_macs_from dst
        priority = value_from 'priority', flow_identifier.value.params

        {'src' => src_mac, 'dst' => dst_mac, 'priority' => priority}
    end

    def get_macs_from(resource)
      macs = []
      if resource.is_a? Array
        resource.each do |identifier|
          macs.push value_from 'mac', identifier.value.params
        end
      else
        macs.push value_from 'mac', resource.value.params
      end
      macs
    end

    def is_defined_in_topology(mac_value, ips_value)
        res = false
        host = (@initial_topology.elements_of_type Host).select { |host| host.mac == mac_value}.first
        if host
            res = true
            warn "The host with mac #{mac_value} has changed the ip, new ips are #{ips_value}, while the old ones were #{host.ips}" unless ips_value.include? host.ips
        end
        res
    end

    def find_path_between(src_mac, dst_mac)
        links = @initial_topology.elements_of_type Link
        hosts = @initial_topology.elements_of_type Host

        graph = []
        links.each do |link|
            graph.push [link.src_element,link.dst_element,1]
        end

        src = hosts.find { |host| host.mac == src_mac }
        dst = hosts.find { |host| host.mac == dst_mac }

        solution = Dijkstra.new src, dst, graph
        path = solution.shortest_path

        #Now we have to find the link that connects both elements to add it to the path!
        my_path = Path.new src, dst
        path.each_with_index do |elem, index|
            break if path.size == (index + 1)
            my_path.add_link links.find{ |link| (link.src_element == elem) && (link.dst_element == path[index+1]) }
        end

        my_path
    end

    def value_from(value_name, array)
        array.select { |elem| elem.name == value_name }.first.value
    end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frag_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.hu.yang.baseskill_android.activity.MainActivity">

</FrameLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Biologia, Lahore 6(2): 127 (1961)

#### Original name
Coryneum piricola S. Ahmad

### Remarks
null


text:
This is a configuration provider forthe up-coming secrets feature of Docker 1.13.

You can use this provider in an ASP.NET Core application that is running in Docker Swarm Mode with commands like the following:

```
$ echo "mySecretValue" | docker secrets create mysecret

```

```
$ docker service create --name test --secret mysecret <myImageName>
```

Now the `test` service will be running and have access to a secret called mysecret. In your app you can access it with

```
var secretValue = Configuration["mysecret"];
```


text:
import { Document } from "../../Document";
import { Helper, RTFJSError } from "../../Helper";
import { GlobalState } from "../Containers";
import { RtfDestination } from "./RtfDestination";

export abstract class DestinationFactory<T extends IDestination> {
    public class: new (parser: GlobalState, inst: Document, name: string, param: number) => T;

    public newDestination(parser: GlobalState, inst: Document, name: string, param: number): T {
        return new this.class(parser, inst, name, param);
    }
}

export interface IDestination {
    _name: string;

    setMetadata?(metaprop: string, metavalue: any): void;

    apply?(): void;

    appendText?(text: string): void;

    sub?(): IDestination;

    handleKeyword?(keyword: string, param: number): void | boolean;

    handleBlob?(blob: ArrayBuffer): void;

    [key: string]: any;
}

export const findParentDestination = (parser: GlobalState, dest: string) => {
    let state = parser.state;
    while (state != null) {
        if (state.destination == null) {
            break;
        }
        if (state.destination._name === dest) {
            return state.destination;
        }
        state = state.parent;
    }
    Helper.log("findParentDestination() did not find destination " + dest);
};

export class DestinationBase implements IDestination {
    public _name: string;

    constructor(name: string) {
        this._name = name;
    }
}

export class DestinationTextBase implements IDestination {
    public _name: string;
    public text: string;

    constructor(name: string) {
        this._name = name;
        this.text = "";
    }

    public appendText(text: string): void {
        this.text += text;
    }
}

export abstract class DestinationFormattedTextBase implements IDestination {
    public _name: string;
    protected parser: GlobalState;
    private _records: ((rtf: RtfDestination) => void)[];

    constructor(parser: GlobalState, name: string) {
        this.parser = parser;
        this._name = name;
        this._records = [];
    }

    public appendText(text: string): void {
        this._records.push((rtf: RtfDestination) => {
            rtf.appendText(text);
        });
    }

    public handleKeyword(keyword: string, param: number): void {
        this._records.push((rtf: RtfDestination) => {
            return rtf.handleKeyword(keyword, param);
        });
    }

    public apply(): void {
        const rtf = findParentDestination(this.parser, "rtf") as any as RtfDestination;
        if (rtf == null) {
            throw new RTFJSError("IDestination " + this._name + " is not child of rtf destination");
        }

        const len = this._records.length;
        let doRender = true;
        if (this.renderBegin != null) {
            doRender = this.renderBegin(rtf, len);
        }

        if (doRender) {
            for (let i = 0; i < len; i++) {
                this._records[i](rtf);
            }
            if (this.renderEnd != null) {
                this.renderEnd(rtf, len);
            }
        }
        delete this._records;
    }

    public abstract renderBegin(rtf: RtfDestination, records: number): boolean;

    public abstract renderEnd(rtf: RtfDestination, records: number): void;
}

export interface IGenericPropertyDestination extends IDestination {
    apply(): void;
}

export class GenericPropertyDestinationFactory extends DestinationFactory<IGenericPropertyDestination> {
    constructor(parentdest: string, metaprop: string) {
        super();
        this.class = class extends DestinationTextBase implements IGenericPropertyDestination {
            private parser: GlobalState;

            constructor(parser: GlobalState, inst: Document, name: string) {
                super(name);
                this.parser = parser;
            }

            public apply() {
                const dest = findParentDestination(this.parser, parentdest);
                if (dest == null) {
                    throw new RTFJSError("IDestination " + this._name + " must be within "
                        + parentdest + " destination");
                }
                if (dest.setMetadata == null) {
                    throw new RTFJSError("IDestination " + parentdest + " does not accept meta data");
                }
                dest.setMetadata(metaprop, this.text);
            }
        };
    }
}

export interface IGenericSubTextPropertyDestination extends IDestination {
    apply(): void;
}

export class GenericSubTextPropertyDestinationFactory extends DestinationFactory<IGenericSubTextPropertyDestination> {
    constructor(name: string, parentDest: string, propOrFunc: string) {
        super();
        this.class = class extends DestinationTextBase implements IGenericSubTextPropertyDestination {
            private parser: GlobalState;

            constructor(parser: GlobalState) {
                super(name);
                this.parser = parser;
            }

            public apply() {
                const dest = findParentDestination(this.parser, parentDest);
                if (dest == null) {
                    throw new RTFJSError(this._name + " destination must be child of " + parentDest + " destination");
                }
                if (dest[propOrFunc] == null) {
                    throw new RTFJSError(this._name + " destination cannot find member + " + propOrFunc
                        + " in " + parentDest + " destination");
                }
                if (dest[propOrFunc] instanceof Function) {
                    dest[propOrFunc](this.text);
                } else {
                    dest[propOrFunc] = this.text;
                }
            }
        };
    }
}

export class RequiredDestinationFactory extends DestinationFactory<IDestination> {
    constructor(name: string) {
        super();
        this.class = class extends DestinationBase implements IDestination {
            constructor() {
                super(name);
            }
        };
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.provisioning;

import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Capacity;
import com.yahoo.config.provision.CloudName;
import com.yahoo.config.provision.ClusterResources;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.flags.JacksonFlag;
import com.yahoo.vespa.flags.PermanentFlags;
import com.yahoo.vespa.flags.StringFlag;
import com.yahoo.vespa.flags.custom.SharedHost;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import java.util.Map;
import java.util.TreeMap;

import static com.yahoo.config.provision.NodeResources.Architecture;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static java.util.Objects.requireNonNull;

/**
 * Defines the policies for assigning cluster capacity in various environments
 *
 * @author bratseth
 * @see NodeResourceLimits
 */
public class CapacityPolicies {

    private final Zone zone;
    private final JacksonFlag<SharedHost> sharedHosts;
    private final StringFlag adminClusterNodeArchitecture;

    public CapacityPolicies(NodeRepository nodeRepository) {
        this.zone = nodeRepository.zone();
        this.sharedHosts = PermanentFlags.SHARED_HOST.bindTo(nodeRepository.flagSource());
        this.adminClusterNodeArchitecture = PermanentFlags.ADMIN_CLUSTER_NODE_ARCHITECTURE.bindTo(nodeRepository.flagSource());
    }

    public Capacity applyOn(Capacity capacity, ApplicationId application, boolean exclusive) {
        return capacity.withLimits(applyOn(capacity.minResources(), capacity, application, exclusive),
                                   applyOn(capacity.maxResources(), capacity, application, exclusive));
    }

    private ClusterResources applyOn(ClusterResources resources, Capacity capacity, ApplicationId application, boolean exclusive) {
        int nodes = decideSize(resources.nodes(), capacity.isRequired(), application.instance().isTester());
        int groups = Math.min(resources.groups(), nodes); // cannot have more groups than nodes
        var nodeResources = decideNodeResources(resources.nodeResources(), capacity.isRequired(), exclusive);
        return new ClusterResources(nodes, groups, nodeResources);
    }

    private int decideSize(int requested, boolean required, boolean isTester) {
        if (isTester) return 1;

        if (required) return requested;
        return switch (zone.environment()) {
            case dev, test -> 1;
            case perf -> Math.min(requested, 3);
            case staging -> requested <= 1 ? requested : Math.max(2, requested / 10);
            case prod -> requested;
        };
    }

    private NodeResources decideNodeResources(NodeResources target, boolean required, boolean exclusive) {
        if (required || exclusive) return target;  // Cannot downsize if resources are required, or exclusively allocated
        if (target.isUnspecified()) return target; // Cannot be modified

        // Dev does not cap the cpu or network of containers since usage is spotty: Allocate just a small amount exclusively
        if (zone.environment() == Environment.dev && zone.cloud().allowHostSharing())
            target = target.withVcpu(0.1).withBandwidthGbps(0.1);

        // Allow slow storage in zones which are not performance sensitive
        if (zone.system().isCd() || zone.environment() == Environment.dev || zone.environment() == Environment.test)
            target = target.with(NodeResources.DiskSpeed.any).with(NodeResources.StorageType.any).withBandwidthGbps(0.1);

        return target;
    }

    public NodeResources defaultNodeResources(ClusterSpec clusterSpec, ApplicationId applicationId, boolean exclusive) {
        if (clusterSpec.type() == ClusterSpec.Type.admin) {
            Architecture architecture = adminClusterArchitecture(applicationId);

            if (clusterSpec.id().value().equals("cluster-controllers")) {
                return clusterControllerResources(clusterSpec, exclusive)
                        .with(architecture);
            }

            return (requiresExclusiveHost(clusterSpec.type(), exclusive)
                    ? versioned(clusterSpec, Map.of(new Version(0), smallestExclusiveResources()))
                    : versioned(clusterSpec, Map.of(new Version(0), smallestSharedResources())))
                    .with(architecture);
        }

        if (clusterSpec.type() == ClusterSpec.Type.content) {
            return zone.cloud().dynamicProvisioning()
                   ? versioned(clusterSpec, Map.of(new Version(0), new NodeResources(2.0, 8, 50, 0.3),
                                                   new Version(8, 75), new NodeResources(2, 16, 300, 0.3)))
                   : versioned(clusterSpec, Map.of(new Version(0), new NodeResources(1.5, 8, 50, 0.3)));
        }
        else {
            return zone.cloud().dynamicProvisioning()
                   ? versioned(clusterSpec, Map.of(new Version(0), new NodeResources(2.0, 8, 50, 0.3)))
                   : versioned(clusterSpec, Map.of(new Version(0), new NodeResources(1.5, 8, 50, 0.3)));
        }
    }

    private NodeResources clusterControllerResources(ClusterSpec clusterSpec, boolean exclusive) {
        if (requiresExclusiveHost(clusterSpec.type(), exclusive)) {
            return versioned(clusterSpec, Map.of(new Version(0), smallestExclusiveResources()));
        }
        return versioned(clusterSpec, Map.of(new Version(0), new NodeResources(0.25, 1.14, 10, 0.3)));
    }

    private Architecture adminClusterArchitecture(ApplicationId instance) {
        return Architecture.valueOf(adminClusterNodeArchitecture.with(APPLICATION_ID, instance.serializedForm()).value());
    }

    /** Returns whether an exclusive host is required for given cluster type and exclusivity requirement */
    private boolean requiresExclusiveHost(ClusterSpec.Type type, boolean exclusive) {
        return ! zone.cloud().allowHostSharing() && (exclusive || !sharedHosts.value().isEnabled(type.name()));
    }

    /** Returns the resources for the newest version not newer than that requested in the cluster spec. */
    static NodeResources versioned(ClusterSpec spec, Map<Version, NodeResources> resources) {
        return requireNonNull(new TreeMap<>(resources).floorEntry(spec.vespaVersion()),
                              "no default resources applicable for " + spec + " among: " + resources)
                .getValue();
    }

    // The lowest amount resources that can be exclusive allocated (i.e. a matching host flavor for this exists)
    private NodeResources smallestExclusiveResources() {
        return (zone.cloud().name().equals(CloudName.GCP))
                ? new NodeResources(1, 4, 50, 0.3)
                : new NodeResources(0.5, 4, 50, 0.3);
    }

    // The lowest amount resources that can be shared (i.e. a matching host flavor for this exists)
    private NodeResources smallestSharedResources() {
        return (zone.cloud().name().equals(CloudName.GCP))
                ? new NodeResources(1, 4, 50, 0.3)
                : new NodeResources(0.5, 2, 50, 0.3);
    }

    /** Returns whether the nodes requested can share physical host with other applications */
    public boolean decideExclusivity(Capacity capacity, boolean requestedExclusivity) {
        if (capacity.cloudAccount().isPresent()) return true; // Implicit exclusive when using custom cloud account
        return requestedExclusivity && (capacity.isRequired() || zone.environment() == Environment.prod);
    }

}


text:
import sys
import os
import shutil

def cmake(platform_dir, src_dir, arg):
    if not(os.path.exists(platform_dir)):
        os.mkdir(platform_dir)
    os.chdir(platform_dir)				# go to platform directory
    cmd = "cmake " + arg + " ../" + src_dir
    print("cmd")
    os.system(cmd)						# run cmake

def clean(platform_dir):
    if os.path.exists(platform_dir):
        shutil.rmtree(platform_dir)

if __name__ == '__main__':
    src_dir = '../src/' 					# source code directory
    bin_dir = '../build/' 				# binary directory
    if not(os.path.exists(bin_dir)): 	# binary directory is created if not found
        os.mkdir(bin_dir)
    platform = sys.platform
    cmd = ""
    if (platform == 'darwin'): 			# platform directory is created if not found
        platform = 'mac'
        cmd = '-G Xcode'
    platform_dir = bin_dir + platform
    for arg in sys.argv:
        if   (arg == '--cmake'):
            cmake(platform_dir, src_dir, cmd)
        elif (arg == '--clean'):
            clean(platform_dir)


text:
@interface CircularDependenciesAssembly : TyphoonAssembly

- (id)classA;

- (id)classB;

- (id)classC;

- (id)classD;

- (id)classE;

//- (id)unsatisfiableClassFWithCircularDependencyInInitializer;
//- (id)unsatisfiableClassGWithCircularDependencyInInitializer;

- (id)prototypeInitInjected;

- (id)prototypePropertyInjected;

- (id)croSingletonA;

- (id)croSingletonB;

- (id)croPrototypeA;

- (id)croPrototypeB;

@end