text:
package sun.security.ssl;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import javax.net.ssl.SSLHandshakeException;

import sun.security.ssl.SSLCipher.SSLWriteCipher;

/**
 * {@code OutputRecord} implementation for {@code SSLEngine}.
 */
final class SSLEngineOutputRecord extends OutputRecord implements SSLRecord {

    private HandshakeFragment fragmenter;
    private boolean isTalkingToV2;      // SSLv2Hello
    private ByteBuffer v2ClientHello;    // SSLv2Hello

    private volatile boolean isCloseWaiting;

    SSLEngineOutputRecord(HandshakeHash handshakeHash) {
        super(handshakeHash, SSLWriteCipher.nullTlsWriteCipher());

        this.packetSize = SSLRecord.maxRecordSize;
        this.protocolVersion = ProtocolVersion.NONE;
    }

    @Override
    public void close() throws IOException {
        recordLock.lock();
        try {
            if (!isClosed) {
                if (fragmenter != null && !fragmenter.isEmpty()) {
                    isCloseWaiting = true;
                } else {
                    super.close();
                }
            }
        } finally {
            recordLock.unlock();
        }
    }

    boolean isClosed() {
        return isClosed || isCloseWaiting;
    }

    @Override
    void encodeAlert(byte level, byte description) throws IOException {
        if (isClosed()) {
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                SSLLogger.warning("outbound has closed, ignore outbound " +
                    "alert message: " + Alert.nameOf(description));
            }
            return;
        }

        if (fragmenter == null) {
           fragmenter = new HandshakeFragment();
        }

        fragmenter.queueUpAlert(level, description);
    }

    @Override
    void encodeHandshake(byte[] source,
            int offset, int length) throws IOException {
        if (isClosed()) {
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                SSLLogger.warning("outbound has closed, ignore outbound " +
                        "handshake message",
                        ByteBuffer.wrap(source, offset, length));
            }
            return;
        }

        if (fragmenter == null) {
           fragmenter = new HandshakeFragment();
        }

        if (firstMessage) {
            firstMessage = false;

            if ((helloVersion == ProtocolVersion.SSL20Hello) &&
                (source[offset] == SSLHandshake.CLIENT_HELLO.id) &&
                                            //  5: recode header size
                (source[offset + 4 + 2 + 32] == 0)) {
                                            // V3 session ID is empty
                                            //  4: handshake header size
                                            //  2: client_version in ClientHello
                                            // 32: random in ClientHello

                // Double space should be big enough for the converted message.
                v2ClientHello = encodeV2ClientHello(
                        source, (offset + 4), (length - 4));

                v2ClientHello.position(2);     // exclude the header
                handshakeHash.deliver(v2ClientHello);
                v2ClientHello.position(0);

                return;
            }
        }

        byte handshakeType = source[offset];
        if (handshakeHash.isHashable(handshakeType)) {
            handshakeHash.deliver(source, offset, length);
        }

        fragmenter.queueUpFragment(source, offset, length);
    }

    @Override
    void encodeChangeCipherSpec() throws IOException {
        if (isClosed()) {
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                SSLLogger.warning("outbound has closed, ignore outbound " +
                    "change_cipher_spec message");
            }
            return;
        }

        if (fragmenter == null) {
           fragmenter = new HandshakeFragment();
        }
        fragmenter.queueUpChangeCipherSpec();
    }

    @Override
    void encodeV2NoCipher() throws IOException {
        isTalkingToV2 = true;
    }

    @Override
    Ciphertext encode(
        ByteBuffer[] srcs, int srcsOffset, int srcsLength,
        ByteBuffer[] dsts, int dstsOffset, int dstsLength) throws IOException {

        if (isClosed) {
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                SSLLogger.warning("outbound has closed, ignore outbound " +
                    "application data or cached messages");
            }

            return null;
        } else if (isCloseWaiting) {
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                SSLLogger.warning("outbound has closed, ignore outbound " +
                    "application data");
            }

            srcs = null;    // use no application data.
        }

        return encode(srcs, srcsOffset, srcsLength, dsts[0]);
    }

    private Ciphertext encode(ByteBuffer[] sources, int offset, int length,
            ByteBuffer destination) throws IOException {

        if (writeCipher.authenticator.seqNumOverflow()) {
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                SSLLogger.fine(
                    "sequence number extremely close to overflow " +
                    "(2^64-1 packets). Closing connection.");
            }

            throw new SSLHandshakeException("sequence number overflow");
        }

        // Don't process the incoming record until all of the
        // buffered records get handled.
        Ciphertext ct = acquireCiphertext(destination);
        if (ct != null) {
            return ct;
        }

        if (sources == null || sources.length == 0) {
            return null;
        }

        int srcsRemains = 0;
        for (int i = offset; i < offset + length; i++) {
            srcsRemains += sources[i].remaining();
        }

        if (srcsRemains == 0) {
            return null;
        }

        int dstLim = destination.limit();
        boolean isFirstRecordOfThePayload = true;
        int packetLeftSize = Math.min(maxRecordSize, packetSize);
        boolean needMorePayload = true;
        long recordSN = 0L;
        while (needMorePayload) {
            int fragLen;
            if (isFirstRecordOfThePayload && needToSplitPayload()) {
                needMorePayload = true;

                fragLen = 1;
                isFirstRecordOfThePayload = false;
            } else {
                needMorePayload = false;

                if (packetLeftSize > 0) {
                    fragLen = writeCipher.calculateFragmentSize(
                            packetLeftSize, headerSize);

                    fragLen = Math.min(fragLen, Record.maxDataSize);
                } else {
                    fragLen = Record.maxDataSize;
                }

                // Calculate more impact, for example TLS 1.3 padding.
                fragLen = calculateFragmentSize(fragLen);
            }

            int dstPos = destination.position();
            int dstContent = dstPos + headerSize +
                                writeCipher.getExplicitNonceSize();
            destination.position(dstContent);

            int remains = Math.min(fragLen, destination.remaining());
            fragLen = 0;
            int srcsLen = offset + length;
            for (int i = offset; (i < srcsLen) && (remains > 0); i++) {
                int amount = Math.min(sources[i].remaining(), remains);
                int srcLimit = sources[i].limit();
                sources[i].limit(sources[i].position() + amount);
                destination.put(sources[i]);
                sources[i].limit(srcLimit);         // restore the limit
                remains -= amount;
                fragLen += amount;

                if (remains > 0) {
                    offset++;
                    length--;
                }
            }

            destination.limit(destination.position());
            destination.position(dstContent);

            if (SSLLogger.isOn && SSLLogger.isOn("record")) {
                SSLLogger.fine(
                        "WRITE: " + protocolVersion.name + " " +
                        ContentType.APPLICATION_DATA.name +
                        ", length = " + destination.remaining());
            }

            // Encrypt the fragment and wrap up a record.
            recordSN = encrypt(writeCipher,
                    ContentType.APPLICATION_DATA.id, destination,
                    dstPos, dstLim, headerSize,
                    protocolVersion);

            if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
                ByteBuffer temporary = destination.duplicate();
                temporary.limit(temporary.position());
                temporary.position(dstPos);
                SSLLogger.fine("Raw write", temporary);
            }

            packetLeftSize -= destination.position() - dstPos;

            // remain the limit unchanged
            destination.limit(dstLim);

            if (isFirstAppOutputRecord) {
                isFirstAppOutputRecord = false;
            }
        }

        return new Ciphertext(ContentType.APPLICATION_DATA.id,
                SSLHandshake.NOT_APPLICABLE.id, recordSN);
    }

    private Ciphertext acquireCiphertext(
            ByteBuffer destination) throws IOException {
        if (isTalkingToV2) {              // SSLv2Hello
            // We don't support SSLv2.  Send an SSLv2 error message
            // so that the connection can be closed gracefully.
            //
            // Please don't change the limit of the destination buffer.
            destination.put(SSLRecord.v2NoCipher);
            if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
                SSLLogger.fine("Raw write", SSLRecord.v2NoCipher);
            }

            isTalkingToV2 = false;

            return new Ciphertext(ContentType.ALERT.id,
                    SSLHandshake.NOT_APPLICABLE.id, -1L);
        }

        if (v2ClientHello != null) {
            // deliver the SSLv2 format ClientHello message
            //
            // Please don't change the limit of the destination buffer.
            if (SSLLogger.isOn) {
                if (SSLLogger.isOn("record")) {
                     SSLLogger.fine(Thread.currentThread().getName() +
                            ", WRITE: SSLv2 ClientHello message" +
                            ", length = " + v2ClientHello.remaining());
                }

                if (SSLLogger.isOn("packet")) {
                    SSLLogger.fine("Raw write", v2ClientHello);
                }
            }

            destination.put(v2ClientHello);
            v2ClientHello = null;

            return new Ciphertext(ContentType.HANDSHAKE.id,
                   SSLHandshake.CLIENT_HELLO.id, -1L);
        }

        if (fragmenter != null) {
            return fragmenter.acquireCiphertext(destination);
        }

        return null;
    }

    @Override
    boolean isEmpty() {
        return (!isTalkingToV2) && (v2ClientHello == null) &&
                ((fragmenter == null) || fragmenter.isEmpty());
    }

    // buffered record fragment
    private static class RecordMemo {
        byte            contentType;
        byte            majorVersion;
        byte            minorVersion;
        SSLWriteCipher  encodeCipher;

        byte[]          fragment;
    }

    private static class HandshakeMemo extends RecordMemo {
        byte            handshakeType;
        int             acquireOffset;
    }

    final class HandshakeFragment {
        private final LinkedList<RecordMemo> handshakeMemos =
                new LinkedList<>();

        void queueUpFragment(byte[] source,
                int offset, int length) throws IOException {
            HandshakeMemo memo = new HandshakeMemo();

            memo.contentType = ContentType.HANDSHAKE.id;
            memo.majorVersion = protocolVersion.major;  // kick start version?
            memo.minorVersion = protocolVersion.minor;
            memo.encodeCipher = writeCipher;

            memo.handshakeType = source[offset];
            memo.acquireOffset = 0;
            memo.fragment = new byte[length - 4];       // 4: header size
                                                        //    1: HandshakeType
                                                        //    3: message length
            System.arraycopy(source, offset + 4, memo.fragment, 0, length - 4);

            handshakeMemos.add(memo);
        }

        void queueUpChangeCipherSpec() {
            RecordMemo memo = new RecordMemo();

            memo.contentType = ContentType.CHANGE_CIPHER_SPEC.id;
            memo.majorVersion = protocolVersion.major;
            memo.minorVersion = protocolVersion.minor;
            memo.encodeCipher = writeCipher;

            memo.fragment = new byte[1];
            memo.fragment[0] = 1;

            handshakeMemos.add(memo);
        }

        void queueUpAlert(byte level, byte description) {
            RecordMemo memo = new RecordMemo();

            memo.contentType = ContentType.ALERT.id;
            memo.majorVersion = protocolVersion.major;
            memo.minorVersion = protocolVersion.minor;
            memo.encodeCipher = writeCipher;

            memo.fragment = new byte[2];
            memo.fragment[0] = level;
            memo.fragment[1] = description;

            handshakeMemos.add(memo);
        }

        Ciphertext acquireCiphertext(ByteBuffer dstBuf) throws IOException {
            if (isEmpty()) {
                return null;
            }

            RecordMemo memo = handshakeMemos.getFirst();
            HandshakeMemo hsMemo = null;
            if (memo.contentType == ContentType.HANDSHAKE.id) {
                hsMemo = (HandshakeMemo)memo;
            }

            // ChangeCipherSpec message is pretty small.  Don't worry about
            // the fragmentation of ChangeCipherSpec record.
            int fragLen;
            if (packetSize > 0) {
                fragLen = Math.min(maxRecordSize, packetSize);
                fragLen = memo.encodeCipher.calculateFragmentSize(
                        fragLen, headerSize);
            } else {
                fragLen = Record.maxDataSize;
            }

            // Calculate more impact, for example TLS 1.3 padding.
            fragLen = calculateFragmentSize(fragLen);

            int dstPos = dstBuf.position();
            int dstLim = dstBuf.limit();
            int dstContent = dstPos + headerSize +
                                    memo.encodeCipher.getExplicitNonceSize();
            dstBuf.position(dstContent);

            if (hsMemo != null) {
                int remainingFragLen = fragLen;
                while ((remainingFragLen > 0) && !handshakeMemos.isEmpty()) {
                    int memoFragLen = hsMemo.fragment.length;
                    if (hsMemo.acquireOffset == 0) {
                        // Don't fragment handshake message header
                        if (remainingFragLen <= 4) {
                            break;
                        }

                        dstBuf.put(hsMemo.handshakeType);
                        dstBuf.put((byte)((memoFragLen >> 16) & 0xFF));
                        dstBuf.put((byte)((memoFragLen >> 8) & 0xFF));
                        dstBuf.put((byte)(memoFragLen & 0xFF));

                        remainingFragLen -= 4;
                    } // Otherwise, handshake message is fragmented.

                    int chipLen = Math.min(remainingFragLen,
                            (memoFragLen - hsMemo.acquireOffset));
                    dstBuf.put(hsMemo.fragment, hsMemo.acquireOffset, chipLen);

                    hsMemo.acquireOffset += chipLen;
                    if (hsMemo.acquireOffset == memoFragLen) {
                        handshakeMemos.removeFirst();

                        // still have space for more records?
                        if ((remainingFragLen > chipLen) &&
                                 !handshakeMemos.isEmpty()) {

                            // look for the next buffered record fragment
                            RecordMemo rm = handshakeMemos.getFirst();
                            if (rm.contentType == ContentType.HANDSHAKE.id &&
                                    rm.encodeCipher == hsMemo.encodeCipher) {
                                hsMemo = (HandshakeMemo)rm;
                            } else {
                                // not of the flight, break the loop
                                break;
                            }
                        }
                    }

                    remainingFragLen -= chipLen;
                }
            } else {
                fragLen = Math.min(fragLen, memo.fragment.length);
                dstBuf.put(memo.fragment, 0, fragLen);

                handshakeMemos.removeFirst();
            }

            dstBuf.limit(dstBuf.position());
            dstBuf.position(dstContent);

            if (SSLLogger.isOn && SSLLogger.isOn("record")) {
                SSLLogger.fine(
                        "WRITE: " + protocolVersion.name + " " +
                        ContentType.nameOf(memo.contentType) +
                        ", length = " + dstBuf.remaining());
            }

            // Encrypt the fragment and wrap up a record.
            long recordSN = encrypt(
                    memo.encodeCipher,
                    memo.contentType, dstBuf,
                    dstPos, dstLim, headerSize,
                    ProtocolVersion.valueOf(memo.majorVersion,
                            memo.minorVersion));

            if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
                ByteBuffer temporary = dstBuf.duplicate();
                temporary.limit(temporary.position());
                temporary.position(dstPos);
                SSLLogger.fine("Raw write", temporary);
            }

            // remain the limit unchanged
            dstBuf.limit(dstLim);

            // Reset the fragmentation offset.
            try {
                if (hsMemo != null) {
                    return new Ciphertext(hsMemo.contentType,
                            hsMemo.handshakeType, recordSN);
                } else {
                    return new Ciphertext(memo.contentType,
                            SSLHandshake.NOT_APPLICABLE.id, recordSN);
                }
            } finally {
                if (isCloseWaiting && isEmpty()) {
                    close();
                }
            }
        }

        boolean isEmpty() {
            return handshakeMemos.isEmpty();
        }
    }

    /*
     * Need to split the payload except the following cases:
     *
     * 1. protocol version is TLS 1.1 or later;
     * 2. bulk cipher does not use CBC mode, including null bulk cipher suites.
     * 3. the payload is the first application record of a freshly
     *    negotiated TLS session.
     * 4. the CBC protection is disabled;
     *
     * By default, we counter chosen plaintext issues on CBC mode
     * ciphersuites in SSLv3/TLS1.0 by sending one byte of application
     * data in the first record of every payload, and the rest in
     * subsequent record(s). Note that the issues have been solved in
     * TLS 1.1 or later.
     *
     * It is not necessary to split the very first application record of
     * a freshly negotiated TLS session, as there is no previous
     * application data to guess.  To improve compatibility, we will not
     * split such records.
     *
     * This avoids issues in the outbound direction.  For a full fix,
     * the peer must have similar protections.
     */
    boolean needToSplitPayload() {
        return (!protocolVersion.useTLS11PlusSpec()) &&
                writeCipher.isCBCMode() && !isFirstAppOutputRecord &&
                Record.enableCBCProtection;
    }
}


