text:
package org.apache.storm.daemon.worker;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
import org.apache.storm.Config;
import org.apache.storm.Constants;
import org.apache.storm.StormTimer;
import org.apache.storm.cluster.DaemonType;
import org.apache.storm.cluster.IStateStorage;
import org.apache.storm.cluster.IStormClusterState;
import org.apache.storm.cluster.VersionedData;
import org.apache.storm.daemon.StormCommon;
import org.apache.storm.daemon.supervisor.AdvancedFSOps;
import org.apache.storm.executor.IRunningExecutor;
import org.apache.storm.generated.Assignment;
import org.apache.storm.generated.DebugOptions;
import org.apache.storm.generated.Grouping;
import org.apache.storm.generated.InvalidTopologyException;
import org.apache.storm.generated.NodeInfo;
import org.apache.storm.generated.StormBase;
import org.apache.storm.generated.StormTopology;
import org.apache.storm.generated.StreamInfo;
import org.apache.storm.generated.TopologyStatus;
import org.apache.storm.grouping.Load;
import org.apache.storm.grouping.LoadMapping;
import org.apache.storm.hooks.IWorkerHook;
import org.apache.storm.messaging.ConnectionWithStatus;
import org.apache.storm.messaging.DeserializingConnectionCallback;
import org.apache.storm.messaging.IConnection;
import org.apache.storm.messaging.IConnectionCallback;
import org.apache.storm.messaging.IContext;
import org.apache.storm.messaging.TransportFactory;
import org.apache.storm.messaging.netty.BackPressureStatus;
import org.apache.storm.metrics2.StormMetricRegistry;
import org.apache.storm.policy.IWaitStrategy;
import org.apache.storm.security.auth.IAutoCredentials;
import org.apache.storm.serialization.ITupleSerializer;
import org.apache.storm.serialization.KryoTupleSerializer;
import org.apache.storm.shade.com.google.common.collect.ImmutableMap;
import org.apache.storm.shade.com.google.common.collect.Sets;
import org.apache.storm.shade.org.apache.commons.lang.Validate;
import org.apache.storm.task.WorkerTopologyContext;
import org.apache.storm.tuple.AddressedTuple;
import org.apache.storm.tuple.Fields;
import org.apache.storm.utils.ConfigUtils;
import org.apache.storm.utils.JCQueue;
import org.apache.storm.utils.ObjectReader;
import org.apache.storm.utils.SupervisorClient;
import org.apache.storm.utils.SupervisorIfaceFactory;
import org.apache.storm.utils.ThriftTopologyUtils;
import org.apache.storm.utils.Utils;
import org.apache.storm.utils.Utils.SmartThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WorkerState {

    private static final Logger LOG = LoggerFactory.getLogger(WorkerState.class);
    private static final long LOAD_REFRESH_INTERVAL_MS = 5000L;
    private static long dropCount = 0;
    final Map<String, Object> conf;
    final IContext mqContext;
    final IConnection receiver;
    final String topologyId;
    final String assignmentId;
    private final Supplier<SupervisorIfaceFactory> supervisorIfaceSupplier;
    final int port;
    final String workerId;
    final IStateStorage stateStorage;
    final IStormClusterState stormClusterState;
    // when worker bootup, worker will start to setup initial connections to
    // other workers. When all connection is ready, we will count down this latch
    // and spout and bolt will be activated, assuming the topology is not deactivated.
    // used in worker only, keep it as a latch
    final CountDownLatch isWorkerActive;
    final AtomicBoolean isTopologyActive;
    final AtomicReference<Map<String, DebugOptions>> stormComponentToDebug;
    // local executors and localTaskIds running in this worker
    final Set<List<Long>> localExecutors;
    final ArrayList<Integer> localTaskIds;
    // [taskId]-> JCQueue :  initialized after local executors are initialized
    final Map<Integer, JCQueue> localReceiveQueues = new HashMap<>();
    final Map<String, Object> topologyConf;
    final StormTopology topology;
    final StormTopology systemTopology;
    final Map<Integer, String> taskToComponent;
    final Map<String, Map<String, Fields>> componentToStreamToFields;
    final Map<String, List<Integer>> componentToSortedTasks;
    final ConcurrentMap<String, Long> blobToLastKnownVersion;
    final ReentrantReadWriteLock endpointSocketLock;
    final AtomicReference<Map<Integer, NodeInfo>> cachedTaskToNodePort;
    final AtomicReference<Map<NodeInfo, IConnection>> cachedNodeToPortSocket;
    // executor id is in form [start_task_id end_task_id]
    final Map<List<Long>, JCQueue> executorReceiveQueueMap;
    final Map<Integer, JCQueue> taskToExecutorQueue;
    final Runnable suicideCallback;
    final Utils.UptimeComputer uptime;
    final Map<String, Object> defaultSharedResources;
    final Map<String, Object> userSharedResources;
    final LoadMapping loadMapping;
    final AtomicReference<Map<String, VersionedData<Assignment>>> assignmentVersions;
    // Timers
    final StormTimer heartbeatTimer = mkHaltingTimer("heartbeat-timer");
    final StormTimer refreshLoadTimer = mkHaltingTimer("refresh-load-timer");
    final StormTimer refreshConnectionsTimer = mkHaltingTimer("refresh-connections-timer");
    final StormTimer refreshCredentialsTimer = mkHaltingTimer("refresh-credentials-timer");
    final StormTimer checkForUpdatedBlobsTimer = mkHaltingTimer("check-for-updated-blobs-timer");
    final StormTimer resetLogLevelsTimer = mkHaltingTimer("reset-log-levels-timer");
    final StormTimer refreshActiveTimer = mkHaltingTimer("refresh-active-timer");
    final StormTimer executorHeartbeatTimer = mkHaltingTimer("executor-heartbeat-timer");
    final StormTimer flushTupleTimer = mkHaltingTimer("flush-tuple-timer");
    final StormTimer userTimer = mkHaltingTimer("user-timer");
    final StormTimer backPressureCheckTimer = mkHaltingTimer("backpressure-check-timer");
    private final WorkerTransfer workerTransfer;
    private final BackPressureTracker bpTracker;
    private final List<IWorkerHook> deserializedWorkerHooks;
    // global variables only used internally in class
    private final Set<Integer> outboundTasks;
    private final AtomicLong nextLoadUpdate = new AtomicLong(0);
    private final boolean trySerializeLocal;
    private final Collection<IAutoCredentials> autoCredentials;
    private final StormMetricRegistry metricRegistry;

    public WorkerState(Map<String, Object> conf,
            IContext mqContext,
            String topologyId,
            String assignmentId,
            Supplier<SupervisorIfaceFactory> supervisorIfaceSupplier,
            int port,
            String workerId,
            Map<String, Object> topologyConf,
            IStateStorage stateStorage,
            IStormClusterState stormClusterState,
            Collection<IAutoCredentials> autoCredentials,
            StormMetricRegistry metricRegistry) throws IOException,
            InvalidTopologyException {
        this.metricRegistry = metricRegistry;
        this.autoCredentials = autoCredentials;
        this.conf = conf;
        this.supervisorIfaceSupplier = supervisorIfaceSupplier;
        this.localExecutors = new HashSet<>(readWorkerExecutors(stormClusterState, topologyId, assignmentId, port));
        this.mqContext = (null != mqContext) ? mqContext : TransportFactory.makeContext(topologyConf);
        this.topologyId = topologyId;
        this.assignmentId = assignmentId;
        this.port = port;
        this.workerId = workerId;
        this.stateStorage = stateStorage;
        this.stormClusterState = stormClusterState;
        this.isWorkerActive = new CountDownLatch(1);
        this.isTopologyActive = new AtomicBoolean(false);
        this.stormComponentToDebug = new AtomicReference<>();
        this.executorReceiveQueueMap = mkReceiveQueueMap(topologyConf, localExecutors);
        this.localTaskIds = new ArrayList<>();
        this.taskToExecutorQueue = new HashMap<>();
        this.blobToLastKnownVersion = new ConcurrentHashMap<>();
        for (Map.Entry<List<Long>, JCQueue> entry : executorReceiveQueueMap.entrySet()) {
            List<Integer> taskIds = StormCommon.executorIdToTasks(entry.getKey());
            for (Integer taskId : taskIds) {
                this.taskToExecutorQueue.put(taskId, entry.getValue());
            }
            this.localTaskIds.addAll(taskIds);
        }
        Collections.sort(localTaskIds);
        this.topologyConf = topologyConf;
        this.topology = ConfigUtils.readSupervisorTopology(conf, topologyId, AdvancedFSOps.make(conf));
        this.systemTopology = StormCommon.systemTopology(topologyConf, topology);
        this.taskToComponent = StormCommon.stormTaskInfo(topology, topologyConf);
        this.componentToStreamToFields = new HashMap<>();
        for (String c : ThriftTopologyUtils.getComponentIds(systemTopology)) {
            Map<String, Fields> streamToFields = new HashMap<>();
            for (Map.Entry<String, StreamInfo> stream :
                ThriftTopologyUtils.getComponentCommon(systemTopology, c).get_streams().entrySet()) {
                streamToFields.put(stream.getKey(), new Fields(stream.getValue().get_output_fields()));
            }
            componentToStreamToFields.put(c, streamToFields);
        }
        this.componentToSortedTasks = Utils.reverseMap(taskToComponent);
        this.componentToSortedTasks.values().forEach(Collections::sort);
        this.endpointSocketLock = new ReentrantReadWriteLock();
        this.cachedNodeToPortSocket = new AtomicReference<>(new HashMap<>());
        this.cachedTaskToNodePort = new AtomicReference<>(new HashMap<>());
        this.suicideCallback = Utils.mkSuicideFn();
        this.uptime = Utils.makeUptimeComputer();
        this.defaultSharedResources = makeDefaultResources();
        this.userSharedResources = makeUserResources();
        this.loadMapping = new LoadMapping();
        this.assignmentVersions = new AtomicReference<>(new HashMap<>());
        this.outboundTasks = workerOutboundTasks();
        this.trySerializeLocal = topologyConf.containsKey(Config.TOPOLOGY_TESTING_ALWAYS_TRY_SERIALIZE)
                                 && (Boolean) topologyConf.get(Config.TOPOLOGY_TESTING_ALWAYS_TRY_SERIALIZE);
        if (trySerializeLocal) {
            LOG.warn("WILL TRY TO SERIALIZE ALL TUPLES (Turn off {} for production", Config.TOPOLOGY_TESTING_ALWAYS_TRY_SERIALIZE);
        }
        int maxTaskId = getMaxTaskId(componentToSortedTasks);
        this.workerTransfer = new WorkerTransfer(this, topologyConf, maxTaskId);
        this.bpTracker = new BackPressureTracker(workerId, taskToExecutorQueue);
        this.deserializedWorkerHooks = deserializeWorkerHooks();
        LOG.info("Registering IConnectionCallbacks for {}:{}", assignmentId, port);
        IConnectionCallback cb = new DeserializingConnectionCallback(topologyConf,
            getWorkerTopologyContext(),
            this::transferLocalBatch);
        Supplier<Object> newConnectionResponse = () -> {
            BackPressureStatus bpStatus = bpTracker.getCurrStatus();
            LOG.info("Sending BackPressure status to new client. BPStatus: {}", bpStatus);
            return bpStatus;
        };
        this.receiver = this.mqContext.bind(topologyId, port, cb, newConnectionResponse);
    }

    private static double getQueueLoad(JCQueue queue) {
        JCQueue.QueueMetrics queueMetrics = queue.getMetrics();
        return ((double) queueMetrics.population()) / queueMetrics.capacity();
    }

    public static boolean isConnectionReady(IConnection connection) {
        return !(connection instanceof ConnectionWithStatus)
               || ((ConnectionWithStatus) connection).status() == ConnectionWithStatus.Status.Ready;
    }

    private static int getMaxTaskId(Map<String, List<Integer>> componentToSortedTasks) {
        int maxTaskId = -1;
        for (List<Integer> integers : componentToSortedTasks.values()) {
            if (!integers.isEmpty()) {
                int tempMax = integers.stream().max(Integer::compareTo).get();
                if (tempMax > maxTaskId) {
                    maxTaskId = tempMax;
                }
            }
        }
        return maxTaskId;
    }

    public List<IWorkerHook> getDeserializedWorkerHooks() {
        return deserializedWorkerHooks;
    }

    public Map<String, Object> getConf() {
        return conf;
    }

    public IConnection getReceiver() {
        return receiver;
    }

    public String getTopologyId() {
        return topologyId;
    }

    public int getPort() {
        return port;
    }

    public String getWorkerId() {
        return workerId;
    }

    public IStateStorage getStateStorage() {
        return stateStorage;
    }

    public CountDownLatch getIsWorkerActive() {
        return isWorkerActive;
    }

    public AtomicBoolean getIsTopologyActive() {
        return isTopologyActive;
    }

    public AtomicReference<Map<String, DebugOptions>> getStormComponentToDebug() {
        return stormComponentToDebug;
    }

    public Set<List<Long>> getLocalExecutors() {
        return localExecutors;
    }

    public List<Integer> getLocalTaskIds() {
        return localTaskIds;
    }

    public Map<Integer, JCQueue> getLocalReceiveQueues() {
        return localReceiveQueues;
    }

    public Map<String, Object> getTopologyConf() {
        return topologyConf;
    }

    public StormTopology getTopology() {
        return topology;
    }

    public StormTopology getSystemTopology() {
        return systemTopology;
    }

    public Map<Integer, String> getTaskToComponent() {
        return taskToComponent;
    }

    public Map<String, Map<String, Fields>> getComponentToStreamToFields() {
        return componentToStreamToFields;
    }

    public Map<String, List<Integer>> getComponentToSortedTasks() {
        return componentToSortedTasks;
    }

    public Map<String, Long> getBlobToLastKnownVersion() {
        return blobToLastKnownVersion;
    }

    public AtomicReference<Map<NodeInfo, IConnection>> getCachedNodeToPortSocket() {
        return cachedNodeToPortSocket;
    }

    public Map<List<Long>, JCQueue> getExecutorReceiveQueueMap() {
        return executorReceiveQueueMap;
    }

    public Runnable getSuicideCallback() {
        return suicideCallback;
    }

    public Utils.UptimeComputer getUptime() {
        return uptime;
    }

    public Map<String, Object> getDefaultSharedResources() {
        return defaultSharedResources;
    }

    public Map<String, Object> getUserSharedResources() {
        return userSharedResources;
    }

    public LoadMapping getLoadMapping() {
        return loadMapping;
    }

    public AtomicReference<Map<String, VersionedData<Assignment>>> getAssignmentVersions() {
        return assignmentVersions;
    }

    public StormTimer getUserTimer() {
        return userTimer;
    }

    public SmartThread makeTransferThread() {
        return workerTransfer.makeTransferThread();
    }

    public void refreshConnections() {
        Assignment assignment = null;
        try {
            assignment = getLocalAssignment(stormClusterState, topologyId);
        } catch (Exception e) {
            LOG.warn("Failed to read assignment. This should only happen when topology is shutting down.", e);
        }

        Set<NodeInfo> neededConnections = new HashSet<>();
        Map<Integer, NodeInfo> newTaskToNodePort = new HashMap<>();
        if (null != assignment) {
            Map<Integer, NodeInfo> taskToNodePort = StormCommon.taskToNodeport(assignment.get_executor_node_port());
            for (Map.Entry<Integer, NodeInfo> taskToNodePortEntry : taskToNodePort.entrySet()) {
                Integer task = taskToNodePortEntry.getKey();
                if (outboundTasks.contains(task)) {
                    newTaskToNodePort.put(task, taskToNodePortEntry.getValue());
                    if (!localTaskIds.contains(task)) {
                        neededConnections.add(taskToNodePortEntry.getValue());
                    }
                }
            }
        }

        Set<NodeInfo> currentConnections = cachedNodeToPortSocket.get().keySet();
        Set<NodeInfo> newConnections = Sets.difference(neededConnections, currentConnections);
        Set<NodeInfo> removeConnections = Sets.difference(currentConnections, neededConnections);

        Map<String, String> nodeHost = assignment != null ? assignment.get_node_host() : null;
        // Add new connections atomically
        cachedNodeToPortSocket.getAndUpdate(prev -> {
            Map<NodeInfo, IConnection> next = new HashMap<>(prev);
            for (NodeInfo nodeInfo : newConnections) {
                next.put(nodeInfo,
                         mqContext.connect(
                             topologyId,
                             //nodeHost is not null here, as newConnections is only non-empty if assignment was not null above.
                             nodeHost.get(nodeInfo.get_node()),    // Host
                             nodeInfo.get_port().iterator().next().intValue(),       // Port
                             workerTransfer.getRemoteBackPressureStatus()));
            }
            return next;
        });

        try {
            endpointSocketLock.writeLock().lock();
            cachedTaskToNodePort.set(newTaskToNodePort);
        } finally {
            endpointSocketLock.writeLock().unlock();
        }

        for (NodeInfo nodeInfo : removeConnections) {
            cachedNodeToPortSocket.get().get(nodeInfo).close();
        }

        // Remove old connections atomically
        cachedNodeToPortSocket.getAndUpdate(prev -> {
            Map<NodeInfo, IConnection> next = new HashMap<>(prev);
            removeConnections.forEach(next::remove);
            return next;
        });

    }

    public void refreshStormActive() {
        refreshStormActive(() -> refreshActiveTimer.schedule(0, this::refreshStormActive));
    }

    public void refreshStormActive(Runnable callback) {
        StormBase base = stormClusterState.stormBase(topologyId, callback);
        isTopologyActive.set(
            (null != base)
            && (base.get_status() == TopologyStatus.ACTIVE));
        if (null != base) {
            Map<String, DebugOptions> debugOptionsMap = new HashMap<>(base.get_component_debug());
            for (DebugOptions debugOptions : debugOptionsMap.values()) {
                if (!debugOptions.is_set_samplingpct()) {
                    debugOptions.set_samplingpct(10);
                }
                if (!debugOptions.is_set_enable()) {
                    debugOptions.set_enable(false);
                }
            }
            stormComponentToDebug.set(debugOptionsMap);
            LOG.debug("Events debug options {}", stormComponentToDebug.get());
        }
    }

    public void refreshLoad(List<IRunningExecutor> execs) {
        Set<Integer> remoteTasks = Sets.difference(new HashSet<>(outboundTasks), new HashSet<>(localTaskIds));
        Map<Integer, Double> localLoad = new HashMap<>();
        for (IRunningExecutor exec : execs) {
            double receiveLoad = getQueueLoad(exec.getReceiveQueue());
            localLoad.put(exec.getExecutorId().get(0).intValue(), receiveLoad);
        }

        Map<Integer, Load> remoteLoad = new HashMap<>();
        cachedNodeToPortSocket.get().values().stream().forEach(conn -> remoteLoad.putAll(conn.getLoad(remoteTasks)));
        loadMapping.setLocal(localLoad);
        loadMapping.setRemote(remoteLoad);

        Long now = System.currentTimeMillis();
        if (now > nextLoadUpdate.get()) {
            receiver.sendLoadMetrics(localLoad);
            nextLoadUpdate.set(now + LOAD_REFRESH_INTERVAL_MS);
        }
    }

    // checks if the tasks which had back pressure are now free again. if so, sends an update to other workers
    public void refreshBackPressureStatus() {
        LOG.debug("Checking for change in Backpressure status on worker's tasks");
        boolean bpSituationChanged = bpTracker.refreshBpTaskList();
        if (bpSituationChanged) {
            BackPressureStatus bpStatus = bpTracker.getCurrStatus();
            receiver.sendBackPressureStatus(bpStatus);
        }
    }

    /**
     * we will wait all connections to be ready and then activate the spout/bolt when the worker bootup.
     */
    public void activateWorkerWhenAllConnectionsReady() {
        int delaySecs = 0;
        int recurSecs = 1;
        refreshActiveTimer.schedule(delaySecs,
            () -> {
                if (areAllConnectionsReady()) {
                    LOG.info("All connections are ready for worker {}:{} with id {}", assignmentId, port, workerId);
                    isWorkerActive.countDown();
                } else {
                    refreshActiveTimer.schedule(recurSecs, () -> activateWorkerWhenAllConnectionsReady(), false, 0);
                }
            }
        );
    }

    /* Not a Blocking call. If cannot emit, will add 'tuple' to pendingEmits and return 'false'. 'pendingEmits' can be null */
    public boolean tryTransferRemote(AddressedTuple tuple, Queue<AddressedTuple> pendingEmits, ITupleSerializer serializer) {
        return workerTransfer.tryTransferRemote(tuple, pendingEmits, serializer);
    }

    public void flushRemotes() throws InterruptedException {
        workerTransfer.flushRemotes();
    }

    public boolean tryFlushRemotes() {
        return workerTransfer.tryFlushRemotes();
    }

    // Receives msgs from remote workers and feeds them to local executors. If any receiving local executor is under Back Pressure,
    // informs other workers about back pressure situation. Runs in the NettyWorker thread.
    private void transferLocalBatch(ArrayList<AddressedTuple> tupleBatch) {
        int lastOverflowCount = 0; // overflowQ size at the time the last BPStatus was sent

        for (int i = 0; i < tupleBatch.size(); i++) {
            AddressedTuple tuple = tupleBatch.get(i);
            JCQueue queue = taskToExecutorQueue.get(tuple.dest);

            // 1- try adding to main queue if its overflow is not empty
            if (queue.isEmptyOverflow()) {
                if (queue.tryPublish(tuple)) {
                    continue;
                }
            }

            // 2- BP detected (i.e MainQ is full). So try adding to overflow
            int currOverflowCount = queue.getOverflowCount();
            if (bpTracker.recordBackPressure(tuple.dest)) {
                receiver.sendBackPressureStatus(bpTracker.getCurrStatus());
                lastOverflowCount = currOverflowCount;
            } else {

                if (currOverflowCount - lastOverflowCount > 10000) {
                    // resend BP status, in case prev notification was missed or reordered
                    BackPressureStatus bpStatus = bpTracker.getCurrStatus();
                    receiver.sendBackPressureStatus(bpStatus);
                    lastOverflowCount = currOverflowCount;
                    LOG.debug("Re-sent BackPressure Status. OverflowCount = {}, BP Status ID = {}. ", currOverflowCount, bpStatus.id);
                }
            }
            if (!queue.tryPublishToOverflow(tuple)) {
                dropMessage(tuple, queue);
            }
        }
    }

    private void dropMessage(AddressedTuple tuple, JCQueue queue) {
        ++dropCount;
        queue.recordMsgDrop();
        LOG.warn(
            "Dropping message as overflow threshold has reached for Q = {}. OverflowCount = {}. Total Drop Count= {}, Dropped Message : {}",
            queue.getName(), queue.getOverflowCount(), dropCount, tuple);
    }

    public void checkSerialize(KryoTupleSerializer serializer, AddressedTuple tuple) {
        if (trySerializeLocal) {
            serializer.serialize(tuple.getTuple());
        }
    }

    public final WorkerTopologyContext getWorkerTopologyContext() {
        try {
            String codeDir = ConfigUtils.supervisorStormResourcesPath(ConfigUtils.supervisorStormDistRoot(conf, topologyId));
            String pidDir = ConfigUtils.workerPidsRoot(conf, topologyId);
            return new WorkerTopologyContext(systemTopology, topologyConf, taskToComponent, componentToSortedTasks,
                                             componentToStreamToFields, topologyId, codeDir, pidDir, port, localTaskIds,
                                             defaultSharedResources,
                                             userSharedResources, cachedTaskToNodePort, assignmentId);
        } catch (IOException e) {
            throw Utils.wrapInRuntime(e);
        }
    }

    private List<IWorkerHook> deserializeWorkerHooks() {
        List<IWorkerHook> myHookList = new ArrayList<>();
        if (topology.is_set_worker_hooks()) {
            for (ByteBuffer hook : topology.get_worker_hooks()) {
                byte[] hookBytes = Utils.toByteArray(hook);
                IWorkerHook hookObject = Utils.javaDeserialize(hookBytes, IWorkerHook.class);
                myHookList.add(hookObject);
            }
        }
        return myHookList;
    }

    public void runWorkerStartHooks() {
        WorkerTopologyContext workerContext = getWorkerTopologyContext();
        for (IWorkerHook hook : getDeserializedWorkerHooks()) {
            hook.start(topologyConf, workerContext);
        }
    }

    public void runWorkerShutdownHooks() {
        for (IWorkerHook hook : getDeserializedWorkerHooks()) {
            hook.shutdown();
        }
    }

    public void closeResources() {
        LOG.info("Shutting down default resources");
        ((ExecutorService) defaultSharedResources.get(WorkerTopologyContext.SHARED_EXECUTOR)).shutdownNow();
        LOG.info("Shut down default resources");
    }

    public boolean areAllConnectionsReady() {
        return cachedNodeToPortSocket.get().values()
                                     .stream()
                                     .map(WorkerState::isConnectionReady)
                                     .reduce((left, right) -> left && right)
                                     .orElse(true);
    }

    public Collection<IAutoCredentials> getAutoCredentials() {
        return this.autoCredentials;
    }

    private List<List<Long>> readWorkerExecutors(IStormClusterState stormClusterState, String topologyId, String assignmentId,
                                                 int port) {
        LOG.info("Reading assignments");
        List<List<Long>> executorsAssignedToThisWorker = new ArrayList<>();
        executorsAssignedToThisWorker.add(Constants.SYSTEM_EXECUTOR_ID);
        Map<List<Long>, NodeInfo> executorToNodePort =
            getLocalAssignment(stormClusterState, topologyId).get_executor_node_port();
        for (Map.Entry<List<Long>, NodeInfo> entry : executorToNodePort.entrySet()) {
            NodeInfo nodeInfo = entry.getValue();
            if (nodeInfo.get_node().equals(assignmentId) && nodeInfo.get_port().iterator().next() == port) {
                executorsAssignedToThisWorker.add(entry.getKey());
            }
        }
        return executorsAssignedToThisWorker;
    }

    private Assignment getLocalAssignment(IStormClusterState stormClusterState, String topologyId) {
        try (SupervisorIfaceFactory fac = supervisorIfaceSupplier.get()) {
            return fac.getIface().getLocalAssignmentForStorm(topologyId);
        } catch (Throwable e) {
            //if any error/exception thrown, fetch it from zookeeper
            Assignment assignment = stormClusterState.remoteAssignmentInfo(topologyId, null);
            if (assignment == null) {
                throw new RuntimeException("Failed to read worker assignment."
                    + " Supervisor client threw exception, and assignment in Zookeeper was null", e);
            }
            return assignment;
        }
    }

    private Map<List<Long>, JCQueue> mkReceiveQueueMap(Map<String, Object> topologyConf, Set<List<Long>> executors) {
        Integer recvQueueSize = ObjectReader.getInt(topologyConf.get(Config.TOPOLOGY_EXECUTOR_RECEIVE_BUFFER_SIZE));
        Integer recvBatchSize = ObjectReader.getInt(topologyConf.get(Config.TOPOLOGY_PRODUCER_BATCH_SIZE));
        Integer overflowLimit = ObjectReader.getInt(topologyConf.get(Config.TOPOLOGY_EXECUTOR_OVERFLOW_LIMIT));

        if (recvBatchSize > recvQueueSize / 2) {
            throw new IllegalArgumentException(Config.TOPOLOGY_PRODUCER_BATCH_SIZE + ":" + recvBatchSize
                    + " is greater than half of " + Config.TOPOLOGY_EXECUTOR_RECEIVE_BUFFER_SIZE + ":"
                    + recvQueueSize);
        }

        IWaitStrategy backPressureWaitStrategy = IWaitStrategy.createBackPressureWaitStrategy(topologyConf);
        Map<List<Long>, JCQueue> receiveQueueMap = new HashMap<>();
        for (List<Long> executor : executors) {
            int port = this.getPort();
            receiveQueueMap.put(executor, new JCQueue("receive-queue" + executor.toString(),
                                                      recvQueueSize, overflowLimit, recvBatchSize, backPressureWaitStrategy,
                this.getTopologyId(), Constants.SYSTEM_COMPONENT_ID, -1, this.getPort(), metricRegistry));

        }
        return receiveQueueMap;
    }

    private Map<String, Object> makeDefaultResources() {
        int threadPoolSize = ObjectReader.getInt(conf.get(Config.TOPOLOGY_WORKER_SHARED_THREAD_POOL_SIZE));
        return ImmutableMap.of(WorkerTopologyContext.SHARED_EXECUTOR, Executors.newFixedThreadPool(threadPoolSize));
    }

    private Map<String, Object> makeUserResources() {
        /* TODO: need to invoke a hook provided by the topology, giving it a chance to create user resources.
         * this would be part of the initialization hook
         * need to separate workertopologycontext into WorkerContext and WorkerUserContext.
         * actually just do it via interfaces. just need to make sure to hide setResource from tasks
         */
        return new HashMap<>();
    }

    private StormTimer mkHaltingTimer(String name) {
        return new StormTimer(name, (thread, exception) -> {
            LOG.error("Error when processing event", exception);
            Utils.exitProcess(20, "Error when processing an event");
        });
    }

    /**
     * Get worker outbound tasks.
     * @return seq of task ids that receive messages from this worker
     */
    private Set<Integer> workerOutboundTasks() {
        WorkerTopologyContext context = getWorkerTopologyContext();
        Set<String> components = new HashSet<>();
        for (Integer taskId : localTaskIds) {
            for (Map<String, Grouping> value : context.getTargets(context.getComponentId(taskId)).values()) {
                components.addAll(value.keySet());
            }
        }

        Set<Integer> outboundTasks = new HashSet<>();

        for (Map.Entry<String, List<Integer>> entry : Utils.reverseMap(taskToComponent).entrySet()) {
            if (components.contains(entry.getKey())) {
                outboundTasks.addAll(entry.getValue());
            }
        }
        return outboundTasks;
    }

    public Set<Integer> getOutboundTasks() {
        return this.outboundTasks;
    }

    /**
     * Check if this worker has remote outbound tasks.
     * @return true if this worker has remote outbound tasks; false otherwise.
     */
    public boolean hasRemoteOutboundTasks() {
        Set<Integer> remoteTasks = Sets.difference(new HashSet<>(outboundTasks), new HashSet<>(localTaskIds));
        return !remoteTasks.isEmpty();
    }

    /**
     * If all the tasks are local tasks, the topology has only one worker.
     * @return true if this worker is the single worker; false otherwise.
     */
    public boolean isSingleWorker() {
        Set<Integer> nonLocalTasks = Sets.difference(getTaskToComponent().keySet(),
                new HashSet<>(localTaskIds));
        return nonLocalTasks.isEmpty();
    }

    public void haltWorkerTransfer() {
        workerTransfer.haltTransferThd();
    }

    public JCQueue getTransferQueue() {
        return workerTransfer.getTransferQueue();
    }

    public StormMetricRegistry getMetricRegistry() {
        return metricRegistry;
    }

    public interface ILocalTransferCallback {
        void transfer(ArrayList<AddressedTuple> tupleBatch);
    }
}


