text:
/* t40c.c
 *
 * Test (pseudo) terminal devices
 *
 * Select works on regular files, (pseudo) terminal devices, streams-based
 * files, FIFOs, pipes, and sockets. This test verifies selecting for (pseudo)
 * terminal devices.
 *
 * This test is part of a bigger select test. It expects as argument which sub-
 * test it is.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/syslimits.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>

#include "common.h"

#define TERMINALW "/dev/ttypf"
#define TERMINALR "/dev/ptypf"
#define SENDSTRING "minixrocks"
#define MAX_ERROR 5

static void open_terminal(int *child_fd, int *parent_fd) {
  int fd1, fd2, i;
  char opentermw[5+OPEN_MAX+1];
  char opentermr[5+OPEN_MAX+1];
  char *term[] = {"f","e","d","c","b","a","9","8","7","6","5","4","3","2","1"};
#define TERMS (sizeof(term)/sizeof(term[0]))

  if (!child_fd || !parent_fd) exit(EXIT_FAILURE);

  for (i = 0; i < TERMS; i++) {
	snprintf(opentermw, 5+OPEN_MAX, "/dev/ttyp%s", term[i]);
	snprintf(opentermr, 5+OPEN_MAX, "/dev/ptyp%s", term[i]);

	/* Open master terminal for writing */
	if((fd1 = open(opentermw, O_WRONLY)) == -1) continue;

	/* Open slave terminal for reading */
	if((fd2 = open(opentermr, O_RDONLY)) == -1) {
		close(fd1);
		continue;
	}

	*child_fd = fd1;
	*parent_fd = fd2;
	return;
  }

  /* If we get here we failed to find a terminal pair */
  exit(EXIT_FAILURE);
}

static int do_child(int terminal) {
  /* Going to sleep for two seconds to allow the parent proc to get ready */
  sleep(2);

  /* Try to write. Doesn't matter how many bytes we actually send. */
  (void) write(terminal, SENDSTRING, strlen(SENDSTRING));

  /* Wait for another second to allow the parent to process incoming data */
  sleep(1);

  /* Write some more, and wait some more. */
  (void) write(terminal, SENDSTRING, strlen(SENDSTRING));

  sleep(1);

  close(terminal);
  exit(0);
}

static int do_parent(int child, int terminal) {
  fd_set fds_read, fds_read2, fds_write, fds_error;
  int retval, terminal2, highest;
  char buf[256];

  /* Clear bit masks */
  FD_ZERO(&fds_read); FD_ZERO(&fds_write); FD_ZERO(&fds_error);
  /* Set read bits */
  FD_SET(terminal, &fds_read);
  FD_SET(terminal, &fds_write);

  /* Test if we can read or write from/to fd. As fd is opened read only we
   * cannot actually write, so the select should return immediately with fd
   * set in fds_write, but not in fds_read. Note that the child waits two
   * seconds before sending data. This gives us the opportunity run this
   * sub-test as reading from fd is blocking at this point. */
  retval = select(terminal+1, &fds_read, &fds_write, &fds_error, NULL);

  if(retval != 1) em(1, "incorrect amount of ready file descriptors");

  if(FD_ISSET(terminal, &fds_read)) em(2, "read should NOT be set");
  if(!FD_ISSET(terminal, &fds_write)) em(3, "write should be set");
  if(FD_ISSET(terminal, &fds_error)) em(4, "error should NOT be set");

  /* Block until ready; until child wrote stuff */
  FD_ZERO(&fds_read); FD_ZERO(&fds_write); FD_ZERO(&fds_error);
  FD_SET(terminal, &fds_read);
  retval = select(terminal+1, &fds_read, NULL, &fds_error, NULL);

  if(retval != 1) em(5, "incorrect amount of ready file descriptors");
  if(!FD_ISSET(terminal, &fds_read)) em(6, "read should be set");
  if(FD_ISSET(terminal, &fds_error)) em(7, "error should not be set");

  FD_ZERO(&fds_read); FD_ZERO(&fds_error);
  FD_SET(terminal, &fds_write);
  retval = select(terminal+1, NULL, &fds_write, NULL, NULL);
  /* As it is impossible to write to a read only fd, this select should return
   * immediately with fd set in fds_write. */
  if(retval != 1) em(8, "incorrect amount or ready file descriptors");

  /* See if selecting on the same object with two different fds results in both
   * fds being returned as ready, immediately.
   */
  terminal2 = dup(terminal);
  if (terminal2 < 0) em(9, "unable to dup file descriptor");

  FD_ZERO(&fds_read);
  FD_SET(terminal, &fds_read);
  FD_SET(terminal2, &fds_read);
  fds_read2 = fds_read;
  highest = terminal > terminal2 ? terminal : terminal2;

  retval = select(highest+1, &fds_read, NULL, NULL, NULL);
  if (retval != 2) em(10, "incorrect amount of ready file descriptors");
  if (!FD_ISSET(terminal, &fds_read)) em(11, "first fd missing from set");
  if (!FD_ISSET(terminal2, &fds_read)) em(12, "second fd missing from set");

  /* Empty the buffer. */
  if (read(terminal, buf, sizeof(buf)) <= 0) em(13, "unable to read data");

  /* Repeat the test, now with a delay. */
  retval = select(highest+1, &fds_read2, NULL, NULL, NULL);
  if (retval != 2) em(10, "incorrect amount of ready file descriptors");
  if (!FD_ISSET(terminal, &fds_read2)) em(11, "first fd missing from set");
  if (!FD_ISSET(terminal2, &fds_read2)) em(12, "second fd missing from set");

  close(terminal2);
  close(terminal);
  waitpid(child, &retval, 0);
  exit(errct);
}

int main(int argc, char **argv) {
  int forkres;
  int master, slave;

  /* Get subtest number */
  if(argc != 2) {
    printf("Usage: %s subtest_no\n", argv[0]);
    exit(-1);
  } else if(sscanf(argv[1], "%d", &subtest) != 1) {
    printf("Usage: %s subtest_no\n", argv[0]);
    exit(-1);
  }

  open_terminal(&master, &slave);

  forkres = fork();
  if(forkres == 0) do_child(master);
  else if(forkres > 0)  do_parent(forkres, slave);
  else { /* Fork failed */
    perror("Unable to fork");
    exit(-1);
  }

  exit(-2); /* We're not supposed to get here. Both do_* routines should exit*/

}


text:
package ncku.hpds.fed.MRv2;

public class FedCloudProtocol {
    /*
     *   Client                 Server
     *   Top Cloud   <---->      Region Cloud
     *    req PING                 res PONG
     *    res OK                   req Map-ProxyReduce Finished
     *    res OK                   req Start-Local Aggregation ( upload partial result from region cloud to top cloud )
     *    record AggregationTime   req Upload Finished  ( if not iterative, Top Cloud disconnect and Server Closed )
     *
     */
	public static final String REQ_MAP_PROXY_REDUCE_FINISHED = "MAP-PR-Finished";
    public static final String REQ_MIGRATE_DATA = "Migrate-Data";
    public static final String REQ_MIGRATE_DATA_FINISHED = "Migrate-Data-Finished";
	public static final String REQ_PING = "PING";
	public static final String RES_PONG = "PONG";
    public static final String RES_OK = "OK";
    public static final String REQ_BYE = "BYE";
    public static final String RES_BYE = "GoodBYE";
    public enum FedSocketState {
        NONE, ACCEPTING, ACCEPTED, CONNECTING, CONNECTED, DISCONNECTED
    };
}

redpajama_set_name: RedPajamaGithub


text:
const _ = require('lodash');

module.exports = {
	hasProps({ args, props = [], action = '' }) {
			const missingProps = _.reduce(props, (accumulator, prop) => {
				if (!_.has(args, prop) || _.chain(args[prop]).toString().isEmpty().value()) {
					accumulator.push(prop);
				}
				return accumulator;
			}, []);

			const message = `[${action}] Missing props values were detected: [ ${missingProps.join(', ')} ]`;
			if (_.size(missingProps) > 0) {
				throw new Error(message);
			}
	},
	validUid({ action, uid, actionKey }) {
		if (!_.isString(uid)) {
			const message = `[${action}] uid prop should be string, currently passed [ ${uid} ]`;
			throw new Error(message);
		}
	},
	validValue({ action, value, actionKey }) {
		if (!_.isObject(value)) {
			const message = `[${action}] value prop should be an object, currently passed [ ${value} ]`;
			throw new Error(message);
		}
	},
	validIndex({ action, index, actionKey }) {
		if (!_.gte(index, 0)) {
			const message = `[${action}] item with index [ ${index} ] was not found.`;
			throw new Error(message);
		}
	},
	validTable({ action, table, actionKey }) {
		if (!_.isString(table)) {
			const message = `[${action}] table prop should be string, currently passed [ ${table} ]`;
			throw new Error(message);
		}
	},
};


text:
  <title>Test for Bug 570378</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />

Mozilla Bug 570378


text:
<!doctype html>

<link rel="stylesheet/less" type="text/css" href="/static/style.less"/>

        Left side Url: http://
        <input id="setUrl" name="leaderUrl" type="text" tabindex="100" value="{{ initial }}"/>

        Right side replace: s/
        <input name="leaderMatch" type="text" tabindex="200" value="{{ subst }}"/>

        /
        <input name="followReplace" type="text" tabindex="300" value="{{ replacement}}"/>

      <input id="reload" type="submit" value="Reload both"/>


text:
package server