text:
namespace MassTransit.ActiveMqTransport.Topology.Builders
{
    using Entities;
    using GreenPipes;

    public interface BrokerTopology :
        IProbeSite
    {
        Topic[] Topics { get; }
        Queue[] Queues { get; }
        Consumer[] Consumers { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Hicks - Warner Wedding
date: 2016-05-24
author: Lauren Moody
tags: weekly links, java
status: published
summary: Morbi suscipit neque vel est maximus, in rhoncus odio tincidunt.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 09/24/2017
  endDate: 09/27/2017
  ctyhocn: MSOMTHX
  groupCode: HWW
published: true
---
Pellentesque at nisl eu sem fermentum lobortis. Nulla ex libero, sodales ac fringilla eget, vestibulum vitae sem. Fusce ullamcorper consequat nibh id lobortis. Quisque suscipit, nisi gravida faucibus sagittis, diam erat sagittis urna, sit amet semper dui augue ut neque. Nunc eu lectus eleifend, lobortis nulla sed, vehicula mauris. Curabitur tincidunt velit orci, ac tincidunt dui auctor id. Aenean interdum, nibh et luctus faucibus, sem turpis tincidunt dui, a ultricies lectus ante ut ex. Fusce lobortis auctor nisl, vel sollicitudin elit mattis eget. Proin eu lobortis nisl. Nam justo nisl, lobortis sed iaculis a, convallis sed est.
Etiam rutrum vitae odio eget iaculis. Nulla a orci id neque interdum ullamcorper. Donec vel quam non neque viverra aliquet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec lacus convallis nisl feugiat vestibulum. In congue, sapien eu finibus tristique, felis justo molestie sem, at lacinia urna nisi at nulla. Integer mattis, urna eu auctor tempor, felis augue auctor augue, nec placerat orci arcu et tellus. Vestibulum tempus mi blandit, elementum ante sit amet, sollicitudin leo.

* Praesent id neque vestibulum, auctor ante ac, consectetur quam
* Quisque sollicitudin dui ut magna interdum, id vehicula lectus sollicitudin
* Sed mollis lectus a dictum mattis
* Praesent eu arcu condimentum turpis ultricies varius sit amet non massa
* Integer aliquet dolor quis est consequat, eget pharetra ante fringilla
* Curabitur mollis quam efficitur, eleifend ipsum et, mollis nisl.

Duis non nibh metus. Sed egestas nibh sit amet nisi pulvinar fermentum. Pellentesque nec mauris sit amet augue lobortis lacinia et a mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas semper orci ac pulvinar pellentesque. Aliquam sed ex at arcu rhoncus cursus at non arcu. Morbi et semper risus, nec mattis dolor. Praesent blandit ullamcorper nunc ac venenatis. Praesent condimentum finibus pretium. Quisque non massa sit amet velit convallis elementum. Donec et semper erat, et sollicitudin augue.


text:
package ca.flop.jpublish.dwr;

import org.directwebremoting.extend.Handler;
import org.directwebremoting.extend.DebugPageGenerator;
import org.directwebremoting.util.LocalUtil;
import org.directwebremoting.util.MimeConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Florin T.PATRASCU
 * @version $Revision:$ Apr 5, 2007, 10:47:57 AM
 */
public class DWRTestHandler  implements Handler {
    /* (non-Javadoc)
     * @see org.directwebremoting.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String scriptName = request.getPathInfo();
        String dwrPrefix = (String) request.getAttribute( DWRModule.DWR_PREFIX_REQUEST_TAG_NAME);
        if (dwrPrefix == null || dwrPrefix.trim().length() == 0) {
            dwrPrefix = DWRModule.DWR_DEFAULT_PREFIX;
        }
        scriptName = LocalUtil.replace(scriptName, dwrPrefix, "");
        scriptName = LocalUtil.replace(scriptName, testHandlerUrl, "");
        scriptName = LocalUtil.replace(scriptName, "/", "");

        String page = debugPageGenerator.generateTestPage(request.getContextPath() + request.getServletPath(), scriptName);

        response.setContentType(MimeConstants.MIME_HTML);
        PrintWriter out = response.getWriter();
        out.print(page);
    }

    /**
     * Setter for the debug page generator
     * @param debugPageGenerator
     */
    public void setDebugPageGenerator(DebugPageGenerator debugPageGenerator)
    {
        this.debugPageGenerator = debugPageGenerator;
    }

    /**
     * The bean to handle debug page requests
     */
    protected DebugPageGenerator debugPageGenerator = null;

    /**
     * Setter for the URL that this handler available on
     * @param testHandlerUrl the testHandlerUrl to set
     */
    public void setTestHandlerUrl(String testHandlerUrl)
    {
        this.testHandlerUrl = testHandlerUrl;
    }

    /**
     * What URL is this handler available on?
     */
    protected String testHandlerUrl;
}


text:
package com.monsanto.arch.kamon.prometheus.metric

import java.util.regex.Pattern

import kamon.metric.SingleInstrumentEntityRecorder
import kamon.util.MilliTimestamp

/** A metric represents a single item in Prometheus' data model.
  *
  * @param value the metric value, note that all values are coerced to doubles
  * @param timestamp the time of this snapshot
  * @param labels the labels for the metric, which should conform to Prometheus' guidelines
  *
  * @see [[com.monsanto.arch.kamon.prometheus.converter.SnapshotConverter SnapshotConverter]]
  *
  * @author Daniel Solano Gómez
  */
case class Metric(value: MetricValue, timestamp: MilliTimestamp, labels: Map[String,String] = Map.empty) {
  // require that everything has values that Prometheus will accept
  labels.foreach {case (key, _) ⇒
    require(Metric.isValidLabelName(key), s"Invalid label name: '$key'")
  }
}

private[prometheus] object Metric {
  /** Verifies that a label name is generally valid. */
  private val LabelNamePattern = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9_]*$")

  /** Returns true if the given name is a valid, non-reserved Prometheus label name. */
  def isValidLabelName(name: String): Boolean = LabelNamePattern.matcher(name).matches() && !name.startsWith("__")
}


text:
package com.sequenceiq.cloudbreak.reactor.api.event.stack.userdata;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sequenceiq.cloudbreak.cloud.event.CloudPlatformResult;
import com.sequenceiq.cloudbreak.common.event.FlowPayload;
import com.sequenceiq.cloudbreak.common.event.Selectable;

public class UserDataUpdateOnProviderResult extends CloudPlatformResult implements Selectable, FlowPayload {
    @JsonCreator
    public UserDataUpdateOnProviderResult(
            @JsonProperty("resourceId") Long resourceId) {
        super(resourceId);
    }
}


text:
#include "xvmaininc.h"
#include "defines.h"
#include "rtlintproto.h"
#include "ftnbridge.h"

#if FORSTR_METHOD_A
#include <descrip>
#endif

#if FORSTR_METHOD_D
#include <fortran.h>
#endif

/************************************************************************/
/* sfor2c_array transforms an input standard C null-terminated two-	*/
/* dimensional array of characters into an output Fortran string array.	*/
/* The Fortran string can be one of several types, defined in		*/
/* ftnbridge.h  The len parameter is the best guess for the length of	*/
/* the Fortran strings on input (used in case the length isn't present),*/
/* and the actual Fortran string length on output.  Maxlen is the true	*/
/* length of the input C string.  Nelements is the number of array	*/
/* elements.  The string array is copied from c_value to for_value.	*/
/* See the routine sc2for for explanations and warnings about the rest	*/
/* of the arguments (FORSTR_PARM, FORSTR_DEF, and FORSTR_BLOCK are	*/
/* still required, as in sc2for().					*/
/*									*/
/* A status code is no longer returned by this function (since there	*/
/* are no errors to return, and nobody looked anyway).			*/
/*									*/
/* See sfor2c.c for comments on how the various Fortran string types	*/
/* are handled, the three API's, and detailed descriptions of the	*/
/* parameters.  The same rules apply for macros, etc.			*/
/************************************************************************/

/* OLD API */

void sc2for_array(
   char *c_string,		/* In: string array in C format		*/
   int maxlen,			/* In: size of c_string inner dimension	*/
   int nelements,		/* In: # of elements in array		*/
   char *for_string,		/* Out: the Fortran string array	*/
   int *len,			/* In/Out: length guess, Ftn length per elem */
   void *argptr,		/* In: ptr to original argument list	*/
   int nargs,			/* In: total number of arguments	*/
   int argno,			/* In: this argument number (start at 1)*/
   int strno			/* In: this string number (start at 1)	*/
)

{
   int which = 0;
   v2_sc2for_array(c_string, maxlen, nelements, for_string, len,
		argptr, nargs, argno, strno, NULL, &which);
}

/* NEW API */

void v2_sc2for_array(
   char *c_string,		/* In: string array in C format		*/
   int maxlen,			/* In: size of c_string inner dimension	*/
   int nelements,		/* In: # of elements in array		*/
   char *for_string,		/* Out: the Fortran string array	*/
   int *len,			/* In/Out: length guess, Ftn length per elem */
   void *argptr,		/* In: ptr to original argument list	*/
   int nargs,			/* In: total number of arguments	*/
   int argno,			/* In: this argument number (start at 1)*/
   int strno,			/* In: this string number (start at 1)	*/
   va_list *valist,		/* In/Out: stdarg ptr past arg list (see*/
				/*     description in sfor2c.c).	*/
				/*     Modified by this routine.	*/
   int *which			/* In/Out: ptr to int indicating which  */
				/*     strlen is pointed at by valist   */
)

{
   int i, j, outlen;
   int null_term = FALSE;
   char *output_string;		/* the actual text address */
   int fortran_length;		/* the length Fortran claims */

   /* It's so simple this way: relegate all the crap to ptr/len.  Sigh.	*/

   output_string = v2_sfor2ptr(for_string);
   fortran_length=v2_sfor2len(for_string, argptr, nargs, argno, strno,
					valist, which);

/************************************************************************/

   if (fortran_length == 0)		/* whoops */
      fortran_length = *len;

   if (*len > 0)
      fortran_length = MIN(fortran_length, *len);

   if (fortran_length <= 0)		/* sanity check on the length */
      fortran_length = strlen(c_string)+1;

   *len = fortran_length;

/* Now that we have the length, copy the C string to the output. */

   for (j = 0; j < nelements; j++) {

      outlen = MIN((int) strlen(c_string), fortran_length); /* don't copy too much! */

      strncpy(output_string, c_string, outlen);

      if (null_term) {		/* Null-terminate if there's room */
         if (outlen < fortran_length)
            output_string[outlen] = '\0';
      }
      else {			/* Blank-fill the string */
         for (i=outlen; i<fortran_length; i++)
            output_string[i] = ' ';
      }

      output_string += fortran_length;
      c_string += maxlen;
   }

   /* return SUCCESS; */

}


text:
package scribe.file.path

import scribe.file.{FileWriter, LogFile}
import scribe.util.Time

import java.io.File

case class MaxSize(maxSizeInBytes: Long, separator: String) extends FileNamePart {
  private val threadLocal = new ThreadLocal[Int] {
    override def initialValue(): Int = 0
  }

  override def current(timeStamp: Long): String = {
    val i = threadLocal.get()
    if (i == 0) {
      ""
    } else {
      s"$separator$i"
    }
  }

  override def regex: String = s"([$separator]\\d*)?"

  override def before(writer: FileWriter): Unit = {
    val logFile = LogFile(writer)
    if (logFile.size >= maxSizeInBytes && logFile.file.exists()) {
      val path = fileFor(writer, 1)
      val lastModified = logFile.file.lastModified()
      rollPaths(writer)
      LogFile.move(logFile, path)
      path.setLastModified(lastModified)
    }
  }

  private def rollPaths(writer: FileWriter, i: Int = 1): Unit = {
    val path = fileFor(writer, i)
    if (path.exists()) {
      rollPaths(writer, i + 1)
      val nextPath = fileFor(writer, i + 1)
      val lastModified = path.lastModified()
      LogFile.copy(path, nextPath)
      LogFile.truncate(path)
      nextPath.setLastModified(lastModified)
    }
  }

  private def fileFor(writer: FileWriter, i: Int): File = {
    threadLocal.set(i)
    try {
      writer.pathBuilder.file(Time())
    } finally {
      threadLocal.remove()
    }
  }
}
object MaxSize {
  val OneHundredMeg: Long = 100000000L
}


text:
namespace Mappy
{
    using System;
    using System.IO;
    using System.Xml.Serialization;

    public static class MappySettings
    {
        private static readonly string ConfigFileLocation = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            @"ArmouredFish\Mappy\settings.xml");

        private static Configuration defaultSettings;

        public static Configuration Settings
        {
            get
            {
                if (defaultSettings == null)
                {
                    defaultSettings = LoadSettings();
                }

                return defaultSettings;
            }
        }

        public static void SaveSettings()
        {
            var dir = Path.GetDirectoryName(ConfigFileLocation);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            using (Stream st = File.Create(ConfigFileLocation))
            {
                var s = new XmlSerializer(typeof(Configuration));
                s.Serialize(st, Settings);
            }
        }

        private static Configuration LoadSettings()
        {
            var s = new XmlSerializer(typeof(Configuration));

            if (!File.Exists(ConfigFileLocation))
            {
                return new Configuration();
            }

            try
            {
                using (Stream st = File.OpenRead(ConfigFileLocation))
                {
                    return (Configuration)s.Deserialize(st);
                }
            }
            catch (InvalidOperationException)
            {
                // TODO: notify the user we failed to load their settings
                return new Configuration();
            }
        }
    }
}


text:
Also could be defined all allowed type for a property

```php
public static function allowedValues()
{
    return [
        'someApiParameter' => [
            'hello',
            'world'
        ],
    ];
}
```

## Configurator class

```php
use sensorario\resources\configurator;
use sensorario\resources\container;
use sensorario\resources\resource;

$configurator = new Configurator(
  'foo',
  new Container(
    'resources' => [
      'foo' => [
        'constraints' => [
          'allowed' => [
            'property_name',
          ],
          'allowedValues' => [
            'property_name' => [
              4,
              7,
            ],
          ],
        ],
      ],
    ]
  )
);

Resource::box([
  'property_name' => 7,
], $configurator);
```


text:
goog.provide('ol.renderer.dom.VectorLayer');

goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.vec.Mat4');
goog.require('ol.ViewHint');
goog.require('ol.dom');
goog.require('ol.extent');
goog.require('ol.layer.Vector');
goog.require('ol.render.Event');
goog.require('ol.render.EventType');
goog.require('ol.render.canvas.Immediate');
goog.require('ol.render.canvas.ReplayGroup');
goog.require('ol.renderer.dom.Layer');
goog.require('ol.renderer.vector');
goog.require('ol.vec.Mat4');

/**
 * @constructor
 * @extends {ol.renderer.dom.Layer}
 * @param {ol.layer.Vector} vectorLayer Vector layer.
 */
ol.renderer.dom.VectorLayer = function(vectorLayer) {

  /**
   * @private
   * @type {CanvasRenderingContext2D}
   */
  this.context_ = ol.dom.createCanvasContext2D();

  var target = this.context_.canvas;
  // Bootstrap sets the style max-width: 100% for all images, which breaks
  // prevents the image from being displayed in FireFox.  Workaround by
  // overriding the max-width style.
  target.style.maxWidth = 'none';
  target.style.position = 'absolute';

  goog.base(this, vectorLayer, target);

  /**
   * @private
   * @type {boolean}
   */
  this.dirty_ = false;

  /**
   * @private
   * @type {number}
   */
  this.renderedRevision_ = -1;

  /**
   * @private
   * @type {number}
   */
  this.renderedResolution_ = NaN;

  /**
   * @private
   * @type {ol.Extent}
   */
  this.renderedExtent_ = ol.extent.createEmpty();

  /**
   * @private
   * @type {function(ol.Feature, ol.Feature): number|null}
   */
  this.renderedRenderOrder_ = null;

  /**
   * @private
   * @type {ol.render.canvas.ReplayGroup}
   */
  this.replayGroup_ = null;

  /**
   * @private
   * @type {goog.vec.Mat4.Number}
   */
  this.transform_ = goog.vec.Mat4.createNumber();

  /**
   * @private
   * @type {goog.vec.Mat4.Number}
   */
  this.elementTransform_ = goog.vec.Mat4.createNumber();

};
goog.inherits(ol.renderer.dom.VectorLayer, ol.renderer.dom.Layer);

/**
 * @inheritDoc
 */
ol.renderer.dom.VectorLayer.prototype.composeFrame =
    function(frameState, layerState) {

  var vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer());
  goog.asserts.assertInstanceof(vectorLayer, ol.layer.Vector);