text:
namespace aliyun {
struct RdsCreateDatabaseRequestType {
  std::string owner_id;
  std::string resource_owner_account;
  std::string resource_owner_id;
  std::string db_instance_id;
  std::string db_name;
  std::string character_set_name;
  std::string db_description;
  std::string owner_account;
};
struct RdsCreateDatabaseResponseType {
};
} // end namespace
#endif

redpajama_set_name: RedPajamaGithub


text:
/**
* Package for calculate task.
*
* @author Roman Shmelev (mailto:roman.shmelev@gmail.com)
* @version $Id$
* @since 0.1
*/
package ru.job4j.web;


text:
<?php

declare(strict_types=1);

namespace Symplify\ChangelogLinker\ChangeTree;

use Nette\Utils\Strings;
use Symplify\ChangelogLinker\Regex\RegexPattern;

final class ChangeResolver
{
    /**
     * @var ChangeFactory
     */
    private $changeFactory;

    /**
     * @var ChangeSorter
     */
    private $changeSorter;

    public function __construct(ChangeFactory $changeFactory, ChangeSorter $changeSorter)
    {
        $this->changeFactory = $changeFactory;
        $this->changeSorter = $changeSorter;
    }

    /**
     * @param mixed[] $pullRequests
     * @return Change[]
     */
    public function resolveSortedChangesFromPullRequestsWithSortPriority(
        array $pullRequests,
        ?string $sortPriority
    ): array {
        $changes = [];

        foreach ($pullRequests as $pullRequest) {
            $changes[] = $this->changeFactory->createFromPullRequest($pullRequest);
        }

        $changes = $this->filterOutUselessChanges($changes);

        return $this->changeSorter->sort($changes, $sortPriority);
    }