import (
	"errors"
	"fmt"
	"io"
	"net"
	"sync"
	"time"

	"github.com/getcfs/megacfs/ftls"
	"github.com/getcfs/megacfs/oort/groupproto"
	"github.com/getcfs/megacfs/oort/proto"
	"github.com/gholt/ring"
	"github.com/gholt/store"
	"github.com/grpc-ecosystem/go-grpc-prometheus"
	"github.com/prometheus/client_golang/prometheus"
	"go.uber.org/zap"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

type GroupStore struct {
	sync.RWMutex
	waitGroup         *sync.WaitGroup
	shutdownChan      chan struct{}
	started           bool
	groupStore        store.GroupStore
	groupStoreMsgRing *ring.TCPMsgRing
	grpcServer        *grpc.Server
	grpcAddressIndex  int
	grpcCertFile      string
	grpcKeyFile       string
	replCertFile      string
	replKeyFile       string
	caFile            string
	logger            *zap.Logger
}

type GroupStoreConfig struct {
	GRPCAddressIndex int
	ReplAddressIndex int
	GRPCCertFile     string
	GRPCKeyFile      string
	ReplCertFile     string
	ReplKeyFile      string
	CAFile           string
	Path             string
	Scale            float64
	Ring             ring.Ring
	Logger           *zap.Logger
}

func resolveGroupStoreConfig(c *GroupStoreConfig) *GroupStoreConfig {
	cfg := &GroupStoreConfig{}
	if c != nil {
		*cfg = *c
	}
	if cfg.Logger == nil {
		var err error
		cfg.Logger, err = zap.NewProduction()
		if err != nil {
			panic(err)
		}
	}
	return cfg
}

func NewGroupStore(cfg *GroupStoreConfig) (*GroupStore, chan error, error) {
	cfg = resolveGroupStoreConfig(cfg)
	s := &GroupStore{
		waitGroup:        &sync.WaitGroup{},
		grpcAddressIndex: cfg.GRPCAddressIndex,
		grpcCertFile:     cfg.GRPCCertFile,
		grpcKeyFile:      cfg.GRPCKeyFile,
		replCertFile:     cfg.ReplCertFile,
		replKeyFile:      cfg.ReplKeyFile,
		caFile:           cfg.CAFile,
		logger:           cfg.Logger,
	}
	var err error
	s.groupStoreMsgRing, err = ring.NewTCPMsgRing(&ring.TCPMsgRingConfig{
		AddressIndex: cfg.ReplAddressIndex,
		UseTLS:       true,
		MutualTLS:    true,
		CertFile:     s.replCertFile,
		KeyFile:      s.replKeyFile,
		CAFile:       s.caFile,
		DefaultPort:  12311,
	})
	if err != nil {
		return nil, nil, err
	}
	s.groupStoreMsgRing.SetRing(cfg.Ring)
	var groupStoreRestartChan chan error
	s.groupStore, groupStoreRestartChan = store.NewGroupStore(&store.GroupStoreConfig{
		Scale:   cfg.Scale,
		Path:    cfg.Path,
		MsgRing: s.groupStoreMsgRing,
	})
	return s, groupStoreRestartChan, nil
}

func (s *GroupStore) Startup(ctx context.Context) error {
	s.Lock()
	defer s.Unlock()
	if s.started {
		return nil
	}
	s.started = true
	s.shutdownChan = make(chan struct{})
	err := s.groupStore.Startup(ctx)
	if err != nil {
		return err
	}
	s.waitGroup.Add(1)
	go func() {
		mRingChanges := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "RingChanges",
			Help:      "Number of received ring changes.",
		})
		mRingChangeCloses := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "RingChangeCloses",
			Help:      "Number of connections closed due to ring changes.",
		})
		mMsgToNodes := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgToNodes",
			Help:      "Number of times MsgToNode function has been called; single message to single node.",
		})
		mMsgToNodeNoRings := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgToNodeNoRings",
			Help:      "Number of times MsgToNode function has been called with no ring yet available.",
		})
		mMsgToNodeNoNodes := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgToNodeNoNodes",
			Help:      "Number of times MsgToNode function has been called with no matching node.",
		})
		mMsgToOtherReplicas := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgToOtherReplicas",
			Help:      "Number of times MsgToOtherReplicas function has been called; single message to all replicas, excluding the local replica if responsible.",
		})
		mMsgToOtherReplicasNoRings := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgToOtherReplicasNoRings",
			Help:      "Number of times MsgToOtherReplicas function has been called with no ring yet available.",
		})
		mListenErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "ListenErrors",
			Help:      "Number of errors trying to establish a TCP listener.",
		})
		mIncomingConnections := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "IncomingConnections",
			Help:      "Number of incoming TCP connections made.",
		})
		mDials := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "Dials",
			Help:      "Number of attempts to establish outgoing TCP connections.",
		})
		mDialErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "DialErrors",
			Help:      "Number of errors trying to establish outgoing TCP connections.",
		})
		mOutgoingConnections := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "OutgoingConnections",
			Help:      "Number of outgoing TCP connections established.",
		})
		mMsgChanCreations := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgChanCreations",
			Help:      "Number of internal message channels created.",
		})
		mMsgToAddrs := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "MsgToAddrsTCPMsgRing",
			Help:      "Number times internal function msgToAddr has been called.",
		})
		mMsgToAddrQueues := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgToAddrQueues",
			Help:      "Number of messages msgToAddr successfully queued.",
		})
		mMsgToAddrTimeoutDrops := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgToAddrTimeoutDrops",
			Help:      "Number of messages msgToAddr dropped after timeout.",
		})
		mMsgToAddrShutdownDrops := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgToAddrShutdownDrops",
			Help:      "Number of messages msgToAddr dropped due to a shutdown.",
		})
		mMsgReads := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgReads",
			Help:      "Number of incoming messages read.",
		})
		mMsgReadErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgReadErrors",
			Help:      "Number of errors reading incoming messages.",
		})
		mMsgWrites := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgWrites",
			Help:      "Number of outgoing messages written.",
		})
		mMsgWriteErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStoreTCPMsgRing",
			Name:      "MsgWriteErrors",
			Help:      "Number of errors writing outgoing messages.",
		})
		mValues := prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: "GroupStore",
			Name:      "Values",
			Help:      "Current number of values stored.",
		})
		mValueBytes := prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: "GroupStore",
			Name:      "ValueBytes",
			Help:      "Current number of bytes for the values stored.",
		})
		mLookups := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "Lookups",
			Help:      "Count of lookup requests executed.",
		})
		mLookupErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "LookupErrors",
			Help:      "Count of lookup requests executed resulting in errors.",
		})

		mLookupGroups := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "LookupGroups",
			Help:      "Count of lookup-group requests executed.",
		})
		mLookupGroupItems := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "LookupGroupItems",
			Help:      "Count of items lookup-group requests have returned.",
		})
		mLookupGroupErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "LookupGroupErrors",
			Help:      "Count of errors lookup-group requests have returned.",
		})

		mReads := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "Reads",
			Help:      "Count of read requests executed.",
		})
		mReadErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "ReadErrors",
			Help:      "Count of read requests executed resulting in errors.",
		})

		mReadGroups := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "ReadGroups",
			Help:      "Count of read-group requests executed.",
		})
		mReadGroupItems := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "ReadGroupItems",
			Help:      "Count of items read-group requests have returned.",
		})
		mReadGroupErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "ReadGroupErrors",
			Help:      "Count of errors read-group requests have returned.",
		})

		mWrites := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "Writes",
			Help:      "Count of write requests executed.",
		})
		mWriteErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "WriteErrors",
			Help:      "Count of write requests executed resulting in errors.",
		})
		mWritesOverridden := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "WritesOverridden",
			Help:      "Count of write requests that were outdated or repeated.",
		})
		mDeletes := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "Deletes",
			Help:      "Count of delete requests executed.",
		})
		mDeleteErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "DeleteErrors",
			Help:      "Count of delete requests executed resulting in errors.",
		})
		mDeletesOverridden := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "DeletesOverridden",
			Help:      "Count of delete requests that were outdated or repeated.",
		})
		mOutBulkSets := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "OutBulkSets",
			Help:      "Count of outgoing bulk-set messages in response to incoming pull replication messages.",
		})
		mOutBulkSetValues := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "OutBulkSetValues",
			Help:      "Count of values in outgoing bulk-set messages; these bulk-set messages are those in response to incoming pull-replication messages.",
		})
		mOutBulkSetPushes := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "OutBulkSetPushes",
			Help:      "Count of outgoing bulk-set messages due to push replication.",
		})
		mOutBulkSetPushValues := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "OutBulkSetPushValues",
			Help:      "Count of values in outgoing bulk-set messages; these bulk-set messages are those due to push replication.",
		})
		mOutPushReplicationSeconds := prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: "GroupStore",
			Name:      "OutPushReplicationSeconds",
			Help:      "How long the last out push replication pass took.",
		})
		mInBulkSets := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSets",
			Help:      "Count of incoming bulk-set messages.",
		})
		mInBulkSetDrops := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetDrops",
			Help:      "Count of incoming bulk-set messages dropped due to the local system being overworked at the time.",
		})
		mInBulkSetInvalids := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetInvalids",
			Help:      "Count of incoming bulk-set messages that couldn't be parsed.",
		})
		mInBulkSetWrites := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetWrites",
			Help:      "Count of writes due to incoming bulk-set messages.",
		})
		mInBulkSetWriteErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetWriteErrors",
			Help:      "Count of errors returned from writes due to incoming bulk-set messages.",
		})
		mInBulkSetWritesOverridden := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetWritesOverridden",
			Help:      "Count of writes from incoming bulk-set messages that result in no change.",
		})
		mOutBulkSetAcks := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "OutBulkSetAcks",
			Help:      "Count of outgoing bulk-set-ack messages.",
		})
		mInBulkSetAcks := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetAcks",
			Help:      "Count of incoming bulk-set-ack messages.",
		})
		mInBulkSetAckDrops := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetAckDrops",
			Help:      "Count of incoming bulk-set-ack messages dropped due to the local system being overworked at the time.",
		})
		mInBulkSetAckInvalids := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetAckInvalids",
			Help:      "Count of incoming bulk-set-ack messages that couldn't be parsed.",
		})
		mInBulkSetAckWrites := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetAckWrites",
			Help:      "Count of writes (for local removal) due to incoming bulk-set-ack messages.",
		})
		mInBulkSetAckWriteErrors := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetAckWriteErrors",
			Help:      "Count of errors returned from writes due to incoming bulk-set-ack messages.",
		})
		mInBulkSetAckWritesOverridden := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InBulkSetAckWritesOverridden",
			Help:      "Count of writes from incoming bulk-set-ack messages that result in no change.",
		})
		mOutPullReplications := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "OutPullReplications",
			Help:      "Count of outgoing pull-replication messages.",
		})
		mOutPullReplicationSeconds := prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: "GroupStore",
			Name:      "OutPullReplicationSeconds",
			Help:      "How long the last out pull replication pass took.",
		})
		mInPullReplications := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InPullReplications",
			Help:      "Count of incoming pull-replication messages.",
		})
		mInPullReplicationDrops := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InPullReplicationDrops",
			Help:      "Count of incoming pull-replication messages droppped due to the local system being overworked at the time.",
		})
		mInPullReplicationInvalids := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "InPullReplicationInvalids",
			Help:      "Count of incoming pull-replication messages that couldn't be parsed.",
		})
		mExpiredDeletions := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "ExpiredDeletions",
			Help:      "Count of recent deletes that have become old enough to be completely discarded.",
		})
		mTombstoneDiscardSeconds := prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: "GroupStore",
			Name:      "TombstoneDiscardSeconds",
			Help:      "How long the last tombstone discard pass took.",
		})
		mCompactionSeconds := prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: "GroupStore",
			Name:      "CompactionSeconds",
			Help:      "How long the last compaction pass took.",
		})
		mCompactions := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "Compactions",
			Help:      "Count of disk file sets compacted due to their contents exceeding a staleness threshold. For example, this happens when enough of the values have been overwritten or deleted in more recent operations.",
		})
		mSmallFileCompactions := prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "GroupStore",
			Name:      "SmallFileCompactions",
			Help:      "Count of disk file sets compacted due to the entire file size being too small. For example, this may happen when the store is shutdown and restarted.",
		})
		mReadOnly := prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: "GroupStore",
			Name:      "ReadOnly",
			Help:      "Indicates when the store has been put in read-only mode, whether by an operator or automatically by the watcher.",
		})
		mAuditSeconds := prometheus.NewGauge(prometheus.GaugeOpts{
			Namespace: "GroupStore",
			Name:      "AuditSeconds",
			Help:      "How long the last audit pass took.",
		})
		prometheus.Register(mRingChanges)
		prometheus.Register(mRingChangeCloses)
		prometheus.Register(mMsgToNodes)
		prometheus.Register(mMsgToNodeNoRings)
		prometheus.Register(mMsgToNodeNoNodes)
		prometheus.Register(mMsgToOtherReplicas)
		prometheus.Register(mMsgToOtherReplicasNoRings)
		prometheus.Register(mListenErrors)
		prometheus.Register(mIncomingConnections)
		prometheus.Register(mDials)
		prometheus.Register(mDialErrors)
		prometheus.Register(mOutgoingConnections)
		prometheus.Register(mMsgChanCreations)
		prometheus.Register(mMsgToAddrs)
		prometheus.Register(mMsgToAddrQueues)
		prometheus.Register(mMsgToAddrTimeoutDrops)
		prometheus.Register(mMsgToAddrShutdownDrops)
		prometheus.Register(mMsgReads)
		prometheus.Register(mMsgReadErrors)
		prometheus.Register(mMsgWrites)
		prometheus.Register(mMsgWriteErrors)
		prometheus.Register(mValues)
		prometheus.Register(mValueBytes)
		prometheus.Register(mLookups)
		prometheus.Register(mLookupErrors)

		prometheus.Register(mLookupGroups)
		prometheus.Register(mLookupGroupItems)
		prometheus.Register(mLookupGroupErrors)

		prometheus.Register(mReads)
		prometheus.Register(mReadErrors)

		prometheus.Register(mReadGroups)
		prometheus.Register(mReadGroupItems)
		prometheus.Register(mReadGroupErrors)

		prometheus.Register(mWrites)
		prometheus.Register(mWriteErrors)
		prometheus.Register(mWritesOverridden)
		prometheus.Register(mDeletes)
		prometheus.Register(mDeleteErrors)
		prometheus.Register(mDeletesOverridden)
		prometheus.Register(mOutBulkSets)
		prometheus.Register(mOutBulkSetValues)
		prometheus.Register(mOutBulkSetPushes)
		prometheus.Register(mOutBulkSetPushValues)
		prometheus.Register(mOutPushReplicationSeconds)
		prometheus.Register(mInBulkSets)
		prometheus.Register(mInBulkSetDrops)
		prometheus.Register(mInBulkSetInvalids)
		prometheus.Register(mInBulkSetWrites)
		prometheus.Register(mInBulkSetWriteErrors)
		prometheus.Register(mInBulkSetWritesOverridden)
		prometheus.Register(mOutBulkSetAcks)
		prometheus.Register(mInBulkSetAcks)
		prometheus.Register(mInBulkSetAckDrops)
		prometheus.Register(mInBulkSetAckInvalids)
		prometheus.Register(mInBulkSetAckWrites)
		prometheus.Register(mInBulkSetAckWriteErrors)
		prometheus.Register(mInBulkSetAckWritesOverridden)
		prometheus.Register(mOutPullReplications)
		prometheus.Register(mOutPullReplicationSeconds)
		prometheus.Register(mInPullReplications)
		prometheus.Register(mInPullReplicationDrops)
		prometheus.Register(mInPullReplicationInvalids)
		prometheus.Register(mExpiredDeletions)
		prometheus.Register(mTombstoneDiscardSeconds)
		prometheus.Register(mCompactionSeconds)
		prometheus.Register(mCompactions)
		prometheus.Register(mSmallFileCompactions)
		prometheus.Register(mReadOnly)
		prometheus.Register(mAuditSeconds)
		tcpMsgRingStats := s.groupStoreMsgRing.Stats(false)
		for {
			select {
			case <-s.shutdownChan:
				s.waitGroup.Done()
				return
			case <-time.After(time.Minute):
				tcpMsgRingStats = s.groupStoreMsgRing.Stats(false)
				mRingChanges.Add(float64(tcpMsgRingStats.RingChanges))
				mRingChangeCloses.Add(float64(tcpMsgRingStats.RingChangeCloses))
				mMsgToNodes.Add(float64(tcpMsgRingStats.MsgToNodes))
				mMsgToNodeNoRings.Add(float64(tcpMsgRingStats.MsgToNodeNoRings))
				mMsgToNodeNoNodes.Add(float64(tcpMsgRingStats.MsgToNodeNoNodes))
				mMsgToOtherReplicas.Add(float64(tcpMsgRingStats.MsgToOtherReplicas))
				mMsgToOtherReplicasNoRings.Add(float64(tcpMsgRingStats.MsgToOtherReplicasNoRings))
				mListenErrors.Add(float64(tcpMsgRingStats.ListenErrors))
				mIncomingConnections.Add(float64(tcpMsgRingStats.IncomingConnections))
				mDials.Add(float64(tcpMsgRingStats.Dials))
				mDialErrors.Add(float64(tcpMsgRingStats.DialErrors))
				mOutgoingConnections.Add(float64(tcpMsgRingStats.OutgoingConnections))
				mMsgChanCreations.Add(float64(tcpMsgRingStats.MsgChanCreations))
				mMsgToAddrs.Add(float64(tcpMsgRingStats.MsgToAddrs))
				mMsgToAddrQueues.Add(float64(tcpMsgRingStats.MsgToAddrQueues))
				mMsgToAddrTimeoutDrops.Add(float64(tcpMsgRingStats.MsgToAddrTimeoutDrops))
				mMsgToAddrShutdownDrops.Add(float64(tcpMsgRingStats.MsgToAddrShutdownDrops))
				mMsgReads.Add(float64(tcpMsgRingStats.MsgReads))
				mMsgReadErrors.Add(float64(tcpMsgRingStats.MsgReadErrors))
				mMsgWrites.Add(float64(tcpMsgRingStats.MsgWrites))
				mMsgWriteErrors.Add(float64(tcpMsgRingStats.MsgWriteErrors))
				stats, err := s.groupStore.Stats(context.Background(), false)
				if err != nil {
					s.logger.Debug("stats error", zap.Error(err))
				} else if sstats, ok := stats.(*store.GroupStoreStats); ok {
					mValues.Set(float64(sstats.Values))
					mValueBytes.Set(float64(sstats.ValueBytes))
					mLookups.Add(float64(sstats.Lookups))
					mLookupErrors.Add(float64(sstats.LookupErrors))

					mLookupGroups.Add(float64(sstats.LookupGroups))
					mLookupGroupItems.Add(float64(sstats.LookupGroupItems))
					mLookupGroupErrors.Add(float64(sstats.LookupGroupErrors))

					mReads.Add(float64(sstats.Reads))
					mReadErrors.Add(float64(sstats.ReadErrors))

					mReadGroups.Add(float64(sstats.ReadGroups))
					mReadGroupItems.Add(float64(sstats.ReadGroupItems))
					mReadGroupErrors.Add(float64(sstats.ReadGroupErrors))

					mWrites.Add(float64(sstats.Writes))
					mWriteErrors.Add(float64(sstats.WriteErrors))
					mWritesOverridden.Add(float64(sstats.WritesOverridden))
					mDeletes.Add(float64(sstats.Deletes))
					mDeleteErrors.Add(float64(sstats.DeleteErrors))
					mDeletesOverridden.Add(float64(sstats.DeletesOverridden))
					mOutBulkSets.Add(float64(sstats.OutBulkSets))
					mOutBulkSetValues.Add(float64(sstats.OutBulkSetValues))
					mOutBulkSetPushes.Add(float64(sstats.OutBulkSetPushes))
					mOutBulkSetPushValues.Add(float64(sstats.OutBulkSetPushValues))
					mOutPushReplicationSeconds.Set(float64(sstats.OutPushReplicationNanoseconds) / 1000000000)
					mInBulkSets.Add(float64(sstats.InBulkSets))
					mInBulkSetDrops.Add(float64(sstats.InBulkSetDrops))
					mInBulkSetInvalids.Add(float64(sstats.InBulkSetInvalids))
					mInBulkSetWrites.Add(float64(sstats.InBulkSetWrites))
					mInBulkSetWriteErrors.Add(float64(sstats.InBulkSetWriteErrors))
					mInBulkSetWritesOverridden.Add(float64(sstats.InBulkSetWritesOverridden))
					mOutBulkSetAcks.Add(float64(sstats.OutBulkSetAcks))
					mInBulkSetAcks.Add(float64(sstats.InBulkSetAcks))
					mInBulkSetAckDrops.Add(float64(sstats.InBulkSetAckDrops))
					mInBulkSetAckInvalids.Add(float64(sstats.InBulkSetAckInvalids))
					mInBulkSetAckWrites.Add(float64(sstats.InBulkSetAckWrites))
					mInBulkSetAckWriteErrors.Add(float64(sstats.InBulkSetAckWriteErrors))
					mInBulkSetAckWritesOverridden.Add(float64(sstats.InBulkSetAckWritesOverridden))
					mOutPullReplications.Add(float64(sstats.OutPullReplications))
					mOutPullReplicationSeconds.Set(float64(sstats.OutPullReplicationNanoseconds) / 1000000000)
					mInPullReplications.Add(float64(sstats.InPullReplications))
					mInPullReplicationDrops.Add(float64(sstats.InPullReplicationDrops))
					mInPullReplicationInvalids.Add(float64(sstats.InPullReplicationInvalids))
					mExpiredDeletions.Add(float64(sstats.ExpiredDeletions))
					mTombstoneDiscardSeconds.Set(float64(sstats.TombstoneDiscardNanoseconds) / 1000000000)
					mCompactionSeconds.Set(float64(sstats.CompactionNanoseconds) / 1000000000)
					mCompactions.Add(float64(sstats.Compactions))
					mSmallFileCompactions.Add(float64(sstats.SmallFileCompactions))
					if sstats.ReadOnly {
						mReadOnly.Set(1)
					} else {
						mReadOnly.Set(0)
					}
					mAuditSeconds.Set(float64(sstats.AuditNanoseconds) / 1000000000)
				} else {
					s.logger.Debug("unknown stats type", zap.Any("stats", stats))
				}
			}
		}
	}()
	s.waitGroup.Add(1)
	go func() {
		s.groupStoreMsgRing.Listen()
		s.waitGroup.Done()
	}()
	s.waitGroup.Add(1)
	go func() {
		<-s.shutdownChan
		s.groupStoreMsgRing.Shutdown()
		s.waitGroup.Done()
	}()
	ln := s.groupStoreMsgRing.Ring().LocalNode()
	if ln == nil {
		return errors.New("no local node set")
	}
	grpcAddr := ln.Address(s.grpcAddressIndex)
	if grpcAddr == "" {
		return fmt.Errorf("no local node address index %d", s.grpcAddressIndex)
	}
	grpcHostPort, err := ring.CanonicalHostPort(grpcAddr, 12310)
	if err != nil {
		return err
	}
	lis, err := net.Listen("tcp", grpcHostPort)
	if err != nil {
		return err
	}
	tlsCfg, err := ftls.NewServerTLSConfig(ftls.DefaultServerFTLSConf(s.grpcCertFile, s.grpcKeyFile, s.caFile))
	if err != nil {
		return err
	}
	s.grpcServer = grpc.NewServer(
		grpc.Creds(credentials.NewTLS(tlsCfg)),
		grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
		grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
	)
	groupproto.RegisterGroupStoreServer(s.grpcServer, s)
	grpc_prometheus.Register(s.grpcServer)

	s.waitGroup.Add(1)
	go func() {
		err := s.grpcServer.Serve(lis)
		if err != nil {
			s.logger.Debug("grpcServer.Serve error", zap.Error(err))
		}
		lis.Close()
		s.waitGroup.Done()
	}()
	s.waitGroup.Add(1)
	go func() {
		<-s.shutdownChan
		s.grpcServer.Stop()
		lis.Close()
		s.waitGroup.Done()
	}()
	return nil
}