  var viewState = frameState.viewState;
  var viewCenter = viewState.center;
  var viewRotation = viewState.rotation;
  var viewResolution = viewState.resolution;
  var pixelRatio = frameState.pixelRatio;
  var viewWidth = frameState.size[0];
  var viewHeight = frameState.size[1];
  var imageWidth = viewWidth * pixelRatio;
  var imageHeight = viewHeight * pixelRatio;

  var transform = ol.vec.Mat4.makeTransform2D(this.transform_,
      pixelRatio * viewWidth / 2,
      pixelRatio * viewHeight / 2,
      pixelRatio / viewResolution,
      -pixelRatio / viewResolution,
      -viewRotation,
      -viewCenter[0], -viewCenter[1]);

  var context = this.context_;

  // Clear the canvas and set the correct size
  context.canvas.width = imageWidth;
  context.canvas.height = imageHeight;

  var elementTransform = ol.vec.Mat4.makeTransform2D(this.elementTransform_,
      0, 0,
      1 / pixelRatio, 1 / pixelRatio,
      0,
      -(imageWidth - viewWidth) / 2 * pixelRatio,
      -(imageHeight - viewHeight) / 2 * pixelRatio);
  ol.dom.transformElement2D(context.canvas, elementTransform, 6);

  this.dispatchEvent_(ol.render.EventType.PRECOMPOSE, frameState, transform);