    /**
     * @param Change[] $changes
     * @return Change[]
     */
    private function filterOutUselessChanges(array $changes): array
    {
        return array_filter($changes, function (Change $change): bool {
            // skip new/fixed tests
            return ! Strings::match($change->getMessage(), RegexPattern::TEST_TITLE);
        });
    }
}


text:
source ./sh/steps/_setup.sh

setup

unset -f _step_setup_plugin setup

. ./sh/steps/_execute.sh


text:
@class NSManagedObjectContext;

@interface BookmarksManager : NSObject
{
    NSManagedObjectContext *_managedObjectContext;
}

+ (void)initialize;
+ (id)_sharedPersistentStoreCoordinator;
+ (id)_newManagedObjectModel;
- (id)init;
- (void)dealloc;
- (void)_configureTransientFeedContext;
- (void)addAllRSSFeedsIfNecessary;
- (id)subscribedFeeds;
- (unsigned long long)countOfSafariFeeds;
- (unsigned long long)countOfSubscribedFeeds;
- (void)saveTransientFeedChanges;
- (void)discardTransientFeedChanges;
- (BOOL)updateContextWithChanges:(id)arg1;
- (void)clearTransientFeedContext;
- (id)transientFeedContext;
- (void)_setContext:(id)arg1;
- (id)addBookmarkWithId:(id)arg1;
- (id)addFolderWithId:(id)arg1 checkIfExists:(BOOL)arg2;
- (id)bookmarkWithId:(id)arg1;
- (id)folderWithId:(id)arg1;
- (id)addBookmarkWithURL:(id)arg1;
- (id)addSubscribedBookmarkWithURL:(id)arg1 name:(id)arg2;
- (id)bookmarksWithURL:(id)arg1;
- (id)bookmarkURLWithName:(id)arg1;
- (id)_itemsWithValue:(id)arg1 forKey:(id)arg2 entity:(id)arg3;
- (BOOL)setBookmarksWithURL:(id)arg1 isSubscribed:(BOOL)arg2 shouldDisplayUnderInbox:(BOOL)arg3;
- (BOOL)deleteBookmarkWithId:(id)arg1;
- (BOOL)_deleteBookmark:(id)arg1;
- (BOOL)deleteFolderWithId:(id)arg1;
- (BOOL)_deleteFolder:(id)arg1;
- (void)deleteAllBookmarks;
- (void)deleteAllFolders;
- (id)_allItemsForEntity:(id)arg1;

@end


text:
import uuid
from setuptools import setup
try:  # for pip >= 10
    from pip._internal.req import parse_requirements
except ImportError:  # for pip <= 9.0.3
    from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements("requirements.txt", session=uuid.uuid1())

# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']

reqs = [str(ir.req) for ir in install_reqs if ir.req is not None]

setup(
    name='Meerkat Frontend',
    version='0.0.1',
    long_description=__doc__,
    packages=['meerkat_frontend'],
    include_package_data=True,
    zip_safe=False,
    install_requires=reqs,
    test_suite='meerkat_frontend.test'
)


text:
"""
Script for building the example.

Usage:
    python setup.py py2app
"""
from setuptools import setup

plist = dict(NSMainNibFile='PyInterpreter')
setup(
    name="PyInterpreter",
    app=["PyInterpreter.py"],
    data_files=["PyInterpreter.nib"],
    setup_requires=["py2app"],
    options=dict(py2app=dict(plist=plist)),
)


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');

class Jam_Exception_Invalidargument extends Kohana_Jam_Exception_Event {}


text:
function(event, options) {
  return {
    submit_form: options.submit_form
  };
}


text:
jcompass
========

Simple Java wrapper over the Compass CSS Authoring Framework


text:
using namespace bkengine;