func (s *GroupStore) Shutdown(ctx context.Context) error {
	s.Lock()
	defer s.Unlock()
	if !s.started {
		return nil
	}
	close(s.shutdownChan)
	s.waitGroup.Wait()
	return s.groupStore.Shutdown(ctx)
}

func (s *GroupStore) Write(stream groupproto.GroupStore_WriteServer) error {
	// NOTE: Each of these streams is synchronized req1, resp1, req2, resp2.
	// But it doesn't have to be that way, it was just simpler to code. Each
	// client/server pair will have a stream for each request/response type, so
	// there's a pretty good amount of concurrency going on there already.
	// Perhaps later we can experiment with intrastream concurrency and see if
	// the complexity is worth it.
	//
	// The main reason for using streams over unary grpc requests was
	// benchmarked speed gains. I suspect it is because unary requests actually
	// set up and tear down streams for each request, but that's just a guess.
	// We stopped looking into it once we noticed the speed gains from
	// switching to streaming.
	var resp groupproto.WriteResponse
	for {
		req, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		resp.Reset()
		resp.RPCID = req.RPCID
		resp.TimestampMicro, err = s.groupStore.Write(stream.Context(), req.KeyA, req.KeyB, req.ChildKeyA, req.ChildKeyB, req.TimestampMicro, req.Value)
		if err != nil {
			resp.Err = proto.TranslateError(err)
		}
		if err := stream.Send(&resp); err != nil {
			return err
		}
	}
}