  var replayGroup = this.replayGroup_;

  if (!goog.isNull(replayGroup) && !replayGroup.isEmpty()) {

    context.globalAlpha = layerState.opacity;
    replayGroup.replay(context, pixelRatio, transform, viewRotation,
        frameState.skippedFeatureUids);

    this.dispatchEvent_(ol.render.EventType.RENDER, frameState, transform);
  }

  this.dispatchEvent_(ol.render.EventType.POSTCOMPOSE, frameState, transform);
};

/**
 * @param {ol.render.EventType} type Event type.
 * @param {olx.FrameState} frameState Frame state.
 * @param {goog.vec.Mat4.Number} transform Transform.
 * @private
 */
ol.renderer.dom.VectorLayer.prototype.dispatchEvent_ =
    function(type, frameState, transform) {
  var context = this.context_;
  var layer = this.getLayer();
  if (layer.hasListener(type)) {
    var render = new ol.render.canvas.Immediate(
        context, frameState.pixelRatio, frameState.extent, transform,
        frameState.viewState.rotation);
    var event = new ol.render.Event(type, layer, render, null,
        frameState, context, null);
    layer.dispatchEvent(event);
    render.flush();
  }
};

/**
 * @inheritDoc
 */
ol.renderer.dom.VectorLayer.prototype.forEachFeatureAtCoordinate =
    function(coordinate, frameState, callback, thisArg) {
  if (goog.isNull(this.replayGroup_)) {
    return undefined;
  } else {
    var resolution = frameState.viewState.resolution;
    var rotation = frameState.viewState.rotation;
    var layer = this.getLayer();
    /** @type {Object.<string, boolean>} */
    var features = {};
    return this.replayGroup_.forEachFeatureAtCoordinate(coordinate,
        resolution, rotation, frameState.skippedFeatureUids,
        /**
         * @param {ol.Feature} feature Feature.
         * @return {?} Callback result.
         */
        function(feature) {
          goog.asserts.assert(goog.isDef(feature));
          var key = goog.getUid(feature).toString();
          if (!(key in features)) {
            features[key] = true;
            return callback.call(thisArg, feature, layer);
          }
        });
  }
};

/**
 * Handle changes in image style state.
 * @param {goog.events.Event} event Image style change event.
 * @private
 */
ol.renderer.dom.VectorLayer.prototype.handleStyleImageChange_ =
    function(event) {
  this.renderIfReadyAndVisible();
};

/**
 * @inheritDoc
 */
ol.renderer.dom.VectorLayer.prototype.prepareFrame =
    function(frameState, layerState) {

  var vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer());
  goog.asserts.assertInstanceof(vectorLayer, ol.layer.Vector);
  var vectorSource = vectorLayer.getSource();

  this.updateAttributions(
      frameState.attributions, vectorSource.getAttributions());
  this.updateLogos(frameState, vectorSource);

  if (!this.dirty_ && (!vectorLayer.getUpdateWhileAnimating() &&
      frameState.viewHints[ol.ViewHint.ANIMATING] ||
      frameState.viewHints[ol.ViewHint.INTERACTING])) {
    return true;
  }

  var frameStateExtent = frameState.extent;
  var viewState = frameState.viewState;
  var projection = viewState.projection;
  var resolution = viewState.resolution;
  var pixelRatio = frameState.pixelRatio;
  var vectorLayerRevision = vectorLayer.getRevision();
  var vectorLayerRenderBuffer = vectorLayer.getRenderBuffer();
  var vectorLayerRenderOrder = vectorLayer.getRenderOrder();

  if (!goog.isDef(vectorLayerRenderOrder)) {
    vectorLayerRenderOrder = ol.renderer.vector.defaultOrder;
  }

  var extent = ol.extent.buffer(frameStateExtent,
      vectorLayerRenderBuffer * resolution);

  if (!this.dirty_ &&
      this.renderedResolution_ == resolution &&
      this.renderedRevision_ == vectorLayerRevision &&
      this.renderedRenderOrder_ == vectorLayerRenderOrder &&
      ol.extent.containsExtent(this.renderedExtent_, extent)) {
    return true;
  }

  // FIXME dispose of old replayGroup in post render
  goog.dispose(this.replayGroup_);
  this.replayGroup_ = null;

  this.dirty_ = false;

  var replayGroup =
      new ol.render.canvas.ReplayGroup(
          ol.renderer.vector.getTolerance(resolution, pixelRatio), extent,
          resolution, vectorLayer.getRenderBuffer());
  vectorSource.loadFeatures(extent, resolution, projection);
  var renderFeature =
      /**
       * @param {ol.Feature} feature Feature.
       * @this {ol.renderer.dom.VectorLayer}
       */
      function(feature) {
    var styles;
    if (goog.isDef(feature.getStyleFunction())) {
      styles = feature.getStyleFunction().call(feature, resolution);
    } else if (goog.isDef(vectorLayer.getStyleFunction())) {
      styles = vectorLayer.getStyleFunction()(feature, resolution);
    }
    if (goog.isDefAndNotNull(styles)) {
      var dirty = this.renderFeature(
          feature, resolution, pixelRatio, styles, replayGroup);
      this.dirty_ = this.dirty_ || dirty;
    }
  };
  if (!goog.isNull(vectorLayerRenderOrder)) {
    /** @type {Array.<ol.Feature>} */
    var features = [];
    vectorSource.forEachFeatureInExtentAtResolution(extent, resolution,
        /**
         * @param {ol.Feature} feature Feature.
         */
        function(feature) {
          features.push(feature);
        }, this);
    goog.array.sort(features, vectorLayerRenderOrder);
    goog.array.forEach(features, renderFeature, this);
  } else {
    vectorSource.forEachFeatureInExtentAtResolution(
        extent, resolution, renderFeature, this);
  }
  replayGroup.finish();

  this.renderedResolution_ = resolution;
  this.renderedRevision_ = vectorLayerRevision;
  this.renderedRenderOrder_ = vectorLayerRenderOrder;
  this.renderedExtent_ = extent;
  this.replayGroup_ = replayGroup;

  return true;
};

/**
 * @param {ol.Feature} feature Feature.
 * @param {number} resolution Resolution.
 * @param {number} pixelRatio Pixel ratio.
 * @param {Array.<ol.style.Style>} styles Array of styles
 * @param {ol.render.canvas.ReplayGroup} replayGroup Replay group.
 * @return {boolean} `true` if an image is loading.
 */
ol.renderer.dom.VectorLayer.prototype.renderFeature =
    function(feature, resolution, pixelRatio, styles, replayGroup) {
  if (!goog.isDefAndNotNull(styles)) {
    return false;
  }
  var i, ii, loading = false;
  for (i = 0, ii = styles.length; i < ii; ++i) {
    loading = ol.renderer.vector.renderFeature(
        replayGroup, feature, styles[i],
        ol.renderer.vector.getSquaredTolerance(resolution, pixelRatio),
        this.handleStyleImageChange_, this) || loading;
  }
  return loading;
};


text:
package engine.handler;

import engine.entity.Entity;

public class EntityHandler {

	// ===========================================================
	// Fields
	// ===========================================================

	private double mVelocityX;
	private double mVelocityY;

	// ===========================================================
	// Constructor
	// ===========================================================

	public void onUpdate(final double delta, Entity pEntity) {

		if (mVelocityX != 0 || mVelocityY != 0) {
			pEntity.setPosition(pEntity.getX() + (mVelocityX/3) *  delta,
					pEntity.getY() + (mVelocityY/3) * delta);
		}

	}

	// ===========================================================
	// Getter/Setter
	// ===========================================================

	public double getVelocityX() {
		return mVelocityX;
	}

	public void setVelocityX(float mVelocityX) {
		this.mVelocityX = mVelocityX;
	}

	public double getVelocityY() {
		return mVelocityY;
	}

	public void setVelocityY(float mVelocityY) {
		this.mVelocityY = mVelocityY;
	}

}// end class


text:
/* What happens if we rewrite the previous program to allow values up to
 * but not including 1000 but neglect to change the arguments to setw
 * Rewrite the program to be more robust in the face of changes that
 * allow i to grow without adjusting the setw aguments*/

#include <iostream>
#include <ios>
#include <iomanip>

using std::cout;
using std::setw;
using std::endl;
using std::setprecision;

/* Function prototypes */
int digits(int n, int places);

int digits(int n, int places)
{
    /* initialize i to the number of desired decimals */
    int i = places;
    for (; n >= 1; i++) {
        n /= 10;
    }
    return i;
}

int main(int argc, const char *argv[])
{
    const double max = 99.9;
    /* Find the number of digits for highest base */
    int max_base = digits(max);
     /* Find the number of digits for highest square */
    int max_squared = digits(max * max);

    for (double i = 1.0; i <= max; i += 0.1) {
        /* add 2 for decimal point and one space for padding */
        cout << setprecision(max_base) << setw(max_base + 2) << i
            << setw(max_squared + 2) << setprecision(max_squared) << i * i << endl;
    }
    return 0;
}


text:
Please add to this list by submitting a pull request.

### Templates