TEST_CASE("INISettingsInterface")
{
    std::shared_ptr<SettingsInterface> settings = std::make_shared<INISettingsInterface>();
    settings->init();

    SECTION("loadFromFile")
    {
        std::string fileName = "tmp.settingsinterface.test.1.ini";
        std::ofstream file(fileName);

        if (!file.good()) {
            FAIL("Unable to open temporary file!");
        }

        SECTION("valid content")
        {
            std::string fileContent = "nosection=1234\n"
                                      "key=value\n"
                                      "[section1]\n"
                                      "bkengine=bk\n";
            file << fileContent;
            file.close();
            SECTION("load from existing file")
            {
                settings->loadFromFile(fileName);
                REQUIRE(settings->hasValue("nosection"));
                REQUIRE(settings->hasValue("key"));
                REQUIRE(settings->hasValue("section1.bkengine"));
                REQUIRE(settings->count() == 3);
            }
            SECTION("load from non existent file")
            {
                settings->loadFromFile("non existent file...");
                REQUIRE(settings->count() == 0);
            }
        }

        SECTION("invalid content")
        {
            std::string fileContent = "nosection1234\n"
                                      "key=value\n"
                                      "[section1\n"
                                      "bkengine=bk\n";
            file << fileContent;
            file.close();

            settings->loadFromFile(fileName);
            REQUIRE(settings->hasValue("key"));
            REQUIRE(settings->hasValue("bkengine"));
            REQUIRE(settings->count() == 2);
        }

        std::remove(fileName.c_str());
    }

    SECTION("create")
    {
        SECTION("key without dot")
        {
            REQUIRE(settings->count() == 0);
            settings->create("nosection", "value");
            REQUIRE(settings->get("nosection") == "value");
            REQUIRE(settings->count() == 1);
        }
        SECTION("key with 1 dot")
        {
            REQUIRE(settings->count() == 0);
            settings->create("section.key", "value");
            REQUIRE(settings->get("section.key") == "value");
            REQUIRE(settings->count() == 1);
        }
        SECTION("key with 2 dot")
        {
            REQUIRE(settings->count() == 0);
            settings->create("section.key.level2", "value");
            REQUIRE(settings->get("section.key.level2") == "value");
            REQUIRE(settings->count() == 1);
        }
        SECTION("empty value")
        {
            REQUIRE(settings->count() == 0);
            settings->create("section.key.level2", "");
            REQUIRE(settings->count() == 1);
        }
        SECTION("already existing key")
        {
            REQUIRE(settings->count() == 0);
            settings->create("section.key.level2", "value");
            REQUIRE(settings->get("section.key.level2") == "value");
            REQUIRE(settings->count() == 1);
            settings->create("section.key.level2", "value2");
            REQUIRE(settings->get("section.key.level2") == "value");
            REQUIRE(settings->count() == 1);
        }
    }

    SECTION("saveToFile")
    {
        std::string fileName = "tmp.settingsinterface.test.3.ini";
        SECTION("save and load back")
        {
            settings->create("nosection", "value1");
            settings->create("section.key1", "bkengine");
            settings->create("section2.testKey.nestedkey", "testvalue");
            settings->saveToFile(fileName);
            REQUIRE(settings->count() == 3);
            settings->create("extrakey", "0");
            REQUIRE(settings->count() == 4);
            settings->loadFromFile(fileName);
            REQUIRE(settings->count() == 3);
            REQUIRE(settings->get("nosection") == "value1");
            REQUIRE(settings->get("section.key1") == "bkengine");
            REQUIRE(settings->get("section2.testKey.nestedkey") == "testvalue");
        }
        SECTION("save to already opened file")
        {
            // TODO: reproduce a failing file opening?
        }
        std::remove(fileName.c_str());
    }

    SECTION("get")
    {
        SECTION("key without section")
        {
            settings->create("nosection", "1234");
            REQUIRE(settings->get("nosection") == "1234");
        }
        SECTION("key with section")
        {
            settings->create("testsection.testkey", "4321");
            REQUIRE(settings->get("testsection.testkey") == "4321");
        }
        SECTION("key with section and dot in it")
        {
            settings->create("testsection.testkey.name", "name");
            REQUIRE(settings->get("testsection.testkey.name") == "name");
        }
        SECTION("key without section which does not exist")
        {
            std::string errorCase = "";
            REQUIRE(settings->count() == 0);
            REQUIRE(settings->get("sec") == errorCase);
        }
        SECTION("key with section which does not exist")
        {
            std::string errorCase = "";
            REQUIRE(settings->count() == 0);
            REQUIRE(settings->get("key1.sec") == errorCase);
        }
    }

    SECTION("remove")
    {
        SECTION("key without section")
        {
            settings->create("nosection", "1234");
            REQUIRE(settings->count() == 1);
            REQUIRE(settings->remove("nosection") == "1234");
            REQUIRE(settings->count() == 0);
        }
        SECTION("key with section")
        {
            settings->create("section.key1", "2424");
            REQUIRE(settings->count() == 1);
            REQUIRE(settings->remove("section.key1") == "2424");
            REQUIRE(settings->count() == 0);
        }
        SECTION("key with section and dot in it")
        {
            settings->create("section.key1.dot", "4242");
            REQUIRE(settings->count() == 1);
            REQUIRE(settings->remove("section.key1.dot") == "4242");
            REQUIRE(settings->count() == 0);
        }
        SECTION("key without section which does not exist")
        {
            std::string errorCase = "";
            REQUIRE(settings->count() == 0);
            REQUIRE(settings->remove("sec") == errorCase);
        }
        SECTION("key with section which does not exist")
        {
            std::string errorCase = "";
            REQUIRE(settings->count() == 0);
            REQUIRE(settings->remove("key1.sec") == errorCase);
        }
    }

    SECTION("hasValue")
    {
        SECTION("key without section")
        {
            settings->create("nosection", "1234");
            REQUIRE(settings->hasValue("nosection"));
        }
        SECTION("key with section")
        {
            settings->create("testsection.testkey", "4321");
            REQUIRE(settings->hasValue("testsection.testkey"));
        }
        SECTION("key with section and dot in it")
        {
            settings->create("testsection.testkey.name", "name");
            REQUIRE(settings->hasValue("testsection.testkey.name"));
        }
        SECTION("key without section which does not exist")
        {
            settings->create("sec.key", "123");
            REQUIRE_FALSE(settings->hasValue("sec"));
        }
        SECTION("key with section which does not exist")
        {
            settings->create("key1", "0");
            REQUIRE_FALSE(settings->hasValue("key1.sec"));
        }
    }

    SECTION("change")
    {
        SECTION("key without section")
        {
            settings->create("nosection", "1234");
            REQUIRE(settings->get("nosection") == "1234");
            settings->change("nosection", "4321");
            REQUIRE(settings->get("nosection") == "4321");
            REQUIRE(settings->count() == 1);
        }
        SECTION("key with section")
        {
            settings->create("testsection.testkey", "1234");
            REQUIRE(settings->get("testsection.testkey") == "1234");
            settings->change("testsection.testkey", "4321");
            REQUIRE(settings->get("testsection.testkey") == "4321");
            REQUIRE(settings->count() == 1);
        }
        SECTION("key with section and dot in it")
        {
            settings->create("testsection.testkey.name", "name");
            REQUIRE(settings->get("testsection.testkey.name") == "name");
            settings->change("testsection.testkey.name", "54779");
            REQUIRE(settings->get("testsection.testkey.name") == "54779");
            REQUIRE(settings->count() == 1);
        }
        SECTION("key without section which does not exist")
        {
            settings->change("sec", "123");
            REQUIRE_FALSE(settings->hasValue("sec"));
        }
        SECTION("key with section which does not exist")
        {
            settings->change("key", "0");
            REQUIRE_FALSE(settings->hasValue("key.sec"));
        }
    }

    SECTION("count")
    {
        SECTION("key without section")
        {
            REQUIRE(settings->count() == 0);
            settings->create("nosection", "1234");
            REQUIRE(settings->count() == 1);
        }
        SECTION("key with section")
        {
            REQUIRE(settings->count() == 0);
            settings->create("nosection.section", "1234");
            REQUIRE(settings->count() == 1);
        }
        SECTION("key with section and dot in it")
        {
            REQUIRE(settings->count() == 0);
            settings->create("nosection.section.key", "1234");
            REQUIRE(settings->count() == 1);
        }
        SECTION("more complex construct")
        {
            settings->create("sec", "123");
            settings->create("sec.key1", "123");
            settings->create("sec.key2", "123");
            settings->create("s", "123");
            settings->create("se.key1", "123");
            REQUIRE(settings->count() == 5);
        }
    }
}


text:
using System.Xml.Serialization;
using StayWell.Interface;

namespace StayWell.ServiceDefinitions.ServiceLines.Objects
{
	[XmlRoot("ServiceLineHierchy")]
	public class ServiceLineHierarchy : ResultList<ServiceLineHierarchyItem>
	{
	}
}


text:
<!doctype html>
<!-- This file is generated by build.py. -->
<title>embed wide.jpg; overflow:hidden; -o-object-fit:cover; -o-object-position:center center</title>
<link rel="stylesheet" href="../../support/reftests.css">
<link rel='match' href='hidden_cover_bottom_bottom-ref.html'>
<style>
 #test > * { overflow:hidden; -o-object-fit:cover; -o-object-position:center center }
</style>
<div id="test">
 <embed src="../../support/wide.jpg">
</div>


text:
module CurrencyCloud
  class ConversionProfitAndLoss
    include CurrencyCloud::Resource
  end
end


text:
VALUE Structural = Qnil;
void Init_structural();

VALUE Stack = Qnil;
VALUE Queue = Qnil;

void Init_structural() {
  Structural = rb_define_module("Structural");

  Stack = rb_define_class_under(Structural, "Stack", rb_cObject);
  rb_define_method(Stack, "initialize", stack_initialize, 0);
  rb_define_method(Stack, "top", stack_top, 0);
  rb_define_method(Stack, "push", stack_push, 1);
  rb_define_method(Stack, "pop", stack_pop, 0);
  rb_define_method(Stack, "empty?", stack_empty, 0);

  Queue = rb_define_class_under(Structural, "Queue", rb_cObject);
  rb_define_method(Queue, "initialize", queue_initialize, 0);
  rb_define_method(Queue, "enqueue", queue_enqueue, 1);
  rb_define_method(Queue, "dequeue", queue_dequeue, 0);
  rb_define_method(Queue, "peek", queue_peek, 0);
  rb_define_method(Queue, "empty?", queue_empty, 0);
}


text:
FactoryGirl.define do
  factory :label, class: ProjectLabel do
    sequence(:title) { |n| "label#{n}" }
    color "#990000"
    project

    transient do
      priority nil
    end

    after(:create) do |label, evaluator|
      if evaluator.priority
        label.priorities.create(project: label.project, priority: evaluator.priority)
      end
    end
  end

  factory :group_label, class: GroupLabel do
    sequence(:title) { |n| "label#{n}" }
    color "#990000"
    group
  end
end


text:
  Viverols est
       un village
       géographiquement positionné dans le département de Puy-de-Dôme en Auvergne. Elle totalisait 390 habitants en 2008.

La ville offre de multiples  équipements, elle propose entre autres un terrain de tennis, un terrain de sport et trois boucles de randonnée.

À proximité de Viverols sont positionnées géographiquement les communes de
La Chaulme localisée à 5 km, 132 habitants,
Saint-Clément-de-Valorgue localisée à 7 km, 221 habitants,
Saillant à 3 km, 274 habitants,
Baffie localisée à 5 km, 115 habitants,
Églisolles à 2 km, 246 habitants,
Saint-Romain située à 6 km, 215 habitants,
 entre autres. De plus, Viverols est située à seulement 23 km de Montbrison.

Le parc d'habitations, à Viverols, se décomposait en 2011 en 31 appartements et 349 maisons soit
 un marché relativement équilibré.

Si vous envisagez de demenager à Viverols, vous pourrez facilement trouver une maison à acheter.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>NetworkReceiver</title>
<meta name="date" content="2017-03-29">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.example.moodmobile

Class NetworkReceiver

java.lang.Object

android.content.BroadcastReceiver

android.support.v4.content.WakefulBroadcastReceiver

com.example.moodmobile.NetworkReceiver

public class NetworkReceiver
extends android.support.v4.content.WakefulBroadcastReceiver

Created by zindi on 3/16/17.

Nested Class Summary

Nested classes/interfaces inherited from class android.content.BroadcastReceiver

android.content.BroadcastReceiver.PendingResult

Constructor Summary

Constructors

Constructor and Description

NetworkReceiver()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
onReceive(android.content.Context context,
         android.content.Intent intent)

Methods inherited from class android.support.v4.content.WakefulBroadcastReceiver

completeWakefulIntent, startWakefulService

Methods inherited from class android.content.BroadcastReceiver

abortBroadcast, clearAbortBroadcast, getAbortBroadcast, getDebugUnregister, getResultCode, getResultData, getResultExtras, goAsync, isInitialStickyBroadcast, isOrderedBroadcast, peekService, setDebugUnregister, setOrderedHint, setResult, setResultCode, setResultData, setResultExtras

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NetworkReceiver

public NetworkReceiver()

Method Detail

onReceive

public void onReceive(android.content.Context context,
                      android.content.Intent intent)

Specified by:

onReceive in class android.content.BroadcastReceiver

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
"""NLTK Command Line Interface - Stanford API

Usage:
  stanford.py --tool=postagger --jar FILE --model PATH --input FILE [--output NONE]
  stanford.py --tool=neragger --jar FILE --model PATH --input FILE  [--output NONE]
  stanford.py --tool=lexparser --jar FILE --modeljar FILE --model PATH --input FILE [--output NONE]
  stanford.py (-h | --help)
  stanford.py --version

  stanford.py --postag FILE [--lang LANG] [--output NONE]
  stanford.py --lexparse FILE [--lang LANG] [--output NONE]
  stanford.py --nertag FILE [--lang LANG] [--output NONE]

  stanford.py --postag FILE [--model PATH] [--output NONE]
  stanford.py --lexparse FILE [--model PATH] [--output NONE]
  stanford.py --nertag FILE [--model LANG] [--output NONE]

Options:
  -h --help     Show this screen.
  --tool		Tagger/Parser option (i.e. 'lexparser', 'postagger', etc.)
  --jar			Path to jar file (Complusory)
  --model		Path to model name (Complusory).
  --modeljar	Path to model jar file (Only use with Stanford parsers).
  --input		Path to input file.
  --output		Path to output file [default: None].
  --postag      TL;DR, "I just want to POS tag this file" [default: eng].
  --nertag      TL;DR, "I just want to NER tag this file" (only English).
  --lexparse    TL;DR, "I just want to parse this file" [default: eng].
  --lang		The language option for TL;DR options [default: eng].
"""

from __future__ import print_function
import io
import os
import re

from nltk.tag.stanford import StanfordPOSTagger, StanfordNERTagger
from nltk.parse.stanford import StanfordParser
#from nltk.parse.stanford import StanfordDependencyParser
#from nltk.parse.stanford import StanfordNeuralDependencyParser

from docopt import docopt

taggers = {
'postagger': StanfordPOSTagger,
'nertagger':StanfordNERTagger
}

parsers = {
'lexparser':StanfordParser,
#'depparser':StanfordDependencyParser, # Not coded yet.
#'neuralparser':StanfordNeuralDependencyParser # Not coded yet.
}

lexparser_languages = {
# Arabic
'ara': ['arabicFactored.ser.gz'],
# Chinese
'cmn': ['chinesePCFG.ser.gz', 'chineseFactored.ser.gz',
'xinhuaPCFG.ser.gz', 'xinhuaFactored.ser.gz', 'xinhuaFactoredSegmenting.ser.gz'],
# German
'deu':['germanPCFG.ser.gz', 'germanFactored.ser.gz'],
# English
'eng': ['englishRNN.ser.gz', 'englishPCFG.ser.gz',
'englishFactored.ser.gz', 'englishPCFG.caseless.ser.gz', 'wsjPCFG.ser.gz',
'wsjRNN.ser.gz', 'wsjFactored.ser.gz'],
# French
'fre': ['frenchFactored.ser.gz'],
# Spanish
'spa': ['spanishPCFG.ser.gz']}

postagger_languages = {
# Arabic
'ara': ['arabic.tagger'],
# Chinese
'cmn': ['chinese-distsim.tagger', 'chinese-nodistsim.tagger'],
# English
'eng': ['english-bidirectional-distsim.tagger',
'english-caseless-left3words-distsim.tagger',
'english-left3words-distsim.tagger', 'wsj-0-18-bidirectional-distsim.tagger',
'wsj-0-18-bidirectional-nodistsim.tagger',
'wsj-0-18-caseless-left3words-distsim.tagger',
'wsj-0-18-left3words-distsim.tagger', 'wsj-0-18-left3words-nodistsim.tagger'],
# French
'fre': ['french.tagger'],
# German
'deu': ['german-dewac.tagger', 'german-fast-caseless.tagger',
'german-fast.tagger', 'german-hgc.tagger'],
# Spanish
'spa': ['spanish-distsim.tagger', 'spanish.tagger']
}

nertagger_languages = {
# Chinese
'cmn': ['chinese.misc.distsim.crf.ser.gz'],
# German
'deu': ['german.dewac_175m_600.crf.ser.gz', 'german.hgc_175m_600.crf.ser.gz'],
# English
'eng': ['english.all.3class.distsim.crf.ser.gz', 'english.conll.4class.distsim.crf.ser.gz',
'english.muc.7class.distsim.crf.ser.gz', 'example.serialized.ncc.ncc.ser.gz'],
# Spansih
'spa': ['spanish.ancora.distsim.s512.crf.ser.gz']
}

def stanford_tag_sents(sentences, tagger):
	tagged_sents = tagger.tag_sents(sentences)
	for sent in tagged_sents:
		yield " ".join(word + '#' + pos for word, pos in sent)

def stanford_parse_sents(sentences, parser):
	parsed_sents = sum([list(i) for i in parser.parse_sents(sentences)], [])
	return [re.sub(' +',' ', str(sent).replace('\n', '')) for sent in parsed_sents]

def initialize_tool(arguments):
	"""
	To initalize the Stanford tools given the users arguments from command line.
	"""
	tool_name = arguments['--tool']
	if tool_name in taggers:
		tagger = taggers[tool_name](model_filename=arguments['--model'], path_to_jar=arguments['--jar'])
		return tagger, stanford_tag_sents
	elif tool_name in parsers:
		parser = parsers[tool_name](model_path=arguments['--model'], path_to_models_jar=arguments['--modeljar'], path_to_jar=arguments['--jar'])
		return parser, stanford_parse_sents

def initialize_iofiles(arugments):
	infile, outfile = "", ""
	if arguments['FILE']:
		infile = arguments['FILE']
	elif arguments['--input']:
		infile = arguments['--input']
	if arugments['--output']:
		outfile = arugments['--output']
	return infile, outfile

def augment_arugments(arguments):
	homedir = os.path.expanduser("~")
	# Augment arugments for LexParser.
	if '--lexparse' in arguments.keys() and arguments['--lexparse']:
		arguments['--tool']	= 'lexparser'
		arguments['--jar']	= homedir +'/stanford-parser/stanford-parser.jar'
		arguments['--modeljar']	= homedir +'/stanford-parser/stanford-parser-3.5.2-models.jar'
		if arguments['--model'] is None:
			if arguments['--lang'] == None:
				arguments['--model'] = 'edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz'
			else:
				arguments['--model'] = 'edu/stanford/nlp/models/lexparser/'
				arguments['--model']+= lexparser_languages[arguments['--lang']][0]
	# Augment arugments for POSTagger.
	elif '--postag' in arguments.keys() and arguments['--postag']:
		arguments['--tool']	= 'postagger'
		arguments['--jar']	= homedir +'/stanford-postagger/stanford-postagger.jar'
		if arguments['--model'] is None:
			if arguments['--lang'] == None:
				arguments['--model'] = homedir + '/stanford-postagger/models/english-bidirectional-distsim.tagger'
			else:
				arguments['--model'] =  homedir + '/stanford-postagger/models/'
				arguments['--model']+= postagger_languages[arguments['--lang']][0]
	# Augment arugments for NERTagger.
	elif '--nertag' in arguments.keys() and arguments['--nertag']:
		arguments['--tool']	= 'nertagger'
		arguments['--jar']	= homedir +'/stanford-ner/stanford-ner.jar'
		if arguments['--model'] is None:
			if arguments['--lang'] == None:
				arguments['--model'] = homedir + '/stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz'
			else:
				arguments['--model'] =  homedir + '/stanford-ner/classifiers/'
				arguments['--model']+= nertagger_languages[arguments['--lang']][0]

if __name__ == '__main__':
	arguments = docopt(__doc__, version='NLTK CLI (Stanford Tools) version 0.0.1')
	# Augment arguments for TL;DR commands.
	if arguments['--tool'] is None:
		augment_arugments(arguments)

	tool, process = initialize_tool(arguments)
	infile, outfile = initialize_iofiles(arguments)
	if outfile:
		fout = io.open(outfile, 'w', encoding='utf8')
	with io.open(infile, 'r', encoding='utf8') as fin:
		sentences = [line.strip().split() for line in fin]
		for processed_sent in process(sentences, tool):
			if outfile:
				fout.write(processed_sent + '\n')
			else:
				print(processed_sent)


text:
<?php
	//insertStaticChampionData.php
	include ('conection.php');
	$query = "TRUNCATE TABLE masteriesdescriptions; TRUNCATE TABLE masteries;";
	$execute = mysqli_multi_query($conection, $query);
?>


text:
namespace ICARTT_Merge_Configuration.GUI
{
    partial class ProcessControl
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        protected System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.processLabel = new System.Windows.Forms.Label();
            this.controlsPanel = new System.Windows.Forms.Panel();
            this.SuspendLayout();
            //
            // processLabel
            //
            this.processLabel.AutoSize = true;
            this.processLabel.BackColor = System.Drawing.SystemColors.Control;
            this.processLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 15F);
            this.processLabel.Location = new System.Drawing.Point(-5, 0);
            this.processLabel.Name = "processLabel";
            this.processLabel.Size = new System.Drawing.Size(167, 25);
            this.processLabel.TabIndex = 0;
            this.processLabel.Text = "GENERIC LABEL";
            //
            // controlsPanel
            //
            this.controlsPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.controlsPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.controlsPanel.BackColor = System.Drawing.SystemColors.ControlDark;
            this.controlsPanel.Location = new System.Drawing.Point(0, 28);
            this.controlsPanel.Name = "controlsPanel";
            this.controlsPanel.Size = new System.Drawing.Size(319, 357);
            this.controlsPanel.TabIndex = 1;
            //
            // ProcessControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.controlsPanel);
            this.Controls.Add(this.processLabel);
            this.Name = "ProcessControl";
            this.Size = new System.Drawing.Size(319, 385);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        protected System.Windows.Forms.Label processLabel;
        protected System.Windows.Forms.Panel controlsPanel;
    }
}


text:
int errno;
int _doserrno;
int _sys_nerr;

char* error_desc_buff = NULL;

char* strerror(int errno)
{
	if (NULL != error_desc_buff)
	{
		LocalFree(error_desc_buff);
		error_desc_buff = NULL;
	}

	FormatMessage(
		FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
		NULL,
		errno,
		0,
		(LPTSTR)&error_desc_buff,
		1024,
		NULL
	);
	return error_desc_buff;
}

#endif


text:
import React, {Component} from 'react';
import {Text, View} from 'react-native';

import TabNavigator from 'react-native-tab-navigator';

export default class TestPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedTab: 'home'
        };
    }

    render() {
        return (
            <View style={{
                flex: 1,
                backgroundColor: '#eee',
                justifyContent: 'center'
            }}>
                <Text style={{
                    fontSize: 20,
                    color: '#f00'
                }}>我是TestPage,导入使用的!</Text>
            </View>
        );
    }
};


text:
Tweets by CoderDojoNGTD

    {% if site.data.ui-text[site.locale].follow_label %}

{{ site.data.ui-text[site.locale].follow_label }}

    {% endif %}
    {% if site.twitter.username %}

 Twitter

    {% endif %}
    {% if site.facebook.username %}

 Facebook

    {% endif %}
    {% if site.author.github %}

 GitHub

    {% endif %}
    {% if site.author.bitbucket %}

 Bitbucket

    {% endif %}

 {{ site.data.ui-text[site.locale].feed_label | default: "Feed" }}

© {{ site.time | date: '%Y' }} {{ site.name | default: site.title }}. {{ site.data.ui-text[site.locale].powered_by | default: "Powered by" }} Jekyll & Minimal Mistakes.


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1">
        <meta name="robots" content="noindex, nofollow">
        <meta name="description" content="Mathieu Davy's one man web studio">
        <meta name="author" content="Mathieu Davy">
        <link rel="alternate" type="application/rss+xml" title="Ekynoxe - Web development in London" href="http://www.ekynoxe.com/rss.xml">

        <meta name="viewport" content="width=device-width,initial-scale=1">

        <title>Orange Social Life is a winner - Ekynoxe - Web development in London</title>
        <link href="/assets/css/global.css" rel="stylesheet" type="text/css">

        <link rel="shortcut icon" href="/assets/img/style/favicon.ico">

        <link rel="apple-touch-icon-precomposed" sizes="152x152" href="/assets/img/style/apple-touch-icon-152x152-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/assets/img/style/apple-touch-icon-144x144-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="120x120" href="/assets/img/style/apple-touch-icon-120x120-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/assets/img/style/apple-touch-icon-114x114-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="76x76" href="/assets/img/style/apple-touch-icon-76x76-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/assets/img/style/apple-touch-icon-72x72-precomposed.png">
        <link rel="apple-touch-icon-precomposed" href="/assets/img/style/apple-touch-icon-precomposed.png">

HOME

                <time datetime="2010-03-31">March 31, 2010</time>

Orange Social Life is a winner

On March 18 2010, Orange Social Life won the mobile news award of the most innovative service
social_life_web_r500