func (s *GroupStore) Read(stream groupproto.GroupStore_ReadServer) error {
	var resp groupproto.ReadResponse
	for {
		req, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		resp.Reset()
		resp.RPCID = req.RPCID
		resp.TimestampMicro, resp.Value, err = s.groupStore.Read(stream.Context(), req.KeyA, req.KeyB, req.ChildKeyA, req.ChildKeyB, resp.Value)
		if err != nil {
			resp.Err = proto.TranslateError(err)
		}
		if err := stream.Send(&resp); err != nil {
			return err
		}
	}
}

func (s *GroupStore) Lookup(stream groupproto.GroupStore_LookupServer) error {
	var resp groupproto.LookupResponse
	for {
		req, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		resp.Reset()
		resp.RPCID = req.RPCID
		resp.TimestampMicro, resp.Length, err = s.groupStore.Lookup(stream.Context(), req.KeyA, req.KeyB, req.ChildKeyA, req.ChildKeyB)
		if err != nil {
			resp.Err = proto.TranslateError(err)
		}
		if err := stream.Send(&resp); err != nil {
			return err
		}
	}
}

func (s *GroupStore) LookupGroup(stream groupproto.GroupStore_LookupGroupServer) error {
	var resp groupproto.LookupGroupResponse
	for {
		req, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		resp.Reset()
		resp.RPCID = req.RPCID
		items, err := s.groupStore.LookupGroup(stream.Context(), req.KeyA, req.KeyB)
		if err != nil {
			resp.Err = proto.TranslateError(err)
		} else {
			for _, v := range items {
				g := groupproto.LookupGroupItem{}
				g.Length = v.Length
				g.ChildKeyA = v.ChildKeyA
				g.ChildKeyB = v.ChildKeyB
				g.TimestampMicro = v.TimestampMicro
				resp.Items = append(resp.Items, &g)
			}
		}
		if err := stream.Send(&resp); err != nil {
			return err
		}
	}
}

func (s *GroupStore) ReadGroup(stream groupproto.GroupStore_ReadGroupServer) error {
	var resp groupproto.ReadGroupResponse
	for {
		req, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		resp.Reset()
		resp.RPCID = req.RPCID
		lgis, err := s.groupStore.LookupGroup(stream.Context(), req.KeyA, req.KeyB)
		if err != nil {
			resp.Err = proto.TranslateError(err)
		} else {
			resp.Items = make([]*groupproto.ReadGroupItem, len(lgis))
			itemCount := 0
			for i, lgi := range lgis {
				g := groupproto.ReadGroupItem{}
				g.TimestampMicro, g.Value, err = s.groupStore.Read(stream.Context(), req.KeyA, req.KeyB, lgi.ChildKeyA, lgi.ChildKeyB, nil)
				if err != nil {
					continue
				}
				g.ChildKeyA = lgi.ChildKeyA
				g.ChildKeyB = lgi.ChildKeyB
				resp.Items[i] = &g
				itemCount++
			}
			resp.Items = resp.Items[:itemCount]
		}
		if err := stream.Send(&resp); err != nil {
			return err
		}
	}
}

func (s *GroupStore) Delete(stream groupproto.GroupStore_DeleteServer) error {
	var resp groupproto.DeleteResponse
	for {
		req, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		resp.Reset()
		resp.RPCID = req.RPCID
		resp.TimestampMicro, err = s.groupStore.Delete(stream.Context(), req.KeyA, req.KeyB, req.ChildKeyA, req.ChildKeyB, req.TimestampMicro)
		if err != nil {
			resp.Err = proto.TranslateError(err)
		}
		if err := stream.Send(&resp); err != nil {
			return err
		}
	}
}

func (s *GroupStore) Stats() []byte {
	stats, err := s.groupStore.Stats(context.Background(), true)
	if err != nil {
		return nil
	}
	return []byte(stats.String())
}

// Wait isn't implemented yet, need graceful shutdowns in grpc
func (s *GroupStore) Wait() {}


text:
FragmentTransactionBuilder
==========================

This library wraps around FragmentTransactions in an elegant way.
<br />

### Prerequisites

1. This project uses android support-v4:20.+
2. This project currently compiles with API 20 and buildToolsVersion 20.0.0, hopefully there will be a way to use project level in the future.
3. MinSDk is 9

### Including in Your Project

1. Clone this repo or skip
2. Go to your build.gradle file

```groovy

dependencies{
  // Maven coming soon!

  //or locally in the a folder named "Libraries"
  compile project(':Libraries:FragmentTransactionBuilder');
}

```

### Usage

This library supports nearly all Fragment transaction methods and handles the messy logic for you. By default if you specify the *Fragment* class it will construct it with the default constructor. Also it will create tag based on its ```getClass().getSimpleName()```. The default *Mode* is replace.

```java

  new FragmentTransactionBuilder()
    .fragment(FragmentClass.class)
    .layoutId(R.id.SomeLayout)
    .mode(Mode.ADD)
    .execute(fragmentActivity);

  new FragmentTransactionBuilder()
    .fragment(FragmentClass.class)
    .layoutId(R.id.SomeLayout)
    .popBackStack(true)
    .execute(fragmentActivity);

```

### License

The MIT License (MIT)

Copyright (c) 2014 Andrew Grosner

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
interface IContext {
    begin(): ng.IPromise<any>;
}

interface ITransition {
    push(stage: IStage);
    execute(context: IContext): ITransition;
}

interface IStage {
    execute(context: IContext): ng.IPromise<any>;
}

interface IStageFactory {
    (): IStage;
}

interface IFactory {
    create(state: any, params: any, updateroute?: boolean): ITransition;
}

interface IStateTransition {
    locals: any;
    canceled: boolean;
    cancelReason: any;
    cancel: (reason?: any) => void;
    goto: (state: any, params?: any) => void;
}

//var trx = {
//    locals: context.locals,
//    canceled: false,
//    cancel: function () {
//        trx.canceled = true;
//    },
//    goto: function (state, params?) {
//        trx.canceled = true;
//        gotofn({ state: state, params: { all: params }, updateroute: true });
//    }
//};

//TODO: stateTransition.create should be suffice for the factory.
class Factory implements IFactory {
    factories: IStageFactory[] = [];

    constructor(public inject: ng.auto.IInjectorService, private q: ng.IQService) { }

    public create(state: any, params: any, updateroute?: boolean) : ITransition {
        var trans = new Transition(state, params, updateroute);
        forEach(this.factories,  (fac: IStageFactory) => {
            //TODO: Use injection.
            //var stage = null;
            trans.push(fac());
        });
        return trans;
    }
}

class Transition implements ITransition {
    stages: IStage[] = [];
    constructor(private state: any, private params: any, private updateroute?: boolean) { }

    public push(stage: IStage) {
        this.stages.push(stage);
    }

    public execute(context: IContext): ITransition {
        var q: ng.IPromise<any> = context.begin();
        forEach(this.stages, function (stage: IStage) {
            q = q.then(function () {
                return stage.execute(context);
            });
        });

        return this;
    }
}


text:
<?php

namespace YouFood\MainBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;

/**
 * ThemeAdmin
 *
 * @author Adrien Brault <adrien.brault@gmail.com>
 */
class ThemeAdmin extends Admin
{
    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('name')