* [re-frame-template](https://github.com/Day8/re-frame-template) - Generates the client side SPA

* [Luminus](http://www.luminusweb.net) - Generates SPA plus server side.

* [re-natal](https://github.com/drapanjanas/re-natal) - React Native apps.

* [Slush-reframe](https://github.com/kristianmandrup/slush-reframe) - A scaffolding generator for re-frame run using NodeJS. Should work wih re-frame `0.7.0` if used on a project started from the `0.7.0` version of re-frame-template.

* [Celibidache](https://github.com/velveteer/celibidache/) - An opinionated starter for re-frame applications using Boot. Based on re-frame `0.7.0`

### Examples and Applications Using re-frame

* [How to create decentralised apps with re-frame and Ethereum](https://medium.com/@matus.lestan/how-to-create-decentralised-apps-with-clojurescript-re-frame-and-ethereum-81de24d72ff5#.b9xh9xnis) - Tutorial with links to code and live example.

* [Elfeed-cljsrn](https://github.com/areina/elfeed-cljsrn) - A mobile client for [Elfeed](https://github.com/skeeto/elfeed) rss reader, built with React Native.

* [Memory Hole](https://github.com/yogthos/memory-hole) - A small issue tracking app written with Luminus and re-frame.

* [Crossed](https://github.com/velveteer/crossed/) - A multiplayer crossword puzzle generator. Based on re-frame `0.7.0`

* [imperimetric](https://github.com/Dexterminator/imperimetric) - Webapp for converting texts with some system of measurement to another, such as imperial to metric.

* [Brave Clojure Open Source](https://github.com/braveclojure/open-source) A site using re-frame, liberator, boot and more to display active github projects that powers [http://open-source.braveclojure.com](http://open-source.braveclojure.com). Based on re-frame `0.6.0`

* [flux-challenge with re-frame](https://github.com/staltz/flux-challenge/tree/master/submissions/jelz) -  flux-challenge is "a frontend challenge to test UI architectures and solutions". This is a ClojureScript + re-frame version. Based on re-frame `0.5.0`

* [fractalify](https://github.com/madvas/fractalify/)  -
  An entertainment and educational webapp for creating & sharing fractal images that powers [fractalify.com](http://fractalify.com). Based on re-frame `0.4.1`

* [Angular Phonecat tutorial in re-frame](http://dhruvp.github.io/2015/03/07/re-frame/) - A detailed step-by-step tutorial that ports the Angular Phonecat tutorial to re-frame. Based on re-frame `0.2.0`

* [Braid](https://github.com/braidchat/braid) - A new approach to group chat, designed around conversations and tags instead of rooms.

### Effect and CoEffect Handlers

* [async-flow-fx](https://github.com/Day8/re-frame-async-flow-fx) - manage a boot process dominated by async
* [http-fx](https://github.com/Day8/re-frame-http-fx) - performing Ajax tasks (via cljs-ajax)
* [re-frame-forward-events-fx](https://github.com/Day8/re-frame-forward-events-fx) - slightly exotic
* [cookie-fx](https://github.com/SMX-LTD/re-frame-cookie-fx) - set and get cookies
* [document-fx](https://github.com/SMX-LTD/re-frame-document-fx) - set and get on `js/document` attributes
* [re-frame-youtube-fx](https://github.com/micmarsh/re-frame-youtube-fx) - YouTube iframe API wrapper
* [re-frame-web3-fx](https://github.com/madvas/re-frame-web3-fx) - Ethereum Web3 API
* [re-frame-google-analytics-fx](https://github.com/madvas/re-frame-google-analytics-fx) - Google Analytics API

### Routing

* (Bidirectional using Silk and Pushy)[https://pupeno.com/2015/08/18/no-hashes-bidirectional-routing-in-re-frame-with-silk-and-pushy/]

### Tools, Techniques & Libraries

* [re-frame-undo](https://github.com/Day8/re-frame-undo) - An undo library for re-frame
* Animation using `react-flip-move` - http://www.upgradingdave.com/blog/posts/2016-12-17-permutation.html
* [re-frisk](https://github.com/flexsurfer/re-frisk) - A library for visualizing re-frame data and events.
* [re-thread](https://github.com/yetanalytics/re-thread) - A library for running re-frame applications in Web Workers.
* [re-frame-datatable](https://github.com/kishanov/re-frame-datatable) - DataTable UI component built for use with re-frame.
* [Stately: State Machines](https://github.com/nodename/stately) also https://www.youtube.com/watch?v=klqorRUPluw
* [re-frame-test](https://github.com/Day8/re-frame-test) - Integration Testing (not documented)
* [re-learn](https://github.com/oliyh/re-learn) - Data driven tutorials for educating users of your reagent / re-frame app, built with re-frame

### Videos

* [re-frame your ClojureScript applications](https://youtu.be/cDzjlx6otCU) - re-frame presentation given at Clojure/Conj 2016

* [A Video Tour of the Source Code of Ninja Tools](https://carouselapps.com/2015/12/02/tour-of-the-source-code-of-ninja-tools/)

### Server Side Rendering

* [Prerenderer](https://github.com/pupeno/prerenderer) - Server pre-rendering library using NodeJS that works with re-frame `0.6.0` (later versions untested)
   Rationale [Part 1](https://carouselapps.com/2015/09/14/isomorphic-clojurescriptjavascript-for-pre-rendering-single-page-applications-part-2/)
   [Part 2](https://carouselapps.com/2015/09/14/isomorphic-clojurescriptjavascript-for-pre-rendering-single-page-applications-part-2/)
   [Part 3](https://pupeno.com/2015/10/02/isomorphic-javascript-with-clojurescript-for-pre-rendering-single-page-applications-part-3/)
   [Release Announcement](https://pupeno.com/2015/12/13/prerenderer-0-2-0-released/)

* [Server Side Rendering with re-frame](http://davidtanzer.net/server_side_rendering_with_re_frame) - Blog post on rendering re-frame views with Clojure.

* [Rendering Reagent on the Server Using Hiccup](http://yogthos.net/posts/2015-11-24-Serverside-Reagent.html)- Blog post on rendering Reagent with Clojure.

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- END doctoc generated TOC please keep comment here to allow auto update -->


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <link rel="SHORTCUT ICON" href="../../../img/clover.ico" />

  <title>EasyMock 3.0</title>

                    Clover Test Report - EasyMock 3.0
Coverage timestamp: sam. mai 8 2010 14:37:27 CEST

                            Overview
                            Package
                            File
                            Test

                            FRAMES
                            NO FRAMES
                            SHOW HELP

    Test
        Unique Coverage
        Status
    Start time
    Time (seconds)
    Message

        equalsAfterActivation

        0%

                          1
    PASS

        8 mai 14:37:25

        0.0

        Target Class
                Unique
                Coverage contributed by equalsAfterActivation.

            org.easymock.internal.ClassExtensionHelper
              org.easymock.internal.ClassExtensionHelper

                                        0.0

            0.42857143
            42,9%

            org.easymock.internal.MockInvocationHandler
              org.easymock.internal.MockInvocationHandler

                                        0.0

            0.14285715
            14,3%

            org.easymock.internal.LastControl
              org.easymock.internal.LastControl

                                        0.0

            0.12676056
            12,7%

            org.easymock.internal.ObjectMethodsFilter
              org.easymock.internal.ObjectMethodsFilter

                                        0.0

            0.115384616
            11,5%

            org.easymock.internal.MocksControl
              org.easymock.internal.MocksControl

                                        0.0

            0.03125
            3,1%

            org.easymock.internal.RecordState
              org.easymock.internal.RecordState

                                        0.0

            0.03125
            3,1%

            org.easymock.internal.ReplayState
              org.easymock.internal.ReplayState

                                        0.0

            0.030303031
            3%

            org.easymock.EasyMock
              org.easymock.EasyMock

                                        0.0

            0.012106538
            1,2%

 	Report generated by Clover Code Coverage v3.0.1
sam. mai 8 2010 14:37:33 CEST.
 	 	Clover: Open Source License registered to EasyMock .


text:
'use strict'

var FunctionExpression = require('../expressions/FunctionExpression.js')
  , TypeParameter = require('../types/TypeParameter.js')
  , ValueExpression = require('../expressions/ValueExpression.js')
  , MatchExpression = require('../expressions/MatchExpression.js')
  , RefinementExpression = require('../expressions/RefinementExpression.js')
  , Type = require('../types/Type.js')
  , FunctionType = require('../types/FunctionType.js')
  , Expression = require('../expressions/Expression.js')
  , util = require('../util.js')
  , verbosityLevels = require('../verbosityLevels.js')
  , traversalUtil = require('./traversalUtil.js')
  , UniqueType = require('../types/UniqueType.js')
  , tap = require('../tap.js')
  , typeUtil = require('../types/typeUtil.js')

function Solver(maxAstNodes, ignoredTypes, insertFunctionExpressions, options) {
  this.insertFunctionExpressions = insertFunctionExpressions
  this.maxAstNodes = maxAstNodes
  this.unexploredPaths = 0
  this.ignoredTypes = ignoredTypes
  this.options = options
}

function checkLen(len) {
  if(isNaN(len)) throw new Error('len isNaN')
  if(len + 1 > this.maxAstNodes) {
    this.unexploredPaths++
    return false
  }
  return true
}

Solver.prototype.traverse = function(state) {
  return traverseExpression.call(this, state)
}

function addFunctionArgumentsAsExpressions(state) {

  var node = state.node
    , varCounter = state.varCounter
    , expressions = state.expressions

  // Add the function's arguments as candidates expressions:
  for(var p = 0; p < node.bindingTypes.length; p++) {
    var argType = typeUtil.instantiateTypeParameters(node.bindingTypes[p])
      , argIndex = varCounter++

    //if(argType instanceof TypeParameter)
    //  argType = new UniqueType(argType.name)

    var argValue = new ValueExpression('arg' + argIndex)
    argValue.returnsResolved(argType)
    argValue.as('arg' + argIndex)
    expressions = {
      head: argValue,
      tail: expressions
    }
  }

  return expressions
}

function traverseExpression(state) {

  var self = this
    , parentExpressions = state.expressions
    , parentTypes = state.types
    , parentVarCounter = state.varCounter
    , node = state.node
    , parent = state.parent
    , typeFilterList = state.typeFilterList
    , parentNode = state.parentNode
    , parentExpr = parentNode.expr
    , parentId = parentNode.id
    , childIndex = state.childIndex
    , len = state.len
    , cont = state.cont
    , expressions = parentExpressions
    , types = parentTypes
    , varCounter = parentVarCounter
    , children = node.args
    , id = len + 1

  if(!checkLen.call(self, len)) return null

  if(node instanceof FunctionExpression) {
    var boundExpressions = addFunctionArgumentsAsExpressions(state)
    varCounter += expressions ?
      util.listIndexOf(boundExpressions, expressions.head) :
      util.listCount(boundExpressions)
    expressions = boundExpressions
  }

  var expressionNode = {
    expr: node,
    id: id,
    parentId: parentId,
    varCount: parentVarCounter
  }

  function traverseBranch(
    index, branchTraversal, branchLen, branchTypeFilterList) {

    if(index >= node.args.length) {
      // Branch termination means typeFilter isn't propagated.
      return cont(
        branchTraversal, branchLen, branchTypeFilterList, expressions)
    }

    // Don't apply type filters across branches of MatchExpressions
    var childTypeFilters = node instanceof MatchExpression ?
      util.listFindLastValue(branchTypeFilterList, id) :
      util.listFindValue(branchTypeFilterList, id)

    var child = node.args[index].type.filterType(childTypeFilters)

    return traverseType.call(self, {
      types: types,
      expressions: expressions,
      varCounter: varCounter,
      node: child,
      parent: branchTraversal,
      typeFilterList: branchTypeFilterList,
      parentNode: expressionNode,
      childIndex: index,
      len: branchLen,
      cont: function onBranch(termTraversal, termLen, termTypeFilterList) {
        return traverseBranch(
          index + 1,
          termTraversal,
          termLen,
          termTypeFilterList)
      }
    })
  }

  var initialBranchTraversal = { head: expressionNode, tail: parent }

  return traverseBranch(0, initialBranchTraversal, len + 1,
    typeFilterList) // No typeFilter for first child.
}

function refineType(state, expressions, varCounter) {

  var parentNode = state.parentNode
    , parent = state.parent
    , childIndex = state.childIndex
    , parentId = parentNode.id
    , unionType = parentNode.expr.args[0].type
    , matchedType = unionType.children[childIndex - 1]

  var siblingList = util.listFilter(parent, function(candidate) {
    return candidate.parentId === parentId
  })

  var bindExpression = util.listLast(siblingList).expr
  if(bindExpression instanceof ValueExpression) {
    var removed = util.listRemoveFirst(expressions, bindExpression)
    expressions = removed
  }

  var refinementValue = new RefinementExpression('refinement' + varCounter)
  refinementValue.source = bindExpression
  refinementValue.returnsResolved(
    typeUtil.instantiateTypeParameters(matchedType))
  refinementValue.as('refinement' + varCounter)

  expressions = {
    head: refinementValue,
    tail: expressions
  }

  return expressions
}

function traverseType(state) {

  var self = this
    , parentExpressions = state.expressions
    , parentTypes = state.types
    , parentVarCounter = state.varCounter
    , node = state.node
    , parent = state.parent
    , typeFilterList = state.typeFilterList
    , parentNode = state.parentNode
    , parentExpr = parentNode.expr
    , parentId = parentNode.id
    , childIndex = state.childIndex
    , len = state.len
    , cont = state.cont
    , expressions = parentExpressions
    , types = parentTypes
    , varCounter = parentVarCounter

  if(!checkLen.call(self, len)) return null

  if(parentExpr instanceof MatchExpression && childIndex) {
    var refinedTypeExpressions = refineType(state, expressions, varCounter)
    varCounter += util.listIndexOf(expressions, refinedTypeExpressions.head)
    expressions = refinedTypeExpressions
  }

  if(self.options.searchPath) {
    var traversalStr = traversalUtil.toString(parent)
    if(traversalStr.indexOf(self.options.searchPath) < 0 &&
      self.options.searchPath.indexOf(traversalStr) < 0) {
      return
    }
  }

  if(self.options.verbosity >= verbosityLevels.traversal) {
    tap.comment()
    tap.comment('~ traversing ~')
    tap.comment(traversalUtil.toString(parent) || 'nil')
  }

  // Find expressions that match type.
  var candidate = expressions
    , match = false

  if(self.options.verbosity >= verbosityLevels.expression)
    tap.comment('expression ' + parentExpr + ' (childIndex ' + childIndex + ')')

  if(self.insertFunctionExpressions && node instanceof FunctionType) {
    // create new functionExpression
    candidate = { head: new FunctionExpression('fn', node), tail: candidate }
    match = true
  }

  while(candidate) {

    var filterTypeResult = filterCandidateByType.call(
      self, node, candidate, parentId, typeFilterList)

    if(filterTypeResult) {

      var childExpression = filterTypeResult.childExpression
        , childTypeFilterList = filterTypeResult.childTypeFilterList

      if(!childExpression.allowParent(parentExpr, childIndex)) {
        if(childExpression.constraintsFailSilently)
          match = true

        if(self.options.verbosity >= verbosityLevels.expression) {
          tap.comment('  candidate: ' + candidate.head,
            '- child forbade parent')
        }
      } else if (!parentExpr.allowChild(childExpression, childIndex)) {

        if(parentExpr.constraintsFailSilently)
          match = true

        if(self.options.verbosity >= verbosityLevels.expression) {
          tap.comment('  candidate: ' + candidate.head,
            '- parent forbade child')
        }

      } else {

        match = true

        if(self.options.verbosity >= verbosityLevels.expression) {
          tap.comment('  candidate: ' + candidate.head, '- yes')
        }

        var traversal = traverseExpression.call(self, {
          expressions: expressions,
          types: types,
          varCounter: varCounter,
          node: childExpression,
          parent: parent,
          // Pass typeFilters down through types:
          typeFilterList: childTypeFilterList,
          parentNode: parentNode,
          childIndex: childIndex,
          len: len,
          cont: cont
        })
        if(traversal) return traversal
      }
    } else if(self.options.verbosity >= verbosityLevels.expression) {
      tap.comment('  candidate: ' + candidate.head, '- no')
var candidateStr = 'arg1 : #element -> String'
if(candidateStr === candidate.head.toString() && node+''==="'element -> String") {
  tap.comment('    why not? node: ' + node)
}
    }

    candidate = candidate.tail
  }

  // Handle match found but no solution:
  if(match) return null

  // Log a failed match:
  for(var i = 0; i < this.ignoredTypes.length; i++) {
    if(!this.ignoredTypes[i].containsType(node, {})) continue
    if(self.options.verbosity >= verbosityLevels.expression)
      tap.comment('ignoring traversal for ' + node)
    return
  }
  tap.comment('problematic traversal:')
  tap.comment(traversalUtil.toString(parent))
  tap.comment('available expressions:')
  util.listForEach(expressions, function(expr) {
    tap.comment('  ' + expr)
  })
  throw new Error('Found no expression that returns type ' + node)
}

function filterCandidateByType(node, candidate, parentId, typeFilterList) {

  if(candidate.head.type === node) {
    return {
      childExpression: candidate.head,
      childTypeFilterList: typeFilterList
    }
  }

  // The child type should always be a proper or improper superset
  // of the parent expression's type.
  var typeFilters = {}

  if(node.containsType(candidate.head.type, typeFilters)) {
    return {
      childExpression: candidate.head,
      childTypeFilterList: util.listAddKeyValue(
        typeFilterList, parentId, typeFilters)
    }
  }

  // There is still a case we need to check.
  // The expression's type can be a superset of the parent's type
  // before filtering, but after filtering it may still be
  // a proper or improper subset of the parent.

  // Example:
  // Let's look at the ternary expression:
  // ?: : 'a takes (Boolean, 'a, 'a)
  // Let's say we have a specification that returns a Number.
  // So Number is the node and "?:" is the candidate.head.
  // The candidate.head type is 'a
  // We should be able to use a ternary expression to return a Number.
  // Number is not a superset of 'a.
  // 'a is a superset of Number.
  // After we find that 'a is a superset of Number,
  // we have a typeFilter that maps 'a to Number.
  // After type filtering, the ternary operator looks like:
  // ?: : Number takes (Boolean, Number, Number)
  // Now the expression type is Number
  // This a strict subset of 'node', so this is a valid match.

  // First check if the expression result's type is
  // a proper or improper superset of the parent type.
  var expressionContainsParentType =
    candidate.head.type.containsType(node, typeFilters = {})
  if(!expressionContainsParentType) {
    if(this.options.verbosity >= verbosityLevels.diagnostic)
      tap.comment(
        '  expression ' + candidate.head +
        ' does not contain parent type ' + node)
    return null
  }

  // We know that the expression is a proper/improper superset
  // of the parent type.
  // This may be because of a typeParameter filter.
  // The filtered expression's type
  // is a proper/improper subset of the parent's type.
  // We can now traverse the AST with this type.

  var filteredChildExpression = candidate.head.filterType(typeFilters)

  // We need to check that the parent type
  // contains the type-filtered-expression's result type.
  // (Note that we just pass new typeFilters here.
  // This is because the filteredChildExpression.type already
  // has the type filtered applied.  We don't want to apply them again.
  // Otherwise we could run into the following case:
  //   'a contains Array<'a> is true
  //   typeFilters are 'a: Array<'a>
  // Reapplying the type filter would generate Array<Array<'a>>,
  // which would be incorrect.)
  var parentContainsFilteredChild = node.containsType(
    filteredChildExpression.type, {})
  if(parentContainsFilteredChild) {
    return {
      childExpression: filteredChildExpression,
      childTypeFilterList: util.listAddKeyValue(
        typeFilterList, parentId, typeFilters)
    }
  }

  if(this.options.verbosity >= verbosityLevels.diagnostic)
    tap.comment('  parent does not contain filtered child')
  return null
}

module.exports = Solver


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34014
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Updater.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("ftp://arma2.wogames.info/ARMA2/Utilities/WOG_Launcher/Resources/AppManifest.xml")]
        public string RemoteManifest {
            get {
                return ((string)(this["RemoteManifest"]));
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Resources\\AppManifest.xml")]
        public string LocalManifest {
            get {
                return ((string)(this["LocalManifest"]));
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Client.exe")]
        public string UpdateClientExecutablePath {
            get {
                return ((string)(this["UpdateClientExecutablePath"]));
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("2")]
        public int RetryAttempts {
            get {
                return ((int)(this["RetryAttempts"]));
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Client.exe")]
        public string UpdateClientProcessName {
            get {
                return ((string)(this["UpdateClientProcessName"]));
            }
        }
    }
}


text:
module ActiveSupport #:nodoc:
  module CoreExtensions #:nodoc:
    module Range #:nodoc:
      # Getting dates in different convenient string representations and other objects
      module Conversions
        DATE_FORMATS = {
          :db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
        }

        def self.included(klass) #:nodoc:
          klass.send(:alias_method, :to_default_s, :to_s)
          klass.send(:alias_method, :to_s, :to_formatted_s)
        end

        def to_formatted_s(format = :default)
          DATE_FORMATS[format] ? DATE_FORMATS[format].call(first, last) : to_default_s
        end
      end
    end
  end
end


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

<menu xmlns:android="http://schemas.android.com/apk/res/android">
	<item
		android:id="@id/action_bar_history_clear"
		android:orderInCategory="0"
		android:icon="@drawable/ic_action_delete"
		android:showAsAction="always" />
</menu>


text:
using Newtonsoft.Json;
using System.Collections.Generic;
using ZKWebStandard.Extensions;

namespace ZKWeb.Plugins.Common.Base.src.UIComponents.Forms.Attributes {
	/// <summary>
	/// 富文本编辑器的属性
	/// 这个属性需要其他插件实现,请注意引用实现的插件
	/// </summary>
	public class RichTextEditorAttribute : FormFieldAttribute {
		/// <summary>
		/// 自定义配置
		/// </summary>
		public Dictionary<string, object> Config { get; set; }
		/// <summary>
		/// 图片管理器地址,指定时可以启用图片上传功能
		/// </summary>
		public string ImageBrowserUrl {
			get { return Config.GetOrDefault<string>("imageBrowserUrl"); }
			set { Config["imageBrowserUrl"] = value; }
		}

		/// <summary>
		/// 初始化
		/// </summary>
		/// <param name="name">字段名称</param>
		/// <param name="config">自定义配置,格式是Json</param>
		public RichTextEditorAttribute(string name, string config = null) {
			Name = name;
			Config = JsonConvert.DeserializeObject<Dictionary<string, object>>(config ?? "{}");
		}
	}
}


text:
'use strict';

import {createDecorator, ServiceIdentifier} from 'vs/platform/instantiation/common/instantiation';
import {ListenerUnbind, ListenerCallback, IEventEmitter, IEmitterEvent} from 'vs/base/common/eventEmitter';
import EditorCommon = require('vs/editor/common/editorCommon');
import {EventProvider} from 'vs/base/common/eventProvider';
import URI from 'vs/base/common/uri';
import {IDisposable} from 'vs/base/common/lifecycle';

// Resource Service

export var ResourceEvents = {
	ADDED: 'resource.added',
	REMOVED: 'resource.removed',
	CHANGED: 'resource.changed'
};

export interface IResourceAddedEvent {
	url: URI;
	addedElement: EditorCommon.IMirrorModel;
}

export interface IResourceRemovedEvent {
	url: URI;
	removedElement: EditorCommon.IMirrorModel;
}

export interface IResourceChangedEvent {
	url: URI;
	originalEvents: IEmitterEvent[];
}

export var IResourceService = createDecorator<IResourceService>('resourceService');

export interface IResourceService {
	serviceId: ServiceIdentifier<any>;
	insert(url: URI, element: EditorCommon.IMirrorModel): void;
	get(url: URI): EditorCommon.IMirrorModel;
	all(): EditorCommon.IMirrorModel[];
	contains(url: URI): boolean;
	remove(url: URI): void;
	addListener_(eventType: 'resource.added', listener: (event: IResourceAddedEvent) => void): ListenerUnbind;
	addListener_(eventType: 'resource.removed', listener: (event: IResourceRemovedEvent) => void): ListenerUnbind;
	addListener_(eventType: 'resource.changed', listener: (event: IResourceChangedEvent) => void): ListenerUnbind;
	addListener_(eventType: string, listener: ListenerCallback): ListenerUnbind;
	addListener2_(eventType: 'resource.added', listener: (event: IResourceAddedEvent) => void): IDisposable;
	addListener2_(eventType: 'resource.removed', listener: (event: IResourceRemovedEvent) => void): IDisposable;
	addListener2_(eventType: 'resource.changed', listener: (event: IResourceChangedEvent) => void): IDisposable;
	addListener2_(eventType: string, listener: ListenerCallback): IDisposable;
}


text:
<?php

declare(strict_types=1);

namespace OpenTelemetry\SDK\Metrics\Stream;

use OpenTelemetry\SDK\Common\Attribute\AttributesInterface;

/**
 * @internal
 *
 * @template T
 */
final class Metric
{

    /**
     * @var array<AttributesInterface>
     */
    public array $attributes;
    /**
     * @var array<T>
     */
    public array $summaries;
    public int $timestamp;
    public int $revision;
    /**
     * @param array<AttributesInterface> $attributes
     * @param array<T> $summaries
     */
    public function __construct(array $attributes, array $summaries, int $timestamp, int $revision)
    {
        $this->attributes = $attributes;
        $this->summaries = $summaries;
        $this->timestamp = $timestamp;
        $this->revision = $revision;
    }
}


text:
title: A Little Bit of Everything
date: 2012-07-30 00:00:00 -06:00
categories:
- whats-blooming
layout: post
blog-banner: whats-blooming-now-summer.jpg
post-date: July 30, 2012
post-time: 12:52 PM
blog-image: wbn-default.jpg
---

It is the end of July and there are still plenty of flowers to see. Some plants are still flowering, some are re-flowering and other flowers are new.

The great thing about re-visiting Red Butte Garden is the constant change of color and variety of blossoms. Each time you visit is like your first time.

Echeveria     Echeveria subrigida 'Fire and Ice'

Slipper Spurge    Pedilanthus macrocarpus

These two unique succulents can be found in the flower bed at the bottom of the steps before you enter the Visitor Center

Hibiscus   Hibiscus  'Kopper King'

With flowers larger than a dinner plate, this giant-flowered Hibiscus really makes a statement. This specimen can be found growing near the Water Pavilion

Sunburst St. Johnswort    Hypericum frondosum   'Sunburst'

Look for this handsome shrub growing on south perimeter of the Four Seasons Garden

Bergamot     Monarda didyma  'Raspberry Wine'

This hummingbird magnet, found in our Herb Garden, has fragrant foliage that can be made into a great tea.

Heavy Metal Switch Grass     Panicum virgatum   'Heavy Metal'

The next time you walk by a tall grass, take a close look. This specimen is producing colorful stamens and stigmas.

Coneflower    Rudbeckia   'Herbstonne''

Tall, bright yellow flowers like this one make a great backdrop for lower-growing shrubs and perennials. This coneflower grows on the north and south berms of the Four Seasons Garden

 Photography by Sarah Anderson


text:
package org.ecloudmanager.service.deployment.geolite;

import org.apache.commons.lang3.StringUtils;

public class GeolocationRecord {
    private String geoid;
    private String country;
    private String subdivision;
    private String city;
    private String label;

    public GeolocationRecord() {
    }

    public GeolocationRecord(String geoid, String country, String subdivision, String city, String label) {
        this.geoid = geoid;
        this.label = label;
        this.country = country;
        this.subdivision = subdivision;
        this.city = city;
    }

    public GeolocationRecordType getType() {
        return StringUtils.isEmpty(getSubdivision()) && StringUtils.isEmpty(getCity()) ? GeolocationRecordType.COUNTRY : GeolocationRecordType.CITY;
    }

    public String getGeoid() {
        return geoid;
    }

    public void setGeoid(String geoid) {
        this.geoid = geoid;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getSubdivision() {
        return subdivision;
    }

    public void setSubdivision(String subdivision) {
        this.subdivision = subdivision;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}


text:
#ifndef ARM_COMPUTE_TEST_SIMPLE_TENSOR_H
#define ARM_COMPUTE_TEST_SIMPLE_TENSOR_H

#include "arm_compute/core/TensorShape.h"
#include "arm_compute/core/Types.h"
#include "arm_compute/core/Utils.h"
#include "tests/IAccessor.h"
#include "tests/Utils.h"

#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <stdexcept>
#include <utility>

namespace arm_compute
{
namespace test
{
class RawTensor;

/** Simple tensor object that stores elements in a consecutive chunk of memory.
 *
 * It can be created by either loading an image from a file which also
 * initialises the content of the tensor or by explcitly specifying the size.
 * The latter leaves the content uninitialised.
 *
 * Furthermore, the class provides methods to convert the tensor's values into
 * different image format.
 */
template <typename T>
class SimpleTensor : public IAccessor
{
public:
    /** Create an uninitialised tensor. */
    SimpleTensor() = default;

    /** Create an uninitialised tensor of the given @p shape and @p format.
     *
     * @param[in] shape  Shape of the new raw tensor.
     * @param[in] format Format of the new raw tensor.
     */
    SimpleTensor(TensorShape shape, Format format);

    /** Create an uninitialised tensor of the given @p shape and @p data type.
     *
     * @param[in] shape             Shape of the new raw tensor.
     * @param[in] data_type         Data type of the new raw tensor.
     * @param[in] num_channels      (Optional) Number of channels (default = 1).
     * @param[in] quantization_info (Optional) Quantization info for asymmetric quantization (default = empty).
     * @param[in] data_layout       (Optional) Data layout of the tensor (default = NCHW).
     */
    SimpleTensor(TensorShape shape, DataType data_type,
                 int              num_channels      = 1,
                 QuantizationInfo quantization_info = QuantizationInfo(),
                 DataLayout       data_layout       = DataLayout::NCHW);

    /** Create a deep copy of the given @p tensor.
     *
     * @param[in] tensor To be copied tensor.
     */
    SimpleTensor(const SimpleTensor &tensor);

    /** Create a deep copy of the given @p tensor.
     *
     * @param[in] tensor To be copied tensor.
     *
     * @return a copy of the given tensor.
     */
    SimpleTensor &operator=(SimpleTensor tensor);
    /** Allow instances of this class to be move constructed */
    SimpleTensor(SimpleTensor &&) = default;
    /** Default destructor. */
    ~SimpleTensor() = default;

    /** Tensor value type */
    using value_type = T;
    /** Tensor buffer pointer type */
    using Buffer = std::unique_ptr<value_type[]>;

    friend class RawTensor;

    /** Return value at @p offset in the buffer.
     *
     * @param[in] offset Offset within the buffer.
     *
     * @return value in the buffer.
     */
    T &operator[](size_t offset);

    /** Return constant value at @p offset in the buffer.
     *
     * @param[in] offset Offset within the buffer.
     *
     * @return constant value in the buffer.
     */
    const T &operator[](size_t offset) const;

    /** Shape of the tensor.
     *
     * @return the shape of the tensor.
     */
    TensorShape shape() const override;
    /** Size of each element in the tensor in bytes.
     *
     * @return the size of each element in the tensor in bytes.
     */
    size_t element_size() const override;
    /** Total size of the tensor in bytes.
     *
     * @return the total size of the tensor in bytes.
     */
    size_t size() const override;
    /** Image format of the tensor.
     *
     * @return the format of the tensor.
     */
    Format format() const override;
    /** Data layout of the tensor.
     *
     * @return the data layout of the tensor.
     */
    DataLayout data_layout() const override;
    /** Data type of the tensor.
     *
     * @return the data type of the tensor.
     */
    DataType data_type() const override;
    /** Number of channels of the tensor.
     *
     * @return the number of channels of the tensor.
     */
    int num_channels() const override;
    /** Number of elements of the tensor.
     *
     * @return the number of elements of the tensor.
     */
    int num_elements() const override;
    /** Available padding around the tensor.
     *
     * @return the available padding around the tensor.
     */
    PaddingSize padding() const override;
    /** Quantization info in case of asymmetric quantized type
     *
     * @return
     */
    QuantizationInfo quantization_info() const override;

    /** Constant pointer to the underlying buffer.
     *
     * @return a constant pointer to the data.
     */
    const T *data() const;

    /** Pointer to the underlying buffer.
     *
     * @return a pointer to the data.
     */
    T *data();

    /** Read only access to the specified element.
     *
     * @param[in] coord Coordinates of the desired element.
     *
     * @return A pointer to the desired element.
     */
    const void *operator()(const Coordinates &coord) const override;

    /** Access to the specified element.
     *
     * @param[in] coord Coordinates of the desired element.
     *
     * @return A pointer to the desired element.
     */
    void *operator()(const Coordinates &coord) override;

    /** Swaps the content of the provided tensors.
     *
     * @param[in, out] tensor1 Tensor to be swapped.
     * @param[in, out] tensor2 Tensor to be swapped.
     */
    template <typename U>
    friend void swap(SimpleTensor<U> &tensor1, SimpleTensor<U> &tensor2);

protected:
    Buffer           _buffer{ nullptr };
    TensorShape      _shape{};
    Format           _format{ Format::UNKNOWN };
    DataType         _data_type{ DataType::UNKNOWN };
    int              _num_channels{ 0 };
    QuantizationInfo _quantization_info{};
    DataLayout       _data_layout{ DataLayout::UNKNOWN };
};

template <typename T1, typename T2>
SimpleTensor<T1> copy_tensor(const SimpleTensor<T2> &tensor)
{
    SimpleTensor<T1> st(tensor.shape(), tensor.data_type(),
                        tensor.num_channels(),
                        tensor.quantization_info(),
                        tensor.data_layout());
    for(size_t n = 0; n < size_t(st.num_elements()); n++)
    {
        st.data()[n] = static_cast<T1>(tensor.data()[n]);
    }
    return st;
}

template <typename T1, typename T2, typename std::enable_if<std::is_same<T1, T2>::value, int>::type = 0>
SimpleTensor<T1> copy_tensor(const SimpleTensor<half> &tensor)
{
    SimpleTensor<T1> st(tensor.shape(), tensor.data_type(),
                        tensor.num_channels(),
                        tensor.quantization_info(),
                        tensor.data_layout());
    memcpy((void *)st.data(), (const void *)tensor.data(), size_t(st.num_elements() * sizeof(T1)));
    return st;
}

template < typename T1, typename T2, typename std::enable_if < (std::is_same<T1, half>::value || std::is_same<T2, half>::value), int >::type = 0 >
SimpleTensor<T1> copy_tensor(const SimpleTensor<half> &tensor)
{
    SimpleTensor<T1> st(tensor.shape(), tensor.data_type(),
                        tensor.num_channels(),
                        tensor.quantization_info(),
                        tensor.data_layout());
    for(size_t n = 0; n < size_t(st.num_elements()); n++)
    {
        st.data()[n] = half_float::detail::half_cast<T1, T2>(tensor.data()[n]);
    }
    return st;
}

template <typename T>
SimpleTensor<T>::SimpleTensor(TensorShape shape, Format format)
    : _buffer(nullptr),
      _shape(shape),
      _format(format),
      _quantization_info(),
      _data_layout(DataLayout::NCHW)
{
    _num_channels = num_channels();
    _buffer       = std::make_unique<T[]>(num_elements() * _num_channels);
}

template <typename T>
SimpleTensor<T>::SimpleTensor(TensorShape shape, DataType data_type, int num_channels, QuantizationInfo quantization_info, DataLayout data_layout)
    : _buffer(nullptr),
      _shape(shape),
      _data_type(data_type),
      _num_channels(num_channels),
      _quantization_info(quantization_info),
      _data_layout(data_layout)
{
    _buffer = std::make_unique<T[]>(this->_shape.total_size() * _num_channels);
}

template <typename T>
SimpleTensor<T>::SimpleTensor(const SimpleTensor &tensor)
    : _buffer(nullptr),
      _shape(tensor.shape()),
      _format(tensor.format()),
      _data_type(tensor.data_type()),
      _num_channels(tensor.num_channels()),
      _quantization_info(tensor.quantization_info()),
      _data_layout(tensor.data_layout())
{
    _buffer = std::make_unique<T[]>(tensor.num_elements() * _num_channels);
    std::copy_n(tensor.data(), this->_shape.total_size() * _num_channels, _buffer.get());
}

template <typename T>
SimpleTensor<T> &SimpleTensor<T>::operator=(SimpleTensor tensor)
{
    swap(*this, tensor);

    return *this;
}

template <typename T>
T &SimpleTensor<T>::operator[](size_t offset)
{
    return _buffer[offset];
}

template <typename T>
const T &SimpleTensor<T>::operator[](size_t offset) const
{
    return _buffer[offset];
}

template <typename T>
TensorShape SimpleTensor<T>::shape() const
{
    return _shape;
}

template <typename T>
size_t SimpleTensor<T>::element_size() const
{
    return num_channels() * element_size_from_data_type(data_type());
}

template <typename T>
QuantizationInfo SimpleTensor<T>::quantization_info() const
{
    return _quantization_info;
}

template <typename T>
size_t SimpleTensor<T>::size() const
{
    const size_t size = std::accumulate(_shape.cbegin(), _shape.cend(), 1, std::multiplies<size_t>());
    return size * element_size();
}

template <typename T>
Format SimpleTensor<T>::format() const
{
    return _format;
}

template <typename T>
DataLayout SimpleTensor<T>::data_layout() const
{
    return _data_layout;
}

template <typename T>
DataType SimpleTensor<T>::data_type() const
{
    if(_format != Format::UNKNOWN)
    {
        return data_type_from_format(_format);
    }
    else
    {
        return _data_type;
    }
}

template <typename T>
int SimpleTensor<T>::num_channels() const
{
    switch(_format)
    {
        case Format::U8:
        case Format::U16:
        case Format::S16:
        case Format::U32:
        case Format::S32:
        case Format::F16:
        case Format::F32:
            return 1;
        // Because the U and V channels are subsampled
        // these formats appear like having only 2 channels:
        case Format::YUYV422:
        case Format::UYVY422:
            return 2;
        case Format::UV88:
            return 2;
        case Format::RGB888:
            return 3;
        case Format::RGBA8888:
            return 4;
        case Format::UNKNOWN:
            return _num_channels;
        //Doesn't make sense for planar formats:
        case Format::NV12:
        case Format::NV21:
        case Format::IYUV:
        case Format::YUV444:
        default:
            return 0;
    }
}

template <typename T>
int SimpleTensor<T>::num_elements() const
{
    return _shape.total_size();
}

template <typename T>
PaddingSize SimpleTensor<T>::padding() const
{
    return PaddingSize(0);
}

template <typename T>
const T *SimpleTensor<T>::data() const
{
    return _buffer.get();
}

template <typename T>
T *SimpleTensor<T>::data()
{
    return _buffer.get();
}

template <typename T>
const void *SimpleTensor<T>::operator()(const Coordinates &coord) const
{
    return _buffer.get() + coord2index(_shape, coord) * _num_channels;
}

template <typename T>
void *SimpleTensor<T>::operator()(const Coordinates &coord)
{
    return _buffer.get() + coord2index(_shape, coord) * _num_channels;
}

template <typename U>
void swap(SimpleTensor<U> &tensor1, SimpleTensor<U> &tensor2)
{
    // Use unqualified call to swap to enable ADL. But make std::swap available
    // as backup.
    using std::swap;
    swap(tensor1._shape, tensor2._shape);
    swap(tensor1._format, tensor2._format);
    swap(tensor1._data_type, tensor2._data_type);
    swap(tensor1._num_channels, tensor2._num_channels);
    swap(tensor1._quantization_info, tensor2._quantization_info);
    swap(tensor1._buffer, tensor2._buffer);
}
} // namespace test
} // namespace arm_compute
#endif /* ARM_COMPUTE_TEST_SIMPLE_TENSOR_H */


text:
Draw Annotations
================

draw annotations like stimulation points, samplings point or synapses.

- :download:`simple.swc<../tests/simple.swc>`

Draw marks
----------
.. code-block:: python

    import swc2vtk
    vtkgen = swc2vtk.VtkGenerator()
    vtkgen.add_swc('simple.swc')
    vtkgen.add_mark((1.0, 1.0, 1.0), size=0.5)
    vtkgen.write_vtk('simple.vtk')
    vtkgen.write_annotation_vtk('simple_mark.vtk')

.. image:: _static/simple_annotation1.png

Draw SWC compartment marks
--------------------------
.. code-block:: python

    import swc2vtk
    vtkgen = swc2vtk.VtkGenerator()
    vtkgen.add_swc('simple.swc')
    vtkgen.add_swc_mark(0, 2, size=0.5)
    vtkgen.write_vtk('simple.vtk')
    vtkgen.write_annotation_vtk('simple_swc_mark.vtk')

.. image:: _static/simple_annotation2.png

Draw Synapses
-------------

.. code-block:: python

    import swc2vtk
    vtkgen = swc2vtk.VtkGenerator()
    vtkgen.add_swc('simple.swc')
    vtkgen.add_swc('simple.swc', shift_y=30)
    vtkgen.add_swc_connection(0, 2, 1, 1, size=0.5, data=2)
    vtkgen.write_vtk('simple.vtk')
    vtkgen.write_annotation_vtk('simple_connection.vtk')

.. image:: _static/simple_annotation3.png


text:
<?php

namespace Movibe\BackendBundle\Controller;

use Movibe\BackendBundle\Form\PresseType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Movibe\BackendBundle\Entity\Presse;

/**
 * Presse controller.
 *
 */
class PresseController extends AbstractController
{
    /**
     * Lists all Presse entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $presses = $em->getRepository('MovibeBackendBundle:Presse')->findAll();
        $pagination = $this->pagination($presses,1000);

        $pages = array();
        $pages['Presses'] = "movibe_backend_presse";
        $this->breadcrumb($pages);

        return $this->render('MovibeBackendBundle:Presse:index.html.twig', array(
            'presses' => $pagination,
        ));
    }
    /**
     * Creates a new Presse entity.
     *
     */
    public function createAction(Request $request)
    {
        $presse = new Presse();

        $form = $this->createCreateForm($presse);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($presse);
            $em->flush();

            $request->getSession()->getFlashbag()->add('message','Une nouvelle presse a été créée');

            return $this->redirect($this->generateUrl('movibe_backend_presse_show', array('id' => $presse->getId())));
        }

        return $this->render('MovibeBackendBundle:Presse:new.html.twig', array(
            'presse' => $presse,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Presse entity.
     *
     * @param Presse $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Presse $presse)
    {
        $form = $this->createForm(new PresseType(), $presse, array(
            'action' => $this->generateUrl('movibe_backend_presse_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Créer'));

        return $form;
    }

    /**
     * Displays a form to create a new Presse entity.
     *
     */
    public function newAction()
    {
        $presse = new Presse();

        $form   = $this->createCreateForm($presse);

        $pages = array();
        $pages['Presses'] = "movibe_backend_presse";
        $pages['Ajout'] = "";
        $this->breadcrumb($pages);

        return $this->render('MovibeBackendBundle:Presse:new.html.twig', array(
            'presse' => $presse,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Presse entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $presse = $em->getRepository('MovibeBackendBundle:Presse')->find($id);

        if (!$presse) {
            throw $this->createNotFoundException("La presse indiquée n'a pas été trouvée.");
        }

        $pages = array();
        $pages['Presses'] = "movibe_backend_presse";
        $pages[$presse->getNom()] = "";
        $this->breadcrumb($pages);

        return $this->render('MovibeBackendBundle:Presse:show.html.twig', array(
            'presse'      => $presse
        ));
    }

    /**
     * Displays a form to edit an existing Presse entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $presse = $em->getRepository('MovibeBackendBundle:Presse')->find($id);

        if (!$presse) {
            throw $this->createNotFoundException("La presse indiquée n'a pas été trouvée.");
        }

        $editForm = $this->createEditForm($presse);

        $pages = array();
        $pages['Presses'] = "movibe_backend_presse";
        $pages['Edition'] = "";
        $this->breadcrumb($pages);

        return $this->render('MovibeBackendBundle:Presse:edit.html.twig', array(
            'presse'      => $presse,
            'edit_form'   => $editForm->createView(),
        ));
    }

    /**
     * Creates a form to edit a Presse entity.
     *
     * @param Presse $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createEditForm(Presse $presse)
    {
        $form = $this->createForm(new PresseType(), $presse, array(
            'action' => $this->generateUrl('movibe_backend_presse_update', array('id' => $presse->getId())),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Edit'));

        return $form;
    }
    /**
     * Edits an existing Presse entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $presse = $em->getRepository('MovibeBackendBundle:Presse')->find($id);

        if (!$presse) {
            throw $this->createNotFoundException("La presse indiquée n'a pas été trouvée.");
        }

        $editForm = $this->createEditForm($presse);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            $request->getSession()->getFlashbag()->add('message','La presse sélectionnée a été modifiée');

            return $this->redirect($this->generateUrl('movibe_backend_presse_show', array('id' => $id)));
        }

        return $this->render('MovibeBackendBundle:Presse:edit.html.twig', array(
            'presse'      => $presse,
            'edit_form'   => $editForm->createView(),
        ));
    }
    /**
     * Deletes a Presse entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $presse = $em->getRepository('MovibeBackendBundle:Presse')->find($id);

        if (!$presse) {
            throw $this->createNotFoundException("La presse indiquée n'a pas été trouvée.");
        }

        $em->remove($presse);
        $em->flush();

        if ($request->isXmlHttpRequest())
        {
            return new JsonResponse(true);
        }
        else
        {
            $request->getSession()->getFlashbag()->add('message','La presse sélectionnée a été supprimée');
            return $this->redirect($this->generateUrl('movibe_backend_presse'));
        }
    }
}