Launched in August 2009, Social Life has consistently attracted customers and offers a wide range of social networks integration.

Having worked on it since it’s very very early stages, it feels great to look at it and feel proud that we all made it!
I remember the day when my boss came around and asked my availabilities for ‘the months to come’ =)

These months started by creating an HTML and JavaScript mobile prototype to be demonstrated around the business units. It already has live update of a twitter feed and notifications.

The interface was going to be really different from anything that had been done so far, promoting social activity through some cleverly expanding friends icons on the home screen depending on their amount of activity, easy access to communication functions directly from there, and deep integration of the social networks in the usual device capabilities.

Things have slightly changed since then, but the concept is the same, and it works!
The whole service sits on top of a pretty big architecture to allow integration through a single access point into all the required social networks. We’ve worked together countless hours into the specifications of this API, the integration with Orange’s partners, developers, manufacturers and vendors, done quite a few business trips around Europe to finally bring it all together!

Now, it’s been rewarded for it’s simplicity over some bigger players in the market and from the point where I stand in R&D, for most of my work to be hidden from the outside world, I am exstatic to see that what we do in R&D (along with Snapshot) is real stuff that makes it out.

Happy about my second award in the month =)

    previous

     next

Comments are disabled temporarily until I find a suitable system, but you can still send a comment by email and I'll add it to this post. Thanks!

twitter

linkedin

            ekynoxe - Mathieu Davy 2019

    top


text:
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts, FlexibleInstances,
        TypeFamilies, ScopedTypeVariables, GADTs #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module     : Data.Matrix.Banded.IOBase
-- Copyright  : Copyright (c) , Patrick Perry <patperry@stanford.edu>
-- License    : BSD3
-- Maintainer : Patrick Perry <patperry@stanford.edu>
-- Stability  : experimental
--

module Data.Matrix.Banded.IOBase
    where

import Data.Ix
import Data.List
import Control.Monad
import Foreign
import System.IO.Unsafe
import Text.Printf

import BLAS.Internal( clearArray, diagLen, diagStart )
import Data.Elem.BLAS.Base( Elem, conjugate )
import qualified Data.Elem.BLAS.Base   as BLAS
import Data.Elem.BLAS.Level2( BLAS2 )
import qualified Data.Elem.BLAS.Level2 as BLAS

import Data.Matrix.Class
import Data.Matrix.Class.MMatrixBase
import Data.Matrix.Class.MSolveBase

import Data.Matrix.Herm
import Data.Matrix.Tri

import Data.Tensor.Class
import Data.Tensor.Class.MTensor

import Data.Matrix.Dense.IOBase( IOMatrix(..) )
import Data.Matrix.Dense.Base( ReadMatrix, WriteMatrix,
    newCopyMatrix, colViews, scaleByMatrix, unsafeCopyMatrix,
    unsafeAxpyMatrix, unsafeMatrixToIOMatrix )
import Data.Vector.Dense.IOBase( IOVector(..), withIOVector )
import Data.Vector.Dense.Base( ReadVector, WriteVector, dim,
    stride, conj, conjEnum, unsafeVectorToIOVector, newListVector,
    newCopyVector, scaleByVector,unsafeCopyVector, unsafeAxpyVector,
    unsafeConvertIOVector, unsafePerformIOWithVector )