        // add custom action links
            ->add('_action', 'actions', array(
                'actions' => array(
                    'view' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureShowFields(ShowMapper $filter)
    {
        $filter
            ->add('name')
            ->add('image')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('name')
            ->add('image', 'sonata_type_model', array(), array('edit' => 'list', 'link_parameters' => array('context' => 'default')));
        ;
    }
}


text:
package com.zeus.common.util;

import java.util.Arrays;

import org.apache.commons.lang.ArrayUtils;

public class ArrayUtil {

	/**
	 * 合并两个数组,剔除相同元素
	 * @param array1
	 * @param array2
	 * @return
	 */
	public static String[] merge(String[] array1,String[] array2){
		if(array1==null||array2==null){
			return (String[]) ArrayUtils.addAll(array1, array2);
		}
		String[] all = new String[array1.length + array2.length];
		Integer length = array1.length;
		System.arraycopy(array1,0,all,0,array1.length);
		for(int j=0;j<array2.length;j++){
			Boolean add = Boolean.TRUE;
			for(int i=0;i<array1.length;i++){
				if(array2[j].equals(array1[i])){
					add = Boolean.FALSE;
					break;
				}
			}
			if(add){
				all[array1.length + j] = array2[j];
				length++;
			}
		}
		return Arrays.copyOf(all, length);
	}

	/**
	 * 合并两个数组,剔除相同元素
	 * @param array1
	 * @param array2
	 * @return
	 */
	public static Object[] merge(Object[] array1,Object[] array2){
		if(array1==null||array2==null){
			return ArrayUtils.addAll(array1, array2);
		}
		Object[] all = new Object[array1.length + array2.length];
		Integer length = array1.length;
		System.arraycopy(array1,0,all,0,array1.length);
		for(int j=0;j<array2.length;j++){
			Boolean add = Boolean.TRUE;
			for(int i=0;i<array1.length;i++){
				if(array2[j].equals(array1[i])){
					add = Boolean.FALSE;
					break;
				}
			}
			if(add){
				all[array1.length + j] = array2[j];
				length++;
			}
		}
		return Arrays.copyOf(all, length);
	}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

/**
 *
 * @author Rflpz
 */
public class Horario {
    private int idHorario;
    private String horaInicio;
    private String horaTermino;
    public Horario(){
    }
    public int getIdHorario() {
        return idHorario;
    }

    public void setIdHorario(int idHorario) {
        this.idHorario = idHorario;
    }

    public String getHoraInicio() {
        return horaInicio;
    }

    public void setHoraInicio(String horaInicio) {
        this.horaInicio = horaInicio;
    }

    public String getHoraTermino() {
        return horaTermino;
    }

    public void setHoraTermino(String horaTermino) {
        this.horaTermino = horaTermino;
    }

}


text:
package ru.stqa.pft.addressbook.appmanager;

import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

/**
 * Created by zacharewicz on 2017-05-01.
 */
public class ApplicationManager {
  FirefoxDriver wd;

  public static boolean isAlertPresent(FirefoxDriver wd) {
    try {
      wd.switchTo().alert();
      return true;
    } catch (NoAlertPresentException e) {
      return false;
    }
  }

  public void init() {
    wd = new FirefoxDriver();
    wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    wd.get("http://localhost/addressbook/group.php");
    login("admin", "secret");
  }

  private void login(String username, String password) {
    wd.findElement(By.name("user")).click();
    wd.findElement(By.name("user")).clear();
    wd.findElement(By.name("user")).sendKeys(username);
    wd.findElement(By.name("pass")).click();
    wd.findElement(By.name("pass")).clear();
    wd.findElement(By.name("pass")).sendKeys(password);
    wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click();
  }

  public void returnToGroupPage() {
    wd.findElement(By.linkText("group page")).click();
  }

  public void submitGroupCreation() {
    wd.findElement(By.name("submit")).click();
  }

  public void fillGroupForm(GroupData groupData) {
    wd.findElement(By.name("group_name")).click();
    wd.findElement(By.name("group_name")).clear();
    wd.findElement(By.name("group_name")).sendKeys(groupData.getName());
    wd.findElement(By.name("group_header")).click();
    wd.findElement(By.name("group_header")).clear();
    wd.findElement(By.name("group_header")).sendKeys(groupData.getHeader());
    wd.findElement(By.name("group_footer")).click();
    wd.findElement(By.name("group_footer")).clear();
    wd.findElement(By.name("group_footer")).sendKeys(groupData.getFooter());
  }

  public void initGroupCreation() {
    wd.findElement(By.name("new")).click();
  }

  public void gotoGroupPage() {
    wd.findElement(By.linkText("groups")).click();
  }

  public void stop() {
    wd.quit();
  }

  public void deleteSelectedGroups() {
      wd.findElement(By.name("delete")).click();
  }

  public void selectGroup() {
      wd.findElement(By.name("selected[]")).click();
  }

  public static class GroupData {
    private final String name;
    private final String header;
    private final String footer;

    public GroupData(String name, String header, String footer) {
      this.name = name;
      this.header = header;
      this.footer = footer;
    }

    public String getName() {
      return name;
    }
    public String getHeader() {
      return header;
    }
    public String getFooter() {
      return footer;
    }
  }
}

public static class NewClientData {
  private final String clientName;
  private final String clientSurname;
  private final String clientPhone;
  private final String clientMail;

  public NewClientData(String ClientName, String ClientSurname, String ClientPhone, String ClientMail) {
    clientName = ClientName;
    clientSurname = ClientSurname;
    clientPhone = ClientPhone;
    clientMail = ClientMail;
  }

  public String getClientName() {
    return clientName;
  }

  public String getClientSurname() {
    return clientSurname;
  }

  public String getClientPhone() {
    return clientPhone;
  }

  public String getClientMail() {
    return clientMail;
  }
}


text:
#ifndef SVGELATTICE_H_
#define SVGELATTICE_H_

#include "../partyql/basicmath/Lattice.h"
using AlgoTrans::CLattice;

#include "../partyql/basicmath/Vektor.h"
using AlgoTrans::CVector;

#include "../partyql/basicmath/scalar/Integer.h"
using AlgoTrans::CInteger;

#include <string>
using std::string;

#include <sstream>
using std::stringstream;

#include "cute.h"
#include "SVGEGraph.h"
#include "SVGELine.h"
#include "SVGEText.h"
#include "ToString.h"

template <class R> class CSVGELattice : public CSVGElement {
	private:
		CLattice<R> lattice;
		CVector<int> lowerBounds;
		CVector<int> upperBounds;
		int width;
		bool flatMode;

		int border;

		int cellDim;
		int xC, yC;

	public:
		string horAxisTitle;
		string verAxisTitle;
		string title;

		bool swapped;

		CSVGELattice(CLattice<R> iLattice, CVector<int> iLowerBounds, CVector<int> iUpperBounds, int iWidth, bool iFlatMode)
		: lattice(iLattice), lowerBounds(iLowerBounds), upperBounds(iUpperBounds), width(iWidth), flatMode(iFlatMode) {
			if (flatMode) {
				ASSERT(lattice.getDimension() - 1 == lowerBounds.getLength());
				ASSERT(lattice.getDimension() - 1 == upperBounds.getLength());

				ASSERT((lattice.getDimension() == 3)
						|| (lattice.getDimension() == 2)); // Only doing these for now
			} else {
				ASSERT(lattice.getDimension() - 1 == lowerBounds.getLength());
				ASSERT(lattice.getDimension() - 1 == upperBounds.getLength());

				ASSERT((lattice.getDimension() == 3)
						|| (lattice.getDimension() == 2)); // Only doing these for now
			}
		};

		CPoint calcGridPos(int x, int y) {
			return CPoint((border + x)*cellDim, (2*yC + border - (border + y))*cellDim);
		}

		CPoint calcCoords(int x, int y) {
			if (lowerBounds.getLength() == 1) {
				return calcGridPos((2*(x - lowerBounds[0]) + 1), 1);
			} else if (lowerBounds.getLength() == 2) {
				return calcGridPos((2*(x - lowerBounds[0]) + 1), 2*(y - lowerBounds[1]) + 1);
			} else return CPoint(0, 0);
		}

		void drawAxis(ostream& os) {
			CColor gridStrokeColor = CColor(0x555555);
			int gridStrokeWidth = (15*(60*cellDim)/100) / 100;
			CColor strokeColor = CColor(0);
			CColor strokeColorMarks = CColor(0);
			int strokeWidth = (25*(60*cellDim)/100) / 100;
			int strokeWidthMarks = (15*(60*cellDim)/100) / 100;
			int markFontSize = (100*cellDim)/100;
			int titleFontSize = (100*cellDim)/100;

			CPoint hatLoc = calcGridPos(2*xC, 0);
			hatLoc.y += 2*cellDim + cellDim/4 + cellDim/4;
			CSVGEText tHorAxisTitle = CSVGEText(hatLoc, strokeColorMarks, horAxisTitle, titleFontSize, "BitStream Vera Sans", "end", "top");

			CPoint vatLoc = calcGridPos(0, 2*yC);
			vatLoc.x -= cellDim + cellDim/2 + cellDim/4 + cellDim/3;
			CSVGEText tVerAxisTitle = CSVGEText(vatLoc, strokeColorMarks, verAxisTitle, titleFontSize, "BitStream Vera Sans", "end", "top");
			//tVerAxisTitle.vertical = true;
			os << &tHorAxisTitle << &tVerAxisTitle;

			CPoint titLoc = calcGridPos(0, 0);
			titLoc.y += cellDim + cellDim/4;
			titLoc.x -= cellDim;
			CSVGEText tTitle = CSVGEText(titLoc, strokeColorMarks, title, titleFontSize, "BitStream Vera Sans", "end", "top");
			os << &tTitle;

			// Marks
			for (int x = lowerBounds[0]; x <= upperBounds[0]; x++) {
				CPoint start = calcGridPos(2*(x - lowerBounds[0]) + 1, 0);
				CPoint end = start;
				end.y += cellDim/4;
				CSVGELine line = CSVGELine(end, start, strokeColorMarks, strokeWidthMarks);

				end.y += cellDim;
				CSVGEText text = CSVGEText(end, strokeColorMarks, intToStr(x), markFontSize, "BitStream Vera Sans", "middle", "top");
				os << &line << &text;

				if (lowerBounds.getLength() == 2) {
					CSVGELine line2 = CSVGELine(start, calcCoords(x, upperBounds[1]),
					                    	gridStrokeColor, gridStrokeWidth);
					os << &line2;
				}
			}

			if (lowerBounds.getLength() == 2) {
				for (int y = lowerBounds[1]; y <= upperBounds[1]; y++) {
					CPoint start = calcGridPos(0, 2*(y - lowerBounds[1]) + 1);
					CPoint end = start;
					end.x -= cellDim/4;
					CSVGELine line = CSVGELine(end, start,
							                    strokeColorMarks, strokeWidthMarks);

					end.x -= cellDim/3;
					CSVGEText text = CSVGEText(end, strokeColorMarks, intToStr(y), markFontSize, "BitStream Vera Sans", "end", "middle");

					CSVGELine line2 = CSVGELine(start, calcCoords(upperBounds[0], y),
							                    gridStrokeColor, gridStrokeWidth);
					os << &line << &text << &line2;
				}
			}

			// Axes
			CPoint zero = calcGridPos(0, 0);
			CSVGELine line = CSVGELine(CPoint(zero.x - strokeWidth/2, zero.y), calcGridPos(2*xC, 0),
					                    strokeColor, strokeWidth);
			os << &line;
			if (lowerBounds.getLength() == 2) {
				CSVGELine line2 = CSVGELine(CPoint(zero.x, zero.y + strokeWidth/2), calcGridPos(0, 2*yC),
					                    strokeColor, strokeWidth);
				os << &line2;
			}
		}

		void encode(ostream& os) {
			border = 3;

			CSVGEGraph g = CSVGEGraph();
			CColor fillColor = CColor(0);
			CColor strokeColor = CColor(0);

			int dim = flatMode ? lattice.getDimension() - 1 : lattice.getDimension();

			xC = upperBounds[0] - lowerBounds[0] + 1;
			cellDim = width / (2*xC + border + 1);
			int radius = ((60 * cellDim) / 100);
			int strokeWidth = ((20 * radius) / 100);

			if (dim == 2) {
				yC = upperBounds[1] - lowerBounds[1] + 1;
				for (int x = lowerBounds[0]; x <= upperBounds[0]; x++) {
					for (int y = lowerBounds[1]; y <= upperBounds[1]; y++) {
						CVector<CInteger> v = CVector<CInteger>();
						if (!swapped) {
							v.appendElement(x);
							v.appendElement(y);
						} else {
							v.appendElement(y);
							v.appendElement(x);
						}
						bool containsPoint = flatMode ? lattice.containsAffinePoint(v) : lattice.containsPoint(v);
						fillColor = containsPoint ? CColor(0xBBAAFF) : CColor(0);
						strokeColor = containsPoint ? CColor(0) : CColor(0);
						int rad = containsPoint ? radius : (radius*2)/7;

						CPoint p = calcCoords(x, y);

						g.addVertex(CSVGEGVertexData(p, rad, fillColor, strokeColor, strokeWidth));
					}
				}
			} else if (dim == 1) {
				yC = 1;
				for (int x = lowerBounds[0]; x <= upperBounds[0]; x++) {
					CVector<CInteger> v = CVector<CInteger>();
					v.appendElement(x);
					bool containsPoint = flatMode ? lattice.containsAffinePoint(v) : lattice.containsPoint(v);
					fillColor = containsPoint ? CColor(0xBBAAFF) : CColor(0);
					strokeColor = containsPoint ? CColor(0) : fillColor;
					int rad = containsPoint ? radius : (radius*2)/7;

					CPoint p = calcCoords(x, 0);

					g.addVertex(CSVGEGVertexData(p, rad, fillColor, strokeColor, strokeWidth));
				}
			}

			drawAxis(os);

			os << &g;
		}

		virtual ~CSVGELattice() { };
};

#endif /* SVGELATTICE_H_ */


text:
<?php

class Struts_Option_Color extends Struts_Option {

	public function input_html() {
		$id = esc_attr( $this->html_id() );
		$name = esc_attr( $this->html_name() );

		$default_value = $this->default_value() ? $this->default_value() : '#FFFFFF';
		$default_value = esc_attr( $default_value );

		$value = $this->value() ? $this->value() : $this->default_value();
		$value = esc_attr( $value );

		echo "

";
		echo "<input type='text' id='$id' name='$name' value='$value' class='struts-color-chooser-input' />";
	}

	protected function standard_validation( $value ) {
		if ( '#' !== substr( $value, 0, 1 ) ) {
			$value = '#' . $value;
		}

		// Color must be in hex format
		if ( ! ctype_xdigit( substr( $value, 1 ) ) ) {
			return $this->default_value();
		}

		return $value;
	}

	protected function label_html() {
		if ( $this->label() ) {
			echo 'html_id() ) . '">' . $this->label() . ' ';
			echo '' . __( 'show color picker', 'struts' ) . '';
			echo "";
		}
	}

	/**
	 * The Theme Customizer stores color values without the pound sign. To ensure backwards
	 * compatibility, when retrieving the value, we append the pound sign if it doesn't exist.
	 */
	public function value( $value = NULL ) {
		if ( NULL === $value ) {
			$value = $this->_value;
			if ( '#' !== substr( $value, 0, 1 ) ) {
				$value = '#' . $value;
			}
			return $value;
		}

		$this->_value = $value;
		return $this;
	}

	/**
	* Farbtastic requires a value to be set to function properly.
	* We override the default_value function here to provide #FFFFFF as a default
	* in the case the user hasn't specified a default.
	*/
	public function default_value( $default_value = NULL ) {
		if ( NULL === $default_value ) {
			if ( NULL === $this->_default_value ) {
				return '#FFFFFF';
			} else {
				return $this->_default_value;
			}
		}

		$this->_default_value = $default_value;
		return $this;
	}

	protected function add_customizer_control( $wp_customize, $setting_name, $priority ) {
		$wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, $this->name(), $this->customizer_control_options( $setting_name, $priority ) ) );
	}
}


text:
from unittest.mock import patch
from django.utils import timezone

import warnings
from collections import namedtuple
from django.test import TestCase

from ..factories import SpecFactory, JobFactory
from ..models import Job, Package, Spec
from ..tasks import query_pypi

def fake_distributions(*distributions):
    Distribution = namedtuple('Distribution', ['name', 'version'])
    result = []
    for dist in distributions:
        name, version = dist.split('==')
        result.append(Distribution(name, version))
    return result

def fake_requirement(name, specs):
    Requirement = namedtuple('Requirement', ['name', 'specs', 'extras'])
    return Requirement(name, specs, extras=[])

class JobTest(TestCase):

    def setUp(self):
        self.reqs_txt = """
            -r some_missing_file
            django>=1.4,<1.5
            Django-Geoip==0.3
            # tests below
            coverage
            coveralls>0.2
            # TODO: VCS
        """

    def test_can_be_created_from_requirements_txt(self):
        with warnings.catch_warnings():
            # We're ignoring -r not being parsed
            # "Recursive requirements not supported. Skipping."
            warnings.simplefilter("ignore", category=UserWarning)
            job = Job.objects.create_from_requirements(self.reqs_txt)

        assert job.requirements == self.reqs_txt
        assert list(map(str, job.lines.all().order_by('pk'))) == [
            'django>=1.4,<1.5',
            'Django-Geoip==0.3',
            'coverage',
            'coveralls>0.2']

class JobStatusTest(TestCase):

    def test_completed_if_no_specs_no_lines(self):
        job = JobFactory()
        assert job.status == 'success', 'No specs, no lines'

    def test_pending_if_unparsed_lines(self):
        job = JobFactory(lines=['spanish=42,inquisition==7'])
        assert job.status == 'pending', 'It has 2 unparsed lines'

    def test_pending_if_pending_specs(self):
        job = JobFactory(specs=['foo=1,bar==2'])
        assert job.status == 'running', 'It has 2 unfinished specs, but lines are parsed'

    def test_running_if_running_and_finished_specs(self):
        job = JobFactory(specs=['foo=1,bar==2'])
        spec = job.specs.first()
        spec.status = 'running'
        spec.save()
        job = Job.objects.get(pk=job.pk)
        assert job.status == 'running', 'Job has started, but has not finished yet'

    def test_running_if_one_spec_pending(self):
        job = JobFactory(specs=['foo=1,bar==2'])
        job.specs.all().update(status='success')
        job = Job.objects.get(pk=job.pk)
        assert job.status == 'success', 'One spec pending'

    def test_running_if_finished_and_pending_specs(self):
        job = JobFactory(specs=['steve==1', 'jobs==2'])
        spec = job.specs.first()
        spec.status = 'finished'
        spec.save()
        assert job.status == 'running', 'One spec has finished, but 1 line is not parsed yet'

    def test_completed_if_specs_completed(self):
        job = JobFactory(specs=['foo=1,bar==2'])
        job.specs.all().update(status='success')
        job = Job.objects.get(pk=job.pk)
        assert job.status == 'success', 'All specs have finished'

class JobSpecTest(TestCase):

    def test_process_requirement(self):
        job = JobFactory(lines=['Django==1.5.4'])
        package, package_created, spec, spec_created = job.lines.all()[0].set_distribution(*fake_distributions('Django==1.5.4'))

        assert list(map(str, Package.objects.all())) == ['Django']
        assert list(map(str, job.specs.all())) == ['Django==1.5.4']
        assert package_created
        assert spec_created

    def test_does_not_create_duplicate_specs(self):
        spec = SpecFactory(version='0.2.19', package__name='lettuce')
        job = JobFactory(lines=['lettuce==0.2.19'])
        same_package, package_created, same_spec, spec_created = job.lines.all()[0].set_distribution(*fake_distributions('lettuce==0.2.19'))

        assert not package_created
        assert not spec_created
        assert Spec.objects.count() == 1
        assert Package.objects.count() == 1
        assert job.specs.all().first().version == spec.version
        assert job.specs.all().first().package.name == spec.package.name
        assert spec.pk == same_spec.pk
        assert same_package.pk == same_spec.package.pk

class PypiTaskTest(TestCase):

    @patch('api.PyPI.get_info')
    def test_updates_spec(self, get_info_mock):
        last_release_date = timezone.now()
        py3_versions = ['3', '3.2', '3.3']
        get_info_mock.return_value = {
            'last_release_date': last_release_date,
            'py3_versions': py3_versions,
        }

        spec = SpecFactory(version='0.2.19', package__name='lettuce')
        assert query_pypi(spec.pk) == get_info_mock.return_value
        spec = Spec.objects.get(pk=spec.pk)
        assert spec.release_date == last_release_date
        assert spec.python_versions == py3_versions


text:
sxg_signer_t sxg_empty_signer() {
  static const sxg_signer_t signer = {
      .name = NULL,
      .date = 0,
      .expires = 0,
      .private_key = NULL,
      .validity_url = NULL,
      .type = SXG_ECDSA,
      .public_key.ecdsa =
          {
              .public_key = NULL,
              .certificate_url = NULL,
          },
  };
  return signer;
}

void sxg_signer_release(sxg_signer_t* target) {
  OPENSSL_free(target->name);
  if (target->private_key != NULL) {
    EVP_PKEY_free(target->private_key);
  }
  OPENSSL_free(target->validity_url);
  switch (target->type) {
    case SXG_ECDSA:
      if (target->public_key.ecdsa.public_key != NULL) {
        X509_free(target->public_key.ecdsa.public_key);
      }
      OPENSSL_free(target->public_key.ecdsa.certificate_url);
      break;
    case SXG_ED25519:
      EVP_PKEY_free(target->public_key.ed25519.public_key);
      break;
    default:
      // Invalid keytype
      abort();
      break;
  }
  *target = sxg_empty_signer();
}

static bool ensure_free_capacity(size_t desired_margin,
                                 sxg_signer_list_t* target) {
  return sxg_ensure_free_capacity_internal(
      target->size, desired_margin, 8, sizeof(sxg_signer_t), &target->capacity,
      (void**)&target->signers);
}

sxg_signer_list_t sxg_empty_signer_list() {
  const sxg_signer_list_t signer_list = {
      .signers = NULL, .size = 0, .capacity = 0};
  return signer_list;
}

void sxg_signer_list_release(sxg_signer_list_t* target) {
  for (size_t i = 0; i < target->size; ++i) {
    sxg_signer_release(&target->signers[i]);
  }
  if (target->signers) {
    OPENSSL_free(target->signers);
  }
  *target = sxg_empty_signer_list();
}

bool sxg_add_ecdsa_signer(const char* name, uint64_t date, uint64_t expires,
                          const char* validity_url, EVP_PKEY* private_key,
                          X509* public_key, const char* certificate_url,
                          sxg_signer_list_t* target) {
  if (!ensure_free_capacity(1, target)) {
    return false;
  }
  sxg_signer_t* const new_signer = &target->signers[target->size];
  new_signer->name = OPENSSL_strdup(name);
  new_signer->validity_url = OPENSSL_strdup(validity_url);
  new_signer->public_key.ecdsa.certificate_url =
      OPENSSL_strdup(certificate_url);
  if (new_signer->name == NULL || new_signer->validity_url == NULL ||
      new_signer->public_key.ecdsa.certificate_url == NULL ||
      EVP_PKEY_up_ref(private_key) != 1) {
    OPENSSL_free(new_signer->name);
    OPENSSL_free(new_signer->validity_url);
    OPENSSL_free(new_signer->public_key.ecdsa.certificate_url);
    return false;
  }
  if (X509_up_ref(public_key) != 1) {
    OPENSSL_free(new_signer->name);
    OPENSSL_free(new_signer->validity_url);
    OPENSSL_free(new_signer->public_key.ecdsa.certificate_url);
    EVP_PKEY_free(private_key);
    return false;
  }
  new_signer->date = date;
  new_signer->expires = expires;
  new_signer->private_key = private_key;
  new_signer->type = SXG_ECDSA;
  new_signer->public_key.ecdsa.public_key = public_key;
  target->size++;
  return true;
}

bool sxg_add_ed25519_signer(const char* name, uint64_t date, uint64_t expires,
                            const char* validity_url, EVP_PKEY* private_key,
                            EVP_PKEY* public_key, sxg_signer_list_t* target) {
  if (!ensure_free_capacity(1, target)) {
    return false;
  }
  sxg_signer_t* const new_signer = &target->signers[target->size];
  new_signer->name = OPENSSL_strdup(name);
  new_signer->validity_url = OPENSSL_strdup(validity_url);
  if (new_signer->name == NULL || new_signer->validity_url == NULL ||
      EVP_PKEY_up_ref(private_key) != 1) {
    OPENSSL_free(new_signer->name);
    OPENSSL_free(new_signer->validity_url);
    return false;
  }
  if (EVP_PKEY_up_ref(public_key) != 1) {
    OPENSSL_free(new_signer->name);
    OPENSSL_free(new_signer->validity_url);
    EVP_PKEY_free(private_key);
    return false;
  }
  new_signer->date = date;
  new_signer->expires = expires;
  new_signer->private_key = private_key;
  new_signer->type = SXG_ED25519;
  new_signer->public_key.ed25519.public_key = public_key;
  target->size++;
  return true;
}


text:
/**
 * \brief Wrapper around Vulkan instance functions
 */

#ifndef VULKANWRAPPER_INSTANCE_HPP
#define VULKANWRAPPER_INSTANCE_HPP

#include "InstanceFunctionList.h"

#include <exception>
#include <string>
#include <utility>
#include <vector>

#define VK_NO_PROTOTYPES
#include <vulkan/vulkan.h>

namespace vkw
{

/**
 * \brief Exception for instance-level failures
 *
 * Represents a failure that occurs inside an Instance.
 */
class InstanceException : public std::exception
{
protected:
    VkResult errorResult; //!< \internal VkResult from failing Vulkan function
    std::string details; //!< \internal Human readable string for error

public:
    InstanceException(VkResult errorResult_in, std::string details_in) noexcept
        : errorResult(errorResult_in)
        , details(std::move(details_in))
    {}

    InstanceException(const InstanceException& other) = default;
    InstanceException(InstanceException&& other) noexcept = default;

    /**
     * \brief Get result from failing Vulkan function
     */
    VkResult getVkResult() const noexcept
    {
        return errorResult;
    }

    virtual const char * what() const noexcept
    {
        return details.c_str();
    }
};

class Device;

/**
 * \brief Wrapper around VkInstance
 *
 * Wraps VkInstance and all instance-level functions; holds all instance-level function pointers.
 */
class Instance
{
protected:
    VkInstance handle; //!< \internal Wrapped Vulkan handle

public:
    struct FunctionPtrs
    {
#define X(name) PFN_##name name;
        VKW_INSTANCE_FUNCTION_LIST
#undef X
    };

    FunctionPtrs functionPtrs;

    typedef void * (*GetProcAddrPtr)(VkInstance, const char *);

    Instance() noexcept
        : handle(nullptr)
    {
    }

    /**
     * Copies VkInstance handle and populates function pointer table.
     *
     * \param handle_in VkInstance handle to be wrapped; takes ownership
     * \param getProcAddr Pointer to function for obtaining Vulkan global and instance-level functions
     */
    Instance(VkInstance handle_in, GetProcAddrPtr getProcAddr);
    Instance(const Instance& other) = delete;
    Instance(Instance&& other) noexcept
        : handle(nullptr)
    {
        std::swap(handle, other.handle);
        std::swap(functionPtrs, other.functionPtrs);
    }

    /**
     * \brief Destroys wrapped VkInstance.
     */
    ~Instance();

    Instance& operator = (const Instance& other) = delete;
    Instance& operator = (Instance&& other) noexcept
    {
        std::swap(handle, other.handle);
        std::swap(functionPtrs, other.functionPtrs);
        return *this;
    }

    /**
     * \brief Get wrapped handle; doesn't give up ownership.
     */
    const VkInstance& getInstance() const noexcept
    {
        return handle;
    }

    /**
     * \brief Get wrapped handle and take ownership of it.
     */
    VkInstance releaseInstance() noexcept
    {
        VkInstance tempHandle = handle;
        handle = nullptr;
        return tempHandle;
    }

    std::vector<VkPhysicalDevice> enumeratePhysicalDevices();
    VkPhysicalDeviceProperties getPhysicalDeviceProperties(VkPhysicalDevice physicalDevice) noexcept;
    std::vector<VkQueueFamilyProperties> getPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice);
    VkPhysicalDeviceFeatures getPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice) noexcept;

    /**
     * \brief Create Device
     *
     * Uses a physical device handle and VkDeviceCreateInfo structure to internally call
     * vkCreateInstance, and then creates Device object to wrap new Vulkan device. Since
     * Device holds pointer to the Instance it is created from, this Instance must last
     * at least as long as the created Device.
     */
    Device createDevice(VkPhysicalDevice phyDev, const VkDeviceCreateInfo& createInfo);
};

} // namespace vkw

#endif // VULKANWRAPPER_INSTANCE_HPP


text:
const process = require('process');
process.env.CHROME_BIN = require('puppeteer').executablePath();

module.exports = function (config) {
  config.set({
    basePath                : '',
    frameworks              : ['jasmine', '@angular-devkit/build-angular'],
    plugins                 : [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client                  : {
      clearContext: false
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'), reports              : ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },

    reporters               : ['progress', 'kjhtml'],
    port                    : 9876,
    colors                  : true,
    logLevel                : config.LOG_INFO,
    autoWatch               : false,
    browsers                : ['ChromeHeadlessNoSandbox'],
    singleRun               : true,
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
      }
    },
  });
};


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Summa veg. Scand. (Stockholm), Section Post. 382 (1849)

#### Original name
Sphaeria carpophila Pers., 1796

### Remarks
null


text:
import Ember from 'ember';

/**
 * @class Bootstrap.SubComponent
 */
export default Ember.Mixin.create({
    targetObject: Ember.computed.alias('parentView')
});


text:
About FOSUserBundle User Manager
================================

In order to be storage agnostic, all operations on the user instances are
handled by a user manager implementing ``FOS\UserBundle\Model\UserManagerInterface``.
Using it ensures that your code will continue to work if you change the storage.
The controllers provided by the bundle use the configured user manager instead
of interacting directly with the storage layer.