-- | Banded matrix in the 'IO' monad.  The type arguments are as follows:
--
--     * @e@: the element type of the matrix.  Only certain element types
--       are supported.
--
data IOBanded e =
       Elem e =>
       IOBanded { transEnumIOBanded :: {-# UNPACK #-} !TransEnum
                , numRowsIOBanded   :: {-# UNPACK #-} !Int
                , numColsIOBanded   :: {-# UNPACK #-} !Int
                , numLowerIOBanded  :: {-# UNPACK #-} !Int
                , numUpperIOBanded  :: {-# UNPACK #-} !Int
                , fptrIOBanded      :: {-# UNPACK #-} !(ForeignPtr e)
                , ptrIOBanded       :: {-# UNPACK #-} !(Ptr e)
                , ldaIOBanded       :: {-# UNPACK #-} !Int
                }

hermIOBanded :: IOBanded e -> IOBanded e
hermIOBanded (IOBanded h m n kl ku f p l) =
    (IOBanded (flipTrans h) n m ku kl f p l)
{-# INLINE hermIOBanded #-}

isHermIOBanded :: IOBanded e -> Bool
isHermIOBanded = (ConjTrans ==) . transEnumIOBanded
{-# INLINE isHermIOBanded #-}

indexIOBanded :: IOBanded e -> (Int,Int) -> Int
indexIOBanded (IOBanded h _ _ kl ku _ _ ld) (i,j) =
    let (ku',i',j') = if h == ConjTrans then (kl,j,i) else (ku,i,j)
    in ku' + (i' - j') + j' * ld
{-# INLINE indexIOBanded #-}

hasStorageIOBanded :: IOBanded e -> (Int,Int) -> Bool
hasStorageIOBanded (IOBanded h m n kl ku _ _ _) (i,j) =
    let (m',kl',ku',i',j') = if h == ConjTrans
                                 then (n,ku,kl,j,i)
                                 else (m,kl,ku,i,j)
    in inRange (max 0 (j'-ku'), min (m'-1) (j'+kl')) i'
{-# INLINE hasStorageIOBanded #-}

-- | Execute an 'IO' action with a pointer to the first element in the
-- banded matrix.
withIOBanded :: IOBanded e -> (Ptr e -> IO a) -> IO a
withIOBanded (IOBanded _ _ _ _ _ f p _) g = do
    a <- g p
    touchForeignPtr f
    return a
{-# INLINE withIOBanded #-}

withIOBandedElem :: IOBanded e -> (Int,Int) -> (Ptr e -> IO a) -> IO a
withIOBandedElem a@(IOBanded _ _ _ _ _ _ _ _) (i,j) f =
    withIOBanded a $ \p ->
        f $ p `advancePtr` (indexIOBanded a (i,j))
{-# INLINE withIOBandedElem #-}

maybeMatrixStorageFromIOBanded :: IOBanded e -> Maybe (IOMatrix e)
maybeMatrixStorageFromIOBanded (IOBanded h _ n kl ku f p l)
    | h == ConjTrans = Nothing
    | otherwise      = Just $ IOMatrix NoTrans (kl+1+ku) n f p l
{-# INLINE maybeMatrixStorageFromIOBanded #-}

maybeIOBandedFromMatrixStorage :: (Int,Int)
                               -> (Int,Int)
                               -> IOMatrix e
                               -> Maybe (IOBanded e)
maybeIOBandedFromMatrixStorage (m,n) (kl,ku) (IOMatrix h m' n' f p l)
    | m < 0 || n < 0 =
        err "dimensions must be non-negative."
    | kl < 0 =
        err "lower bandwdth must be non-negative."
    | m /= 0 && kl >= m =
        err "lower bandwidth must be less than m."
    | ku < 0 =
        err "upper bandwidth must be non-negative."
    | n /= 0 && ku >= n =
        err "upper bandwidth must be less than n."
    | m' /= kl+1+ku =
        err $ "number of rows in the underlying matrix"
              ++ " must be equal to number of diagonals."
    | n' /= n =
        err $ "numbers of columns must be equal"
            ++ " to the number of columns in the underlying matrix."
    | h == ConjTrans =
        Nothing
    | otherwise =
        Just $ IOBanded NoTrans m n kl ku f p l
  where
    err s =
      error $ "maybeBandedFromMatrixStorage " ++ show (m,n) ++ " " ++ show (kl,ku)
            ++ " <matrix of shape " ++ show (m',n') ++ ">: " ++ show s

viewVectorAsIOBanded :: (Int,Int) -> IOVector e -> IOBanded e
viewVectorAsIOBanded (m,n) (IOVector c k f p l)
    | k /= m && k /= n =
        error $ "viewVectorAsBanded " ++ show (m,n) ++ " "
              ++ " <vector of dim " ++ show k ++ ">: "
              ++ "vector must have length equal to one of the specified"
              ++ " diemsion sizes"
    | otherwise =
        let h = if c == Conj then ConjTrans else NoTrans
        in IOBanded h m n 0 0 f p l
{-# INLINE viewVectorAsIOBanded #-}

maybeViewIOBandedAsVector :: IOBanded e -> Maybe (IOVector e)
maybeViewIOBandedAsVector (IOBanded h m n kl ku f p l)
    | kl == 0 && ku == 0 =
        let c = if h == ConjTrans then Conj else NoConj
        in Just $ IOVector c (min m n) f p l
    | otherwise =
        Nothing
{-# INLINE maybeViewIOBandedAsVector #-}

bandwidthsIOBanded :: IOBanded e -> (Int,Int)
bandwidthsIOBanded a =
    (numLowerIOBanded a, numUpperIOBanded a)
{-# INLINE bandwidthsIOBanded #-}

shapeIOBanded :: IOBanded e -> (Int,Int)
shapeIOBanded a = (numRowsIOBanded a, numColsIOBanded a)
{-# INLINE shapeIOBanded #-}

boundsIOBanded :: IOBanded e -> ((Int,Int), (Int,Int))
boundsIOBanded a = ((0,0), (m-1,n-1)) where (m,n) = shapeIOBanded a
{-# INLINE boundsIOBanded #-}

sizeIOBanded :: IOBanded e -> Int
sizeIOBanded (IOBanded _ m n kl ku _ _ _) =
    foldl' (+) 0 $ map (diagLen (m,n)) [(-kl)..ku]

indicesIOBanded :: IOBanded e -> [(Int,Int)]
indicesIOBanded a =
    let is = if isHermIOBanded a
                 then [ (i,j) | i <- range (0,m-1), j <- range (0,n-1) ]
                 else [ (i,j) | j <- range (0,n-1), i <- range (0,m-1) ]
    in filter (hasStorageIOBanded a) is
  where (m,n) = shapeIOBanded a

getSizeIOBanded :: IOBanded e -> IO Int
getSizeIOBanded = return . sizeIOBanded
{-# INLINE getSizeIOBanded #-}

getIndicesIOBanded :: IOBanded e -> IO [(Int,Int)]
getIndicesIOBanded = return . indicesIOBanded
{-# INLINE getIndicesIOBanded #-}

getIndicesIOBanded' :: IOBanded e -> IO [(Int,Int)]
getIndicesIOBanded' = getIndicesIOBanded
{-# INLINE getIndicesIOBanded' #-}

getAssocsIOBanded :: IOBanded e -> IO [((Int,Int),e)]
getAssocsIOBanded a =
    let go []     = return []
        go (i:is) = unsafeInterleaveIO $ do
                        e   <- unsafeReadElemIOBanded a i
                        ies <- go is
                        return $ (i,e):ies
    in go (indicesIOBanded a)
{-# INLINE getAssocsIOBanded #-}

getAssocsIOBanded' :: IOBanded e -> IO [((Int,Int),e)]
getAssocsIOBanded' a =
    sequence [ liftM ((,) i) (unsafeReadElemIOBanded a i)
             | i <- indicesIOBanded a ]
{-# INLINE getAssocsIOBanded' #-}

getElemsIOBanded :: IOBanded e -> IO [e]
getElemsIOBanded a = liftM (snd . unzip) $ getAssocsIOBanded a
{-# INLINE getElemsIOBanded #-}

getElemsIOBanded' :: IOBanded e -> IO [e]
getElemsIOBanded' a = liftM (snd . unzip) $ getAssocsIOBanded a
{-# INLINE getElemsIOBanded' #-}

unsafeReadElemIOBanded :: IOBanded e -> (Int,Int) -> IO e
unsafeReadElemIOBanded a@(IOBanded _ _ _ _ _ _ _ _) (i,j)
    | hasStorageIOBanded a (i,j) =
        let f = if isHermIOBanded a then conjugate else id
        in liftM f $ withIOBandedElem a (i,j) peek
    | otherwise =
        return 0
{-# INLINE unsafeReadElemIOBanded #-}

unsafeWriteElemIOBanded :: IOBanded e -> (Int,Int) -> e -> IO ()
unsafeWriteElemIOBanded a@(IOBanded _ _ _ _ _ _ _ _) ij e =
    let e' = if isHermIOBanded a then conjugate e else e
    in withIOBandedElem a ij (`poke` e')
{-# INLINE unsafeWriteElemIOBanded #-}

modifyWithIOBanded :: (e -> e) -> IOBanded e -> IO ()
modifyWithIOBanded f a = do
    ies <- getAssocsIOBanded a
    forM_ ies $ \(i,e) -> do
         unsafeWriteElemIOBanded a i (f e)

canModifyElemIOBanded :: IOBanded e -> (Int,Int) -> IO Bool
canModifyElemIOBanded a ij = return $ hasStorageIOBanded a ij
{-# INLINE canModifyElemIOBanded #-}

-- | Create a new banded matrix of given shape and (lower,upper), bandwidths,
-- but do not initialize the elements.
newIOBanded_ :: (Elem e) => (Int,Int) -> (Int,Int) -> IO (IOBanded e)
newIOBanded_ (m,n) (kl,ku)
    | m < 0 || n < 0 =
        err "dimensions must be non-negative."
    | kl < 0 =
        err "lower bandwdth must be non-negative."
    | m /= 0 && kl >= m =
        err "lower bandwidth must be less than m."
    | ku < 0 =
        err "upper bandwidth must be non-negative."
    | n /= 0 && ku >= n =
        err "upper bandwidth must be less than n."
    | otherwise =
        let m'  = kl + 1 + ku
            l   = m'
            h   = NoTrans
        in do
            fp <- mallocForeignPtrArray (m' * n)
            let p = unsafeForeignPtrToPtr fp
            return $ IOBanded h m n kl ku fp p l
    where
      err s = fail $ "newBanded_ " ++ show (m,n) ++ " " ++ show (kl,ku) ++ ": " ++ s

newIOBanded :: (Elem e)
            => (Int,Int)
            -> (Int,Int)
            -> [((Int,Int), e)]
            -> IO (IOBanded e)
newIOBanded (m,n) (kl,ku) ies = do
    a <- newIOBanded_ (m,n) (kl,ku)
    withIOBanded a $ \p ->
        clearArray p ((kl+1+ku)*n)
    forM_ ies $ \((i,j),e) -> do
        when (   i < 0 || i >= m
              || j < 0 || j >= n
              || (not $ hasStorageIOBanded a (i,j))) $ error $
            printf "newBanded (%d,%d) (%d,%d) [ ..., ((%d,%d),_), ... ]: invalid index"
                   m n kl ku i j
        unsafeWriteElemIOBanded a (i,j) e
    return a

unsafeNewIOBanded :: (Elem e)
                  => (Int,Int)
                  -> (Int,Int)
                  -> [((Int,Int), e)]
                  -> IO (IOBanded e)
unsafeNewIOBanded (m,n) (kl,ku) ies = do
    a <- newIOBanded_ (m,n) (kl,ku)
    withIOBanded a $ \p ->
        clearArray p ((kl+1+ku)*n)
    forM_ ies $ \(i,e) ->
        unsafeWriteElemIOBanded a i e
    return a

newListsIOBanded :: (Elem e)
                 => (Int,Int)
                 -> (Int,Int)
                 -> [[e]]
                 -> IO (IOBanded e)
newListsIOBanded (m,n) (kl,ku) xs = do
    a <- newIOBanded_ (m,n) (kl,ku)
    zipWithM_ (writeDiagElems a) [(negate kl)..ku] xs
    return a
  where
    writeDiagElems :: (Elem e)
                   => IOBanded e -> Int -> [e] -> IO ()
    writeDiagElems a i es =
        let d   = unsafeDiagViewIOBanded a i
            nb  = max 0 (-i)
            es' = drop nb es
        in zipWithM_ (unsafeWriteElem d) [0..(dim d - 1)] es'

newZeroIOBanded :: (Elem e) => (Int,Int) -> (Int,Int) -> IO (IOBanded e)
newZeroIOBanded mn bw = do
    a <- newIOBanded_ mn bw
    setZeroIOBanded a
    return a

setZeroIOBanded :: IOBanded e -> IO ()
setZeroIOBanded a@(IOBanded _ _ _ _ _ _ _ _) = setConstantIOBanded 0 a
{-# INLINE setZeroIOBanded #-}

newConstantIOBanded :: (Elem e)
                    => (Int,Int) -> (Int,Int) -> e -> IO (IOBanded e)
newConstantIOBanded mn bw e = do
    a <- newIOBanded_ mn bw
    setConstantIOBanded e a
    return a

setConstantIOBanded :: e -> IOBanded e -> IO ()
setConstantIOBanded e a@(IOBanded _ _ _ _ _ _ _ _)
    | isHermIOBanded a = setConstantIOBanded (conjugate e) (hermIOBanded a)
    | otherwise = do
        is <- getIndicesIOBanded a
        mapM_ (\i -> unsafeWriteElemIOBanded a i e) is
{-# INLINE setConstantIOBanded #-}

newCopyIOBanded :: IOBanded e -> IO (IOBanded e)
newCopyIOBanded a@(IOBanded _ _ _ _ _ _ _ _)
    | isHermIOBanded a =
        liftM hermIOBanded $ newCopyIOBanded (hermIOBanded a)
    | otherwise = do
        a' <- newIOBanded_ (shapeIOBanded a) (numLowerIOBanded a, numUpperIOBanded a)
        unsafeCopyIOBanded a' a
        return a'

unsafeCopyIOBanded :: IOBanded e -> IOBanded e -> IO ()
unsafeCopyIOBanded dst@(IOBanded _ _ _ _ _ _ _ _) src
    | isHermIOBanded dst =
        unsafeCopyIOBanded (hermIOBanded dst)
                           (hermIOBanded src)

    | (not . isHermIOBanded) src =
        withIOBanded dst $ \pDst ->
        withIOBanded src $ \pSrc ->
            if ldDst == m && ldSrc == m
                then copyBlock pDst pSrc
                else copyCols  pDst pSrc n

    | otherwise =
        zipWithM_ unsafeCopyVector (diagViews dst) (diagViews src)

  where
    m     = numLowerIOBanded dst + numUpperIOBanded dst + 1 -- we can be sure dst is not herm
    n     = numColsIOBanded dst
    ldDst = ldaIOBanded dst
    ldSrc = ldaIOBanded src

    copyBlock pDst pSrc =
        BLAS.copy NoConj NoConj (m*n) pSrc 1 pDst 1

    copyCols pDst pSrc nleft
        | nleft == 0 = return ()
        | otherwise = do
            BLAS.copy NoConj NoConj m pSrc 1 pDst 1
            copyCols (pDst `advancePtr` ldDst) (pSrc `advancePtr` ldSrc)
                     (nleft-1)

    diagViews a =
        case bandwidthsIOBanded a of
            (kl,ku) -> map (unsafeDiagViewIOBanded a) $ range (-kl,ku)

unsafeRowViewIOBanded :: IOBanded e
                      -> Int
                      -> (Int, IOVector e, Int)
unsafeRowViewIOBanded a@(IOBanded h _ n kl ku f p ld) i =
    if h == ConjTrans then
        case unsafeColViewIOBanded (hermIOBanded a) i of
            (nb, v, na) -> (nb, conj v, na)
    else
        let nb  = min n $ max (i - kl)         0
            na  = min n $ max (n - 1 - i - ku) 0
            r   = min (ku + i)         (kl + ku)
            c   = max (i - kl)         0
            p'  = p `advancePtr` (r + c * ld)
            inc = max (ld - 1) 1
            len = n - (nb + na)
        in (nb, IOVector NoConj len f p' inc, na)

unsafeColViewIOBanded :: IOBanded e
                      -> Int
                      -> (Int, IOVector e, Int)
unsafeColViewIOBanded a@(IOBanded h m _ kl ku f p ld) j =
    if h == ConjTrans then
        case unsafeRowViewIOBanded (hermIOBanded a) j of
            (nb, v, na) -> (nb, conj v, na)
    else
        let nb  = min m $ max (j - ku)         0
            na  = min m $ max (m - 1 - j - kl) 0
            r   = max (ku - j) 0
            c   = j
            p'  = p `advancePtr` (r + c * ld)
            inc = 1
            len = m - (nb + na)
        in (nb, IOVector NoConj len f p' inc, na)

unsafeDiagViewIOBanded :: IOBanded e -> Int -> IOVector e
unsafeDiagViewIOBanded a@(IOBanded h m n _ _ fp p ld) d
    | h == ConjTrans =
         conj $ unsafeDiagViewIOBanded (hermIOBanded a) (negate d)
    | otherwise =
        let off = indexIOBanded a (diagStart d)
            p'  = p `advancePtr` off
            len = diagLen (m,n) d
            inc = ld
        in (IOVector NoConj len fp p' inc)

unsafeGetRowIOBanded :: IOBanded e -> Int -> IO (IOVector e)
unsafeGetRowIOBanded a@(IOBanded _ _ _ _ _ _ _ _) i =
    let (nb,x,na) = unsafeRowViewIOBanded a i
        n = numCols a
    in do
        es <- getElems x
        newListVector n $ (replicate nb 0) ++ es ++ (replicate na 0)

unsafeGetColIOBanded :: IOBanded e -> Int -> IO (IOVector e)
unsafeGetColIOBanded a j =
    liftM conj $ unsafeGetRowIOBanded (hermIOBanded a) j

-- | @gbmv alpha a x beta y@ replaces @y := alpha a * x + beta y@
gbmv :: (ReadVector x IO, WriteVector y IO, BLAS2 e)
     => e -> IOBanded e -> x e -> e -> y e -> IO ()
gbmv alpha a (x :: x e) beta y
    | n == 0 =
        scaleByVector beta y
    | otherwise =
        let transA = transEnumIOBanded a
            (m',n',kl',ku') = if isHermIOBanded a
                                   then (n,m,ku,kl) else (m,n,kl,ku)
            ldA    = ldaIOBanded a
            incX   = stride x
            incY   = stride y
        in unsafePerformIOWithVector y $ \y' ->
           withIOBanded a $ \pA ->
           withIOVector (unsafeVectorToIOVector x) $ \pX ->
           withIOVector y' $ \pY ->
                BLAS.gbmv transA (conjEnum x) (conjEnum y)
                          m' n' kl' ku' alpha pA ldA pX incX beta pY incY
  where
    (m,n)   = shape a
    (kl,ku) = bandwidthsIOBanded a

-- | @gbmm alpha a b beta c@ replaces @c := alpha a * b + beta c@.
gbmm :: (ReadMatrix b IO, WriteMatrix c IO, BLAS2 e)
     => e -> IOBanded e -> b e -> e -> c e -> IO ()
gbmm alpha a b beta c =
    sequence_ $
        zipWith (\x y -> gbmv alpha a x beta y) (colViews b) (colViews c)

unsafeGetColHermIOBanded :: (WriteVector y IO, Elem e)
                         => Herm IOBanded e -> Int -> IO (y e)
unsafeGetColHermIOBanded =
    error "TODO: unsafeGetColHermIOBanded is not implemented"

unsafeGetRowHermIOBanded :: (WriteVector y IO, Elem e)
                         => Herm IOBanded e -> Int -> IO (y e)
unsafeGetRowHermIOBanded =
    error "TODO: unsafeGetRowHermIOBanded is not implemented"

hbmv :: (ReadVector x IO, BLAS2 e) =>
    e -> Herm IOBanded e -> x e -> e -> IOVector e -> IO ()
hbmv alpha h x beta y =
    let (u,a) = hermToBase h
        n     = numCols a
        k     = case u of
                    Upper -> numUpperIOBanded a
                    Lower -> numLowerIOBanded a
        uplo  = case (isHermIOBanded a) of
                    True  -> flipUpLo u
                    False -> u
        ldA   = ldaIOBanded a
        incX  = stride x
        incY  = stride y
        withPtrA
              = case uplo of Upper -> withIOBanded a
                             Lower -> withIOBandedElem a (0,0)
    in unsafePerformIOWithVector y $ \y' ->
       withPtrA $ \pA ->
       withIOVector (unsafeVectorToIOVector x) $ \pX ->
       withIOVector y' $ \pY ->
            BLAS.hbmv uplo (conjEnum x) (conjEnum y)
                      n k alpha pA ldA pX incX beta pY incY

hbmm :: (ReadMatrix b IO, BLAS2 e) =>
    e -> Herm IOBanded e -> b e -> e -> IOMatrix e -> IO ()
hbmm alpha h b beta c =
    zipWithM_ (\x y -> hbmv alpha h x beta y) (colViews b) (colViews c)

unsafeGetColTriIOBanded :: (WriteVector y IO, Elem e)
                        => Tri IOBanded e -> Int -> IO (y e)
unsafeGetColTriIOBanded =
    error "TODO: unsafeGetColTriIOBanded is not implemented"

unsafeGetRowTriIOBanded :: (WriteVector y IO, Elem e)
                        => Tri IOBanded e -> Int -> IO (y e)
unsafeGetRowTriIOBanded =
    error "TODO: unsafeGetRowTriIOBanded is not implemented"

tbmv :: (WriteVector y IO, BLAS2 e) =>
    e -> Tri IOBanded e -> y e -> IO ()
tbmv alpha t x =
    let (u,d,a) = triToBase t
        (transA,uploA)
                  = if isHermIOBanded a then (ConjTrans, flipUpLo u)
                                        else (NoTrans  , u)
        diagA     = d
        n         = numCols a
        k         = case u of Upper -> numUpperIOBanded a
                              Lower -> numLowerIOBanded a
        ldA       = ldaIOBanded a
        incX      = stride x
        withPtrA  = case uploA of
                        Upper -> withIOBanded a
                        Lower -> withIOBandedElem a (0,0)
    in unsafePerformIOWithVector x $ \x' ->
       withPtrA $ \pA ->
       withIOVector x' $ \pX -> do
           scaleByVector alpha x
           BLAS.tbmv uploA transA diagA (conjEnum x) n k pA ldA pX incX

tbmm :: (WriteMatrix b IO, BLAS2 e) =>
    e -> Tri IOBanded e -> b e -> IO ()
tbmm 1     t b = mapM_ (\x -> tbmv 1 t x) (colViews b)
tbmm alpha t b = scaleByMatrix alpha b >> tbmm 1 t b

tbmv' :: (ReadVector x IO, WriteVector y IO, BLAS2 e) =>
    e -> Tri IOBanded e -> x e -> e -> y e -> IO ()
tbmv' alpha a (x :: x e) beta (y  :: y e)
    | beta /= 0 = do
        (x' :: y e) <- newCopyVector x
        tbmv alpha a x'
        scaleByVector beta y
        unsafeAxpyVector 1 x' y
    | otherwise = do
        unsafeCopyVector y x
        tbmv alpha a y

tbmm' :: (ReadMatrix b IO, WriteMatrix c IO, BLAS2 e) =>
    e -> Tri IOBanded e -> b e -> e -> c e -> IO ()
tbmm' alpha a (b :: b e) beta (c :: c e)
    | beta /= 0 = do
        (b' :: c e) <- newCopyMatrix b
        tbmm alpha a b'
        scaleByMatrix beta c
        unsafeAxpyMatrix 1 b' c
    | otherwise = do
        unsafeCopyMatrix c b
        tbmm alpha a c

tbsv :: (WriteVector y IO, BLAS2 e) =>
    e -> Tri IOBanded e -> y e -> IO ()
tbsv alpha t x =
    let (u,d,a) = triToBase t
        (transA,uploA)
                  = if isHermIOBanded a then (ConjTrans, flipUpLo u)
                                        else (NoTrans  , u)
        diagA     = d
        n         = numCols a
        k         = case u of Upper -> numUpperIOBanded a
                              Lower -> numLowerIOBanded a
        ldA       = ldaIOBanded a
        incX      = stride x
        withPtrA  = case uploA of
                        Upper -> withIOBanded a
                        Lower -> withIOBandedElem a (0,0)
    in unsafePerformIOWithVector x $ \x' ->
       withPtrA $ \pA ->
       withIOVector x' $ \pX -> do
           scaleByVector alpha x
           BLAS.tbsv uploA transA diagA (conjEnum x) n k pA ldA pX incX

tbsm :: (WriteMatrix b IO, BLAS2 e) =>
    e -> Tri IOBanded e -> b e -> IO ()
tbsm 1     t b = mapM_ (\x -> tbsv 1 t x) (colViews b)
tbsm alpha t b = scaleByMatrix alpha b >> tbsm 1 t b

tbsv' :: (ReadVector y IO, WriteVector x IO, BLAS2 e)
      => e -> Tri IOBanded e -> y e -> x e -> IO ()
tbsv' alpha a y x = do
    unsafeCopyVector x y
    tbsv alpha a x

tbsm' :: (ReadMatrix c IO, WriteMatrix b IO, BLAS2 e)
      => e -> Tri IOBanded e -> c e -> b e -> IO ()
tbsm' alpha a c b = do
    unsafeCopyMatrix b c
    tbsm alpha a b

instance HasVectorView IOBanded where
    type VectorView IOBanded = IOVector

instance HasMatrixStorage IOBanded where
    type MatrixStorage IOBanded = IOMatrix

instance Shaped IOBanded (Int,Int) where
    shape  = shapeIOBanded
    {-# INLINE shape #-}
    bounds = boundsIOBanded
    {-# INLINE bounds #-}

instance MatrixShaped IOBanded where

instance HasHerm IOBanded where
    herm = hermIOBanded
    {-# INLINE herm #-}

instance ReadTensor IOBanded (Int,Int) IO where
    getSize        = getSizeIOBanded
    {-# INLINE getSize #-}
    getAssocs      = getAssocsIOBanded
    {-# INLINE getAssocs #-}
    getIndices     = getIndicesIOBanded
    {-# INLINE getIndices #-}
    getElems       = getElemsIOBanded
    {-# INLINE getElems #-}
    getAssocs'     = getAssocsIOBanded'
    {-# INLINE getAssocs' #-}
    getIndices'    = getIndicesIOBanded'
    {-# INLINE getIndices' #-}
    getElems'      = getElemsIOBanded'
    {-# INLINE getElems' #-}
    unsafeReadElem = unsafeReadElemIOBanded
    {-# INLINE unsafeReadElem #-}

instance WriteTensor IOBanded (Int,Int) IO where
    setConstant     = setConstantIOBanded
    {-# INLINE setConstant #-}
    setZero         = setZeroIOBanded
    {-# INLINE setZero #-}
    modifyWith      = modifyWithIOBanded
    {-# INLINE modifyWith #-}
    unsafeWriteElem = unsafeWriteElemIOBanded
    {-# INLINE unsafeWriteElem #-}
    canModifyElem   = canModifyElemIOBanded
    {-# INLINE canModifyElem #-}

instance MMatrix IOBanded IO where
    unsafeDoSApplyAddVector    = gbmv
    {-# INLINE unsafeDoSApplyAddVector #-}
    unsafeDoSApplyAddMatrix = gbmm
    {-# INLINE unsafeDoSApplyAddMatrix #-}
    unsafeGetRow a i = unsafeConvertIOVector $ unsafeGetRowIOBanded a i
    {-# INLINE unsafeGetRow #-}
    unsafeGetCol a j = unsafeConvertIOVector $ unsafeGetColIOBanded a j
    {-# INLINE unsafeGetCol #-}

instance MMatrix (Herm IOBanded) IO where
    unsafeDoSApplyAddVector alpha a x beta y =
        hbmv alpha a x beta (unsafeVectorToIOVector y)
    {-# INLINE unsafeDoSApplyAddVector #-}
    unsafeDoSApplyAddMatrix alpha a b beta c =
        hbmm alpha a b beta (unsafeMatrixToIOMatrix c)
    {-# INLINE unsafeDoSApplyAddMatrix #-}
    unsafeGetRow = unsafeGetRowHermIOBanded
    {-# INLINE unsafeGetRow #-}
    unsafeGetCol = unsafeGetColHermIOBanded
    {-# INLINE unsafeGetCol #-}

instance MMatrix (Tri IOBanded) IO where
    unsafeDoSApplyVector_       = tbmv
    {-# INLINE unsafeDoSApplyVector_  #-}
    unsafeDoSApplyMatrix_   = tbmm
    {-# INLINE unsafeDoSApplyMatrix_ #-}
    unsafeDoSApplyAddVector    = tbmv'
    {-# INLINE unsafeDoSApplyAddVector #-}
    unsafeDoSApplyAddMatrix = tbmm'
    {-# INLINE unsafeDoSApplyAddMatrix #-}
    unsafeGetRow = unsafeGetRowTriIOBanded
    {-# INLINE unsafeGetRow #-}
    unsafeGetCol = unsafeGetColTriIOBanded
    {-# INLINE unsafeGetCol #-}

instance MSolve (Tri IOBanded) IO where
    unsafeDoSSolveVector_    = tbsv
    {-# INLINE unsafeDoSSolveVector_ #-}
    unsafeDoSSolveMatrix_ = tbsm
    {-# INLINE unsafeDoSSolveMatrix_ #-}
    unsafeDoSSolveVector     = tbsv'
    {-# INLINE unsafeDoSSolveVector #-}
    unsafeDoSSolveMatrix  = tbsm'
    {-# INLINE unsafeDoSSolveMatrix #-}


text:
<!DOCTYPE html>
<!--
@license
Copyright (C) 2018 The Android Open Source Project

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.
-->

<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>gr-error-dialog</title>

<script src="../../../bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
<script src="../../../bower_components/web-component-tester/browser.js"></script>
<link rel="import" href="../../../test/common-test-setup.html"/>
<link rel="import" href="gr-error-dialog.html">

<script>void(0);</script>

<test-fixture id="basic">
  <template>
    <gr-error-dialog></gr-error-dialog>
  </template>
</test-fixture>

<script>
  suite('gr-error-dialog tests', () => {
    let element;

    setup(() => {
      element = fixture('basic');
    });

    test('dismiss tap fires event', done => {
      element.addEventListener('dismiss', () => { done(); });
      MockInteractions.tap(element.$.dialog.$.confirm);
    });
  });
</script>


text:
// Dependencies
var Typpy = require("typpy")
  , Deffy = require("deffy")
  ;

// Constructor
function Ul() {}

/**
 * merge
 * One level merge. Faster than `deepMerge`.
 *
 * @name merge
 * @function
 * @param dst {Object} The destination object.
 * @param src {Object} The source object (usually defaults).
 * @return {Object} The result object.
 */
Ul.prototype.merge = function (dst, src, p) {
    var res = {}
      , k = null
      ;

    src = Deffy(src, {});
    dst = Deffy(dst, {});

    for (k in src) { res[k] = src[k]; }
    for (k in dst) {
        if (undefined === dst[k]) {
            continue;
        }
        res[k] = dst[k];
    }

    return res;
};

/**
 * deepMerge
 * Recursively merge the objects from arguments, returning a new object.
 *
 * Usage: `Ul.deepMerge(obj1, obj2, obj3, obj4, ..., objN)`
 *
 * @name deepMerge
 * @function
 * @return {Object} The merged objects.
 */
Ul.prototype.deepMerge = function () {

    var dst = {}
      , src
      , p
      , args = [].splice.call(arguments, 0)
      ;

    while (args.length > 0) {
        src = args.splice(-1)[0];
        if (Typpy(src) !== "object") { continue; }
        for (p in src) {
            if (!src.hasOwnProperty(p)) { continue; }
            if (Typpy(src[p]) === "object") {
                dst[p] = this.deepMerge(src[p], dst[p] || {});
            } else {
                if (src[p] !== undefined) {
                    dst[p] = src[p];
                }
            }
        }
    }

    return dst;
};

/**
 * clone
 * Deep clone of the provided item.
 *
 * @name clone
 * @function
 * @param {Anything} item The item that should be cloned
 * @return {Anything} The cloned object
 */
Ul.prototype.clone = function (item) {

    if (!item) { return item; }
    var self = this
      , types = [Number, String, Boolean]
      , result
      , i
      ;

    types.forEach(function(type) {
        if (item instanceof type) {
            result = type(item);
        }
    });

    if (typeof result == "undefined") {
        if (Array.isArray(item)) {
            result = [];
            item.forEach(function(child, index) {
                result[index] = self.clone(child);
            });
        } else if (typeof item == "object") {
            if (!item.prototype) {
                if (item instanceof Date) {
                    result = new Date(item);
                } else {
                    result = {};
                    for (i in item) {
                        result[i] = self.clone(item[i]);
                    }
                }
            } else {
                result = item;
            }
        } else {
            result = item;
        }
    }

    return result;
};

/**
 * home
 * Get the home directory path on any platform. The value can be
 * accessed using `Ul.HOME_DIR` too.
 *
 * @name home
 * @function
 * @return {String} The home directory path.
 */
Ul.prototype.HOME_DIR = process.env[(process.platform == "win32") ? "USERPROFILE" : "HOME"];
Ul.prototype.home = function () {
    return this.HOME_DIR;
};

module.exports = new Ul();


text:
{{vm.social._id ? 'Edit Social' : 'New Social'}}

    <form name="vm.form.socialForm" class="form-horizontal" ng-submit="vm.save(vm.form.socialForm.$valid)" novalidate>
      <fieldset>

          Name
          <input name="name" type="text" ng-model="vm.social.name" id="name" class="form-control" placeholder="Name" required>

Social name is required.

          <button type="submit" class="btn btn-default">{{vm.social._id ? 'Update' : 'Create'}}</button>

      </fieldset>
    </form>