If you configure the ``db_driver`` option to ``orm``, this service is an instance
of ``FOS\UserBundle\Doctrine\UserManager``.

If you configure the ``db_driver`` option to ``mongodb``, this service is an
instance of ``FOS\UserBundle\Doctrine\UserManager``.

If you configure the ``db_driver`` option to ``couchdb``, this service is an
instance of ``FOS\UserBundle\Doctrine\UserManager``.

If you configure the ``db_driver`` option to ``propel``, this service is an instance
of ``FOS\UserBundle\Propel\UserManager``.

Accessing the User Manager service
----------------------------------

The user manager is available in the container as the ``fos_user.user_manager``
service.

.. code-block:: php

    $userManager = $container->get('fos_user.user_manager');

Creating a new User
-------------------

A new instance of your User class can be created by the user manager.

.. code-block:: php

    $user = $userManager->createUser();

``$user`` is now an instance of your user class.

.. note::

    This method will not work if your user class has some mandatory constructor
    arguments.

Retrieving the users
--------------------

The user manager has a few methods to find users based on the unique fields
(username, email and confirmation token) and a method to retrieve all existing
users.

- ``findUserByUsername($username)``
- ``findUserByEmail($email)``
- ``findUserByUsernameOrEmail($value)``  (check if the value looks like an email to choose)
- ``findUserByConfirmationToken($token)``
- ``findUsers()``

To save a user object, you can use the ``updateUser`` method of the user manager.
This method will update the encoded password and the canonical fields and
then persist the changes.

Updating a User object
----------------------

.. code-block:: php

    $user = $userManager->createUser();
    $user->setUsername('John');
    $user->setEmail('john.doe@example.com');

    $userManager->updateUser($user);

.. note::

    To make it easier, the bundle comes with a Doctrine listener handling
    the update of the password and the canonical fields for you behind the
    scenes. If you always save the user through the user manager, you may
    want to disable it to improve performance.

    .. configuration-block::

        .. code-block:: yaml

            # app/config/config.yml
            fos_user:
                # ...
                use_listener: false

        .. code-block:: xml

            <!-- app/config/config.xml -->
            <fos_user:config
                db-driver="orm"
                firewall-name="main"
                use-listener="false"
                user-class="MyProject\MyBundle\Entity\User"
            />

.. caution::

    The Propel implementation does not have such a listener so you have to
    call the method of the user manager to save the user.

.. note::

    For the Doctrine implementations, the default behavior is to flush the
    unit of work when calling the ``updateUser`` method. You can disable the
    flush by passing a second argument set to ``false``.
    This will then be equivalent to calling ``updateCanonicalFields`` and
    ``updatePassword``.

An ORM example::

    public function MainController extends Controller
    {
        public function updateAction($id)
        {
            $user = // get a user from the datastore

            $user->setEmail($newEmail);

            $this->get('fos_user.user_manager')->updateUser($user, false);

            // make more modifications to the database

            $this->getDoctrine()->getManager()->flush();
        }
    }

Overriding the User Manager
---------------------------

You can replace the default implementation of the user manager by defining
a service implementing ``FOS\UserBundle\Model\UserManagerInterface`` and
setting its id in the configuration.
The id of the default implementation is ``fos_user.user_manager.default``

.. code-block:: yaml

    fos_user:
        # ...
        service:
            user_manager: custom_user_manager_id

Your custom implementation can extend ``FOS\UserBundle\Model\UserManager``
to reuse the common logic.

SecurityBundle integration
--------------------------

The bundle provides several implementation of ``Symfony\Component\Security\Core\UserProviderInterface``
on top of the ``UserManagerInterface``.

Although the built-in user managers also implement
``Symfony\Component\Security\Core\User\UserProviderInterface``, using the
UserManager as user provider is deprecated and will tbe removed in future
versions. Use ``FOS\UserBundle\Security\UserProvider`` instead.


text:
package org.apache.causeway.viewer.restfulobjects.applib.domainobjects;

import com.fasterxml.jackson.databind.JsonNode;

import org.apache.causeway.viewer.restfulobjects.applib.JsonRepresentation;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.val;

/**
 * @since 1.x {@index}
 */
public class ActionResultRepresentation extends AbstractObjectMemberRepresentation {

    @RequiredArgsConstructor
    public enum ResultType {
        DOMAIN_OBJECT("domainobject"),
        LIST("list"),
        SCALAR_VALUE("scalarvalue"),

        /**
         * Variant of 'list' representing a list of scalar values.
         * NOT supported by the RO spec v1.0, but allows for custom representations to
         * support this particular data structure.
         * @since 2.0
         */
        SCALAR_VALUES("scalarvalues"),

        VOID("void");

        @Getter private final String value;

        public static ResultType lookup(final String value) {
            for (val resultType : values()) {
                if (resultType.value.equals(value)) {
                    return resultType;
                }
            }
            throw new IllegalArgumentException("Value '" + value + "' is not a valid result type");
        }

        public boolean isVoid() {
            return this == VOID;
        }
    }

    public ActionResultRepresentation(final JsonNode jsonNode) {
        super(jsonNode);
    }

    public JsonRepresentation getResult() {
        return getRepresentation("result");
    }

    public ResultType getResultType() {
        final String resultType = getString("resulttype");
        return ResultType.lookup(resultType);
    }
}


text:
get '/' do
	erb :index
end

get '/test' do
	p linkedin("http://www.google.com")
	redirect '/'
end


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NPoco;
using Xpressive.Home.Contracts.Automation;

namespace Xpressive.Home.Automation
{
    internal sealed class ScriptTriggerService : IScriptTriggerService
    {
        public async Task<IEnumerable<TriggeredScript>> GetTriggersAsync()
        {
            using (var database = new Database("ConnectionString"))
            {
                const string sql = "select * from TriggeredScript";
                return await database.FetchAsync<TriggeredScript>(sql);
            }
        }

        public async Task<IEnumerable<TriggeredScript>> GetTriggersByVariableAsync(string variable)
        {
            using (var database = new Database("ConnectionString"))
            {
                const string sql = "select * from TriggeredScript where [Variable] = @0";
                return await database.FetchAsync<TriggeredScript>(sql, variable);
            }
        }

        public async Task<IEnumerable<TriggeredScript>> GetTriggersByScriptAsync(Guid scriptId)
        {
            using (var database = new Database("ConnectionString"))
            {
                const string sql = "select * from TriggeredScript where ScriptId = @0";
                return await database.FetchAsync<TriggeredScript>(sql, scriptId);
            }
        }

        public async Task<TriggeredScript> AddTriggerAsync(Guid scriptId, string variable)
        {
            var triggeredScript = new TriggeredScript
            {
                Id = Guid.NewGuid(),
                ScriptId = scriptId,
                Variable = variable
            };

            using (var database = new Database("ConnectionString"))
            {
                await database.InsertAsync(triggeredScript);
            }

            return triggeredScript;
        }

        public async Task DeleteTriggerAsync(Guid id)
        {
            using (var database = new Database("ConnectionString"))
            {
                var dto = await database.SingleOrDefaultByIdAsync<TriggeredScript>(id);

                if (dto != null)
                {
                    await database.DeleteAsync(dto);
                }
            }
        }
    }
}


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

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_margin="16dp"
        android:orientation="vertical">

    </androidx.recyclerview.widget.RecyclerView>

    <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/recycler_view"
        android:layout_marginBottom="8dp"
        android:gravity="center_horizontal">

        <Button
            android:id="@+id/button_ok"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="@string/ok" />

    </RelativeLayout>

</RelativeLayout>


text:
namespace gameplay
{

void luaRegister_Image()
{
    const luaL_Reg lua_members[] =
    {
        {"addRef", lua_Image_addRef},
        {"getFormat", lua_Image_getFormat},
        {"getHeight", lua_Image_getHeight},
        {"getRefCount", lua_Image_getRefCount},
        {"getWidth", lua_Image_getWidth},
        {"release", lua_Image_release},
        {NULL, NULL}
    };
    const luaL_Reg lua_statics[] =
    {
        {"create", lua_Image_static_create},
        {NULL, NULL}
    };
    std::vector<std::string> scopePath;

    gameplay::ScriptUtil::registerClass("Image", lua_members, NULL, lua_Image__gc, lua_statics, scopePath);
}

static Image* getInstance(lua_State* state)
{
    void* userdata = luaL_checkudata(state, 1, "Image");
    luaL_argcheck(state, userdata != NULL, 1, "'Image' expected.");
    return (Image*)((gameplay::ScriptUtil::LuaObject*)userdata)->instance;
}

int lua_Image__gc(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                void* userdata = luaL_checkudata(state, 1, "Image");
                luaL_argcheck(state, userdata != NULL, 1, "'Image' expected.");
                gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)userdata;
                if (object->owns)
                {
                    Image* instance = (Image*)object->instance;
                    SAFE_RELEASE(instance);
                }

                return 0;
            }

            lua_pushstring(state, "lua_Image__gc - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

int lua_Image_addRef(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Image* instance = getInstance(state);
                instance->addRef();

                return 0;
            }

            lua_pushstring(state, "lua_Image_addRef - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

int lua_Image_getFormat(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Image* instance = getInstance(state);
                Image::Format result = instance->getFormat();

                // Push the return value onto the stack.
                lua_pushnumber(state, (int)result);

                return 1;
            }

            lua_pushstring(state, "lua_Image_getFormat - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

int lua_Image_getHeight(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Image* instance = getInstance(state);
                unsigned int result = instance->getHeight();

                // Push the return value onto the stack.
                lua_pushunsigned(state, result);

                return 1;
            }

            lua_pushstring(state, "lua_Image_getHeight - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

int lua_Image_getRefCount(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Image* instance = getInstance(state);
                unsigned int result = instance->getRefCount();

                // Push the return value onto the stack.
                lua_pushunsigned(state, result);

                return 1;
            }

            lua_pushstring(state, "lua_Image_getRefCount - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

int lua_Image_getWidth(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Image* instance = getInstance(state);
                unsigned int result = instance->getWidth();

                // Push the return value onto the stack.
                lua_pushunsigned(state, result);

                return 1;
            }

            lua_pushstring(state, "lua_Image_getWidth - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

int lua_Image_release(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Image* instance = getInstance(state);
                instance->release();

                return 0;
            }

            lua_pushstring(state, "lua_Image_release - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

int lua_Image_static_create(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TSTRING || lua_type(state, 1) == LUA_TNIL))
                {
                    // Get parameter 1 off the stack.
                    const char* param1 = gameplay::ScriptUtil::getString(1, false);

                    void* returnPtr = ((void*)Image::create(param1));
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = true;
                        luaL_getmetatable(state, "Image");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_Image_static_create - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 3:
        {
            do
            {
                if (lua_type(state, 1) == LUA_TNUMBER &&
                    lua_type(state, 2) == LUA_TNUMBER &&
                    lua_type(state, 3) == LUA_TNUMBER)
                {
                    // Get parameter 1 off the stack.
                    unsigned int param1 = (unsigned int)luaL_checkunsigned(state, 1);

                    // Get parameter 2 off the stack.
                    unsigned int param2 = (unsigned int)luaL_checkunsigned(state, 2);

                    // Get parameter 3 off the stack.
                    Image::Format param3 = (Image::Format)luaL_checkint(state, 3);

                    void* returnPtr = ((void*)Image::create(param1, param2, param3));
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = true;
                        luaL_getmetatable(state, "Image");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_Image_static_create - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 4:
        {
            do
            {
                if (lua_type(state, 1) == LUA_TNUMBER &&
                    lua_type(state, 2) == LUA_TNUMBER &&
                    lua_type(state, 3) == LUA_TNUMBER &&
                    (lua_type(state, 4) == LUA_TTABLE || lua_type(state, 4) == LUA_TLIGHTUSERDATA))
                {
                    // Get parameter 1 off the stack.
                    unsigned int param1 = (unsigned int)luaL_checkunsigned(state, 1);

                    // Get parameter 2 off the stack.
                    unsigned int param2 = (unsigned int)luaL_checkunsigned(state, 2);

                    // Get parameter 3 off the stack.
                    Image::Format param3 = (Image::Format)luaL_checkint(state, 3);

                    // Get parameter 4 off the stack.
                    gameplay::ScriptUtil::LuaArray<unsigned char> param4 = gameplay::ScriptUtil::getUnsignedCharPointer(4);

                    void* returnPtr = ((void*)Image::create(param1, param2, param3, param4));
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = true;
                        luaL_getmetatable(state, "Image");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_Image_static_create - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1, 3 or 4).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

}


text:
<?php
namespace Fortifi\FortifiApi\Contact\Payloads\Email;

use Packaged\Api\Abstracts\AbstractApiPayload;

class EmailAddressPayload extends AbstractApiPayload
{
  public $emailAddress;
}