text:
package dungen

import dungen._

import scala.annotation.tailrec

/**
 * A quick dungeon-grid generator.
 * Loosely based on the algorithm described in this blog post: [[http://journal.stuffwithstuff.com/2014/12/21/rooms-and-mazes/]]
 *
 * @author Hawk Weisman
 */
class Generator(
                 val maxRooms: Int = 20, // max number of room tries
                 val extraSize: Int = 0   // increase this for larger rooms
                 ) {
  val rand = new java.util.Random

  /**
   * Generate a 2D array of booleans of the specified size. True = empty, false = wall.
   * @param x the max x-dimension for the dungeon grid
   * @param y the max y-dimension for the dungeon grid
   * @return a 2D array of booleans of size (x,y)
   */
  def generate(x: Int, y: Int): Array[Array[Boolean]] = {
    var (grid: Array[Array[Int]], rooms) = makeRooms(Array.ofDim[Int](x,y))
    grid = makeMazes(grid)
    grid.map(slice => slice.map(i => if (i != 0) true else false ))
  }

  def makeMazes(grid: Array[Array[Int]]): Array[Array[Int]] = {
    dfs(0,0)
    def neighbors(p: Point): List[Point] = List(
      Point(p.x + 1, p.y),
      Point(p.x - 1, p.y),
      Point(p.x, p.y + 1),
      Point(p.x, p.y - 1)
      )
    @tailrec def dfs(x: Int, y: Int, visited: List[Point]=Nil, stack: List[Point]=Nil): Unit = {
      var vis = Point(x,y) :: visited
      var sta = stack
      vis.length match {
        case i if i == grid.length * grid(0).length => {}
        case _ =>
          // randomly choose a neighbor
          val eligibleNeighbors = neighbors(Point(x,y)).filter(p =>
            p.y < grid.length     &&
            p.x < grid(0).length  &&
            p.y >= 0              &&
            p.x >= 0              &&
            p.y + 1 >= 0              &&
            p.x + 1 >= 0              &&
            !vis.contains(p)
          )
          val current: Point = eligibleNeighbors.length match {
            case 0 => if (stack != Nil) {
              sta = stack.drop(1)
              stack.head
            } else {
              Point(rand.nextInt(grid(0).length), rand.nextInt(grid.length))
            }
            case i if i > 0 =>
              val doing  = eligibleNeighbors(rand.nextInt(i))
              grid(doing.y)(doing.x) = -1
              vis = doing :: vis
              doing
          }
          dfs(current.x, current.y, vis, sta)
      }
    }
    grid
  }

  /**
   * Carve out rooms on a grid. Each room is colored uniquely.
   *
   * Rooms are colored uniquely 'cause I could implement map coloring here but it would make the algorithm much more complex, and just seems unnecessary.
   * @param grid
   * @return
   */
  protected def makeRooms(grid: Array[Array[Int]]): (Array[Array[Int]], List[Room]) = {
    var rooms: List[Room] = List[Room]()
    for { i <- 1 to maxRooms } {
      val size = (rand.nextInt(2 + extraSize) + 1) * 2 + 1
      val rect = rand.nextInt(1 + size / 2) * 2
      val (height: Int,width: Int) = rand nextInt 3 match {
        case 0 => (size,size) // square room
        case 1 => (size + rect, size)
        case 2 => (size, size + rect)
      }
      val ypos = rand.nextInt(grid.length - height -1) //* 2 + 1
      val xpos = rand.nextInt(grid(0).length - width - 1)// * 2 + 1
      rooms = Room(xpos,ypos,height,width) :: rooms
      for {
        y <- ypos to ypos + height
        x <- xpos to xpos + width
        if grid(x)(y) == 0
      } {
        grid(x)(y) = i
      }
    }
    (grid,rooms)
  }
}
object Generator {
  /**
   * Crappy main method for debugging
   * @param argv
   */
  def main(argv: Array[String]): Unit = "\n" + prettyPrint(new Generator().generate(50,50))
}


text: API for JS Deploy API to heroku lesson

redpajama_set_name: RedPajamaGithub


text:
layout: post
date: 2016-10-13
title: "Moonlight Style H1230"
category: Moonlight
tags: [Moonlight]
---
### Moonlight Style H1230
Just **$359.99**
###

BRANDS	Moonlight

Buy it: [https://www.readybrides.com/en/moonlight/48043-moonlight-style-h1230.html](https://www.readybrides.com/en/moonlight/48043-moonlight-style-h1230.html)


text:
<?php

namespace AppBundle\Security;

use AppBundle\Provider\UserProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Http\HttpUtils;

class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface, AuthenticationFailureHandlerInterface
{
    protected $httpUtils;

    public function __construct(HttpUtils $httpUtils) {
        $this->httpUtils = $httpUtils;
    }

    public function createToken(Request $request, $providerKey)
    {
        $targetUrl = '/api/register';
        if ($this->httpUtils->checkRequestPath($request, $targetUrl)) {
            return;
        }

        $targetUrl = '/api/login';
        if ($this->httpUtils->checkRequestPath($request, $targetUrl)) {
            return;
        }

        // look for an apikey query parameter
        $apiKey = $request->query->get('apikey');

        if (!$apiKey) {
            throw new BadCredentialsException('No API key found');
        }

        return new PreAuthenticatedToken(
            'anon.',
            $apiKey,
            $providerKey
        );
    }

    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        if (!$userProvider instanceof UserProvider) {
            throw new \InvalidArgumentException(
                sprintf(
                    'The user provider must be an instance of UserProvider (%s was given).',
                    get_class($userProvider)
                )
            );
        }

        $apiKey = $token->getCredentials();
        $user = $userProvider->getUserByApiKey($apiKey);

        if (!$user) {
            // CAUTION: this message will be returned to the client
            // (so don't put any un-trusted messages / error strings here)
            throw new CustomUserMessageAuthenticationException(
                sprintf('API Key "%s" or User does not exist.', $apiKey)
            );
        }

        return new PreAuthenticatedToken(
            $user,
            $apiKey,
            $providerKey,
            $user->getRoles()
        );
    }

    public function supportsToken(TokenInterface $token, $providerKey)
    {
        return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        return new JsonResponse(
            array(
                'status' => 403,
                'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
                )
        );
    }
}


text:
<?php

namespace App;

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;

class Image
{
    /**
     * @var ResponseInterface $image
     */
    protected $image;

    /**
     * @var array $mimeTypes
     */
    protected $mimeTypes = [
        'image/jpeg',
        'image/jpg',
        'image/png',
        'image/bmp',
        'image/gif',
        'image/svg+xml',
        'image/webp'
    ];

    /**
     * Image constructor.
     * @param ResponseInterface $image
     */
    public function __construct(ResponseInterface $image)
    {
        $this->image = $image;
    }

    /**
     *  Check image is valid
     */
    public function isValid(): bool
    {
        return in_array($this->getContentType()[0], $this->mimeTypes);
    }

    /**
     * @return \string[]
     */
    public function getContentType()
    {
        return $this->image->getHeader('Content-Type');
    }

    /**
     * @return \string[]
     */
    public function getContentLength()
    {
        return $this->image->getHeader('Content-Length');
    }

    /**
     * @return StreamInterface
     */
    public function getBody(): StreamInterface
    {
        return $this->image->getBody();
    }
}


text:
ACCEPTED

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

#### Published in
Bull. Jard. Bot. Buitenz, 3 Sér. 13(1): 129 (1933)

#### Original name
Helminthosporium inaequale Shear, 1902

### Remarks
null


text:
var Client = require('./client'),
  error = require('./error'),
  runner = require('./runner'),
  token = require('./token');

module.exports = Grant;

/**
 * This is the function order used by the runner
 *
 * @type {Array}
 */
var fns = [
  extractCredentials,
  checkClient,
  checkGrantTypeAllowed,
  checkGrantType,
  checkScope,
  exposeUser,
  generateAccessToken,
  generateExpiresTime,
  saveAccessToken,
  generateRefreshToken,
  saveRefreshToken,
  sendResponse
];

/**
 * Grant
 *
 * @param {Object}   config Instance of OAuth object
 * @param {Object}   req
 * @param {Object}   res
 * @param {Function} next
 */
function Grant (config, options, req, res, next) {
  this.config = config;
  this.options = options || {};
  this.model = config.model;
  this.now = new Date();
  this.req = req;
  this.res = res;

  runner(fns, this, next);
}

/**
 * Basic request validation and extraction of grant_type and client creds
 *
 * @param  {Function} done
 * @this   OAuth
 */
function extractCredentials (done) {
  // Only POST via application/x-www-form-urlencoded is acceptable
  if (this.req.method !== 'POST' ||
      !this.req.is('application/x-www-form-urlencoded')) {
    return done(error('invalid_request',
      'Method must be POST with application/x-www-form-urlencoded encoding'));
  }

  // Grant type
  this.grantType = this.req.body && this.req.body.grant_type;
  if (!this.grantType || !this.grantType.match(this.config.regex.grantType)) {
    return done(error('invalid_request',
      'Invalid or missing grant_type parameter'));
  }

  // Extract credentials
  // http://tools.ietf.org/html/rfc6749#section-3.2.1
  this.client = Client.credsFromBasic(this.req) || Client.credsFromBody(this.req);
  if (!this.client.clientId ||
      !this.client.clientId.match(this.config.regex.clientId)) {
    return done(error('invalid_client',
      'Invalid or missing client_id parameter'));
  } else if (!this.client.clientSecret) {
    return done(error('invalid_client', 'Missing client_secret parameter'));
  }

  done();
}

/**
 * Check extracted client against model
 *
 * @param  {Function} done
 * @this   OAuth
 */
function checkClient (done) {
  var self = this;

  this.model.getClient(this.client.clientId, this.client.clientSecret,
      function (err, client) {
    if (err) return done(error('server_error', false, err));

    if (!client) {
      return done(error('invalid_client', 'Client credentials are invalid'));
    }

    self.req.oauth = { client: client };

    // preserve secret, but use everything else from this method
    var secret = self.client.clientSecret;
    self.client = client;
    self.client.clientSecret = secret;

    done();
  });
}

/**
 * Delegate to the relvant grant function based on grant_type
 *
 * @param  {Function} done
 * @this   OAuth
 */
function checkGrantType (done) {
  if (this.grantType.match(/^[a-zA-Z][a-zA-Z0-9+.-]+:/)
      && this.model.extendedGrant) {
    return useExtendedGrant.call(this, done);
  }

  switch (this.grantType) {
    case 'authorization_code':
      return useAuthCodeGrant.call(this, done);
    case 'password':
      return usePasswordGrant.call(this, done);
    case 'refresh_token':
      return useRefreshTokenGrant.call(this, done);
    case 'client_credentials':
      return useClientCredentialsGrant.call(this, done);
    default:
      done(error('invalid_request',
        'Invalid grant_type parameter or parameter missing'));
  }
}

/**
 * Grant for authorization_code grant type
 *
 * @param  {Function} done
 */
function useAuthCodeGrant (done) {
  var code = this.req.body.code;

  if (!code) {
    return done(error('invalid_request', 'No "code" parameter'));
  }

  var self = this;
  this.model.getAuthCode(code, function (err, authCode) {
    if (err) return done(error('server_error', false, err));

    if (!authCode || authCode.clientId !== self.client.clientId) {
      return done(error('invalid_grant', 'Invalid code'));
    } else if (authCode.expires < self.now) {
      return done(error('invalid_grant', 'Code has expired'));
    }

    self.user = authCode.user || { id: authCode.userId };
    self.scope = authCode.scope;

    if (!self.user.id) {
      return done(error('server_error', false,
        'No user/userId parameter returned from getauthCode'));
    }

    done();
  });
}

/**
 * Grant for password grant type
 *
 * @param  {Function} done
 */
function usePasswordGrant (done) {
  // User credentials
  var uname = this.req.body.username,
    pword = this.req.body.password;
  if (!uname || !pword) {
    return done(error('invalid_client',
      'Missing parameters. "username" and "password" are required'));
  }

  var self = this;
  return this.model.getUser(uname, pword, function (err, user) {
    if (err) return done(error('server_error', false, err));
    if (!user) {
      return done(error('invalid_grant', 'User credentials are invalid'));
    }

    self.user = user;
    self.scope = self.req.body.scope;

    done();
  }, this.req);
}

/**
 * Grant for refresh_token grant type
 *
 * @param  {Function} done
 */
function useRefreshTokenGrant (done) {
  var token = this.req.body.refresh_token;

  if (!token) {
    return done(error('invalid_request', 'No "refresh_token" parameter'));
  }

  var self = this;
  this.model.getRefreshToken(token, function (err, refreshToken) {
    if (err) return done(error('server_error', false, err));

    if (!refreshToken || refreshToken.clientId !== self.client.clientId) {
      return done(error('invalid_grant', 'Invalid refresh token'));
    } else if (refreshToken.expires !== null &&
        refreshToken.expires < self.now) {
      return done(error('invalid_grant', 'Refresh token has expired'));
    }

    if (!refreshToken.user && !refreshToken.userId) {
      return done(error('server_error', false,
        'No user/userId parameter returned from getRefreshToken'));
    }

    self.user = refreshToken.user || { id: refreshToken.userId };
    self.scope = refreshToken.scope;

    if (self.model.revokeRefreshToken) {
      return self.model.revokeRefreshToken(token, function (err) {
        if (err) return done(error('server_error', false, err));
        done();
      });
    }

    done();
  });
}

/**
 * Grant for client_credentials grant type
 *
 * @param  {Function} done
 */
function useClientCredentialsGrant (done) {
  // Client credentials
  var clientId = this.client.clientId,
    clientSecret = this.client.clientSecret;

  if (!clientId || !clientSecret) {
    return done(error('invalid_client',
      'Missing parameters. "client_id" and "client_secret" are required'));
  }

  var self = this;
  return this.model.getUserFromClient(this.client, function (err, user) {
    if (err) return done(error('server_error', false, err));

    if (!user) {
      return done(error('invalid_grant', 'Client credentials are invalid'));
    }

    self.user = user;
    self.scope = self.req.body.scope || self.client.defaultScope;

    done();
  });
}

/**
 * Grant for extended (http://*) grant type
 *
 * @param  {Function} done
 */
function useExtendedGrant (done) {
  var self = this;
  this.model.extendedGrant(this.grantType, this.req,
      function (err, supported, user) {
    if (err) {
      return done(error(err.error || 'server_error',
        err.description || err.message, err));
    }

    if (!supported) {
      return done(error('invalid_request',
        'Invalid grant_type parameter or parameter missing'));
    } else if (!user || user.id === undefined) {
      return done(error('invalid_request', 'Invalid request.'));
    }

    self.user = user;
    done();
  });
}

/**
 * Check the grant type is allowed for this client
 *
 * @param  {Function} done
 * @this   OAuth
 */
function checkGrantTypeAllowed (done) {
  this.model.grantTypeAllowed(this.client.clientId, this.grantType,
      function (err, allowed) {
    if (err) return done(error('server_error', false, err));

    if (!allowed) {
      return done(error('invalid_client',
        'The grant type is unauthorised for this client_id'));
    }

    done();
  });
}

/**
 * Validate the scope request
 *
 * @param  {Function} done
 * @this   OAuth
 */
function checkScope (done) {
  var self = this;
  this.model.validateScope(this.scope, this.client, this.user,
      function(err, scope, invalid) {
    if (err) return done(error('server_error', false, err));
    if (invalid) return done(error('invalid_scope', invalid));

    self.scope = scope;

    done();
  });
}

/**
 * Expose user
 *
 * @param  {Function} done
 * @this   OAuth
 */
function exposeUser (done) {
  this.req.user = this.user;

  done();
}

/**
 * Generate an access token
 *
 * @param  {Function} done
 * @this   OAuth
 */
function generateAccessToken (done) {
  var self = this;
  token(this, 'accessToken', function (err, token) {
    self.accessToken = token;
    done(err);
  });
}

function generateExpiresTime(done) {
	this.accessTokenLifetime = this.config.accessTokenLifetime;

	if (!this.model.generateExpiresTime) {
		return done();
	}

	var self = this;
	this.model.generateExpiresTime(this.req, function(err, expires) {
		if (err) {
			return done(error('server_error', false, err));
		}

		if (expires !== undefined) {
			self.accessTokenLifetime = expires;
		}
		done();
	});
}

/**
 * Save access token with model
 *
 * @param  {Function} done
 * @this   OAuth
 */
function saveAccessToken (done) {
  var accessToken = this.accessToken;

  // Object idicates a reissue
  if (typeof accessToken === 'object' && accessToken.accessToken) {
    this.accessToken = accessToken.accessToken;
    return done();
  }

  var expires = null;
  if ((this.accessTokenLifetime !== null) && (this.accessTokenLifetime > 0)) {
    expires = new Date(this.now);
    expires.setSeconds(expires.getSeconds() + this.accessTokenLifetime);
  }

  this.model.saveAccessToken(accessToken, this.client, expires,
      this.user, this.scope, function (err) {
    if (err) return done(error('server_error', false, err));
    done();
  });
}

/**
 * Generate a refresh token
 *
 * @param  {Function} done
 * @this   OAuth
 */
function generateRefreshToken (done) {
  if (this.config.grants.indexOf('refresh_token') === -1) return done();

  var self = this;
  token(this, 'refreshToken', function (err, token) {
    self.refreshToken = token;
    done(err);
  });
}

/**
 * Save refresh token with model
 *
 * @param  {Function} done
 * @this   OAuth
 */
function saveRefreshToken (done) {
  var refreshToken = this.refreshToken;

  if (!refreshToken) return done();

  // Object idicates a reissue
  if (typeof refreshToken === 'object' && refreshToken.refreshToken) {
    this.refreshToken = refreshToken.refreshToken;
    return done();
  }

  var expires = null;
  if (this.config.refreshTokenLifetime !== null) {
    expires = new Date(this.now);
    expires.setSeconds(expires.getSeconds() + this.config.refreshTokenLifetime);
  }

  this.model.saveRefreshToken(refreshToken, this.client.clientId, expires,
      this.user, this.scope, function (err) {
    if (err) return done(error('server_error', false, err));
    done();
  });
}

/**
 * Sends the resulting token(s) and related information to the client
 *
 * @param  {Function} done
 * @this   OAuth
 */
function sendResponse (done) {
  var response = {
    token_type: 'bearer',
    access_token: this.accessToken
  };

  if (this.accessTokenLifetime !== null) {
    response.expires_in = this.accessTokenLifetime;
  }

  if (this.refreshToken) {
    response.refresh_token = this.refreshToken;
  }

  if (this.scope) {
    response.scope = this.scope;
  }

  if (this.options.skipResponse) {
    return done();
  }

  this.res.set({'Cache-Control': 'no-store', 'Pragma': 'no-cache'});
  this.res.jsonp(response);

  if (this.config.continueAfterResponse)
    done();
}


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

#include <spu_intrinsics.h>

#include "cos_sin.h"
#include "divd2.h"

/*
 * FUNCTION
 *	vector double _tand2(vector double angle)
 *
 * DESCRIPTION
 *	The _tand2 function computes the tangent of a vector of "angle"s
 *      (expressed in radians) to an accuracy of double precision floating
 *      point.
 *
 */
static __inline vector double _tand2(vector double angle)
{
  vec_int4    octant;
  vec_ullong2 select;
  vec_double2 cos, sin;
  vec_double2 num, den;
  vec_double2 toggle_sign, answer;

  /* Range reduce the input angle x into the range -PI/4 to PI/4
   * by performing simple modulus.
   */
  MOD_PI_OVER_FOUR(angle, octant);

  /* Compute the cosine and sine of the range reduced input.
   */
  COMPUTE_COS_SIN(angle, cos, sin);

  /* For each SIMD element, select the numerator, denominator, and sign
   * correction depending upon the octant of the original angle.
   *
   *   octants      angles     numerator denominator sign toggle
   *   -------   ------------  --------- ----------- -----------
   *     0          0 to 45      sin        cos          no
   *    1,2        45 to 135     cos        sin         no,yes
   *    3,4       135 to 225     sin        cos         yes,no
   *    5,6       225 to 315     cos        sin         no,yes
   *     7        315 to 360     sin        cos          yes
   */
  octant = spu_shuffle(octant, octant, ((vec_uchar16) {
					  0,1, 2, 3, 0,1, 2, 3,
					    8,9,10,11, 8,9,10,11 }));

  toggle_sign = spu_and((vec_double2)spu_sl(octant, 30),
    (vec_double2) spu_splats(0x8000000000000000ULL));

  select = (vec_ullong2)spu_cmpeq(spu_and(octant, 2), 0);
  num = spu_sel(cos, sin, select);
  den = spu_sel(sin, cos, select);

  answer = spu_xor(_divd2(num, den), toggle_sign);

  return (answer);
}

#endif /* _TAND2_H_ */
#endif /* __SPU__ */


text:
package org.apache.apex.engine.util;

import java.net.URISyntaxException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

import com.datatorrent.api.Context;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.util.PubSubWebSocketClient;
import com.datatorrent.stram.util.SharedPubSubWebSocketClient;

/**
 * @since 3.7.0
 */
public class PubSubWebSocketClientBuilder
{
  public static final String GATEWAY_LOGIN_URL_PATH = "/ws/v2/login";

  private static final Logger logger = LoggerFactory.getLogger(PubSubWebSocketClientBuilder.class);

  private Context context;

  public PubSubWebSocketClientBuilder setContext(Context context)
  {
    this.context = context;
    return this;
  }

  private <T extends PubSubWebSocketClient> T build(Class<T> clazz)
  {
    Preconditions.checkState(context != null, "Context not specified");
    String gatewayAddress = context.getValue(LogicalPlan.GATEWAY_CONNECT_ADDRESS);
    if (gatewayAddress != null) {
      int timeout = context.getValue(LogicalPlan.PUBSUB_CONNECT_TIMEOUT_MILLIS);
      boolean gatewayUseSsl = context.getValue(LogicalPlan.GATEWAY_USE_SSL);

      // The builder can be used to build different types of PubSub clients in future but for now only one is supported
      SharedPubSubWebSocketClient wsClient = null;

      try {
        wsClient = new SharedPubSubWebSocketClient((gatewayUseSsl ? "wss://" : "ws://") + gatewayAddress + "/pubsub", timeout);

        String gatewayUserName = context.getValue(LogicalPlan.GATEWAY_USER_NAME);
        String gatewayPassword = context.getValue(LogicalPlan.GATEWAY_PASSWORD);
        if (gatewayUserName != null && gatewayPassword != null) {
          wsClient.setLoginUrl((gatewayUseSsl ? "https://" : "http://") + gatewayAddress + GATEWAY_LOGIN_URL_PATH);
          wsClient.setUserName(gatewayUserName);
          wsClient.setPassword(gatewayPassword);
        }

        return (T)wsClient;
      } catch (URISyntaxException e) {
        logger.warn("Unable to initialize websocket for gateway address {}", gatewayAddress, e);
      }

      return null;
    }

    return null;
  }

  public SharedPubSubWebSocketClient build()
  {
    return build(SharedPubSubWebSocketClient.class);
  }

}


text:
package org.elasticsearch.action;

import org.elasticsearch.ElasticsearchIllegalArgumentException;

/**
 * Write Consistency Level control how many replicas should be active for a write operation to occur (a write operation
 * can be index, or delete).
 *
 *
 */
public enum WriteConsistencyLevel {
    DEFAULT((byte) 0),
    ONE((byte) 1),
    QUORUM((byte) 2),
    ALL((byte) 3);

    private final byte id;

    WriteConsistencyLevel(byte id) {
        this.id = id;
    }

    public byte id() {
        return id;
    }

    public static WriteConsistencyLevel fromId(byte value) {
        if (value == 0) {
            return DEFAULT;
        } else if (value == 1) {
            return ONE;
        } else if (value == 2) {
            return QUORUM;
        } else if (value == 3) {
            return ALL;
        }
        throw new ElasticsearchIllegalArgumentException("No write consistency match [" + value + "]");
    }

    public static WriteConsistencyLevel fromString(String value) {
        if (value.equals("default")) {
            return DEFAULT;
        } else if (value.equals("one")) {
            return ONE;
        } else if (value.equals("quorum")) {
            return QUORUM;
        } else if (value.equals("all")) {
            return ALL;
        }
        throw new ElasticsearchIllegalArgumentException("No write consistency match [" + value + "]");
    }
}


text:
package uk.ac.ncl.cs.csc8101.hadoop.rank;

import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.util.StringUtils;

import java.io.IOException;

public class RankSortMapper extends Mapper<LongWritable, Text, FloatWritable, Text> {

    /**
     * The `map(...)` method is executed against each item in the input split. A key-value pair is
     * mapped to another, intermediate, key-value pair.
     *

     * Specifically, this method should take Text objects in the form:
     * `"[page]    [finalPagerank]    outLinkA,outLinkB,outLinkC..."`
     * discard the outgoing links, parse the pagerank to a float and map each page to its rank.
     *

     * Note: The output from this Mapper will be sorted by the order of its keys.
     *
     * @param key     the key associated with each item output from {@link uk.ac.ncl.cs.csc8101.hadoop.calculate.RankCalculateReducer RankCalculateReducer}
     * @param value   the text value "[page]  [finalPagerank]   outLinkA,outLinkB,outLinkC..."
     * @param context Mapper context object, to which key-value pairs are written
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

        String rank = "0.0";
        String page;
        String[] fullList = value.toString().split("\t");
        if (fullList.length >= 2 && !fullList[0].equals("") && !fullList[1].equals("")) {
            page = fullList[0];
            rank = fullList[1];
      //      System.out.println("Key:" + rank);
            Float rankValue = Float.parseFloat(rank);
     //       System.out.println("Value:" + page);
            //Writing the rank and page to output
            context.write(new FloatWritable(rankValue), new Text(page));
        }

    }

}


text:
package org.w3._1999.xlink.util;

import java.util.Map;

import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.util.XMLProcessor;
import org.w3._1999.xlink.XlinkPackage;

/**
 * This class contains helper methods to serialize and deserialize XML documents
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public class XlinkXMLProcessor extends XMLProcessor {

	/**
	 * Public constructor to instantiate the helper.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public XlinkXMLProcessor() {
		super((EPackage.Registry.INSTANCE));
		XlinkPackage.eINSTANCE.eClass();
	}

	/**
	 * Register for "*" and "xml" file extensions the XlinkResourceFactoryImpl factory.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	protected Map<String, Resource.Factory> getRegistrations() {
		if (registrations == null) {
			super.getRegistrations();
			registrations.put(XML_EXTENSION, new XlinkResourceFactoryImpl());
			registrations.put(STAR_EXTENSION, new XlinkResourceFactoryImpl());
		}
		return registrations;
	}

} //XlinkXMLProcessor


text:
export interface BaseStepperProps {
  size?: 'md' | 'lg';
  shape?: 'rect' | 'radius' | 'circle';
  value?: number;
  defaultValue?: number;
  type?: 'text' | 'number' | 'price' | 'tel';
  step?: number;
  min?: number;
  max?: number;
  disabled?: boolean;
  disableInput?: boolean;
  onInputChange?: (value: number | string) => void;
  onChange?: (value: number | string) => void;
}


text:
typedef struct {
  int verbose;
  char* inputFile;
  char** argv;
  int bitDepth;
} config_t;

extern config_t config;


text:
#import <Foundation/Foundation.h>

@class SBJson5StreamWriter;

@interface SBJson5StreamWriterState : NSObject
+ (id)sharedInstance;
- (BOOL)isInvalidState:(SBJson5StreamWriter *)writer;
- (void)appendSeparator:(SBJson5StreamWriter *)writer;
- (BOOL)expectingKey:(SBJson5StreamWriter *)writer;
- (void)transitionState:(SBJson5StreamWriter *)writer;
- (void)appendWhitespace:(SBJson5StreamWriter *)writer;
@end

@interface SBJson5StreamWriterStateObjectStart : SBJson5StreamWriterState
@end

@interface SBJson5StreamWriterStateObjectKey : SBJson5StreamWriterStateObjectStart
@end

@interface SBJson5StreamWriterStateObjectValue : SBJson5StreamWriterState
@end

@interface SBJson5StreamWriterStateArrayStart : SBJson5StreamWriterState
@end

@interface SBJson5StreamWriterStateArrayValue : SBJson5StreamWriterState
@end

@interface SBJson5StreamWriterStateStart : SBJson5StreamWriterState
@end

@interface SBJson5StreamWriterStateComplete : SBJson5StreamWriterState
@end

@interface SBJson5StreamWriterStateError : SBJson5StreamWriterState
@end


text:
<?php

/**
 * Form upload main file with php and html5.
 *
 * PHP version >= 5.2
 *
 * @category PHP
 * @package  AyeShare
 * @author   Romnick Bien Pantua (pantuts)
 * @license  MIT License
 * @link     http://pantuts.com
 * @version  1.4
 */

session_start();

// set session id
if (!isset($_SESSION['id'])) $_SESSION['id'] = uniqid();

// gzip compression with php
ob_start('ob_gzhandler');

// parse config file
$parseIni = parse_ini_file('./config.ini');
$maxFileSize = htmlentities($parseIni['size']);
$tooltip = htmlentities($parseIni['tip']);

?>

<!DOCTYPE html>

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

	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="description" content="Minimalist Self Hosted File Sharing">
	<meta property="og:locale" content="en_US"/>
	<meta property="og:type" content="website"/>
	<meta property="og:title" content="AyeShare | Minimalist Self Hosted File Sharing"/>
	<meta property="og:url" content=""/>
	<meta property="og:site_name" content=""/>
	<title>AyeShare | Minimalist Self Hosted File Sharing Service</title>
	<link rel="stylesheet" href="css/normalize.css">
	<link rel="stylesheet" href="css/styles.css">
	<link rel="shortcut icon" type="icon" href="images/favicon.png">

AyeShare

			<form action="./ayeupload.php" id="upload-form" method="post" enctype="multipart/form-data">

					Upload File
					<input type="hidden" name="MAX_FILE_SIZE" id="mfs" value="<?php echo $maxFileSize; ?>" />
					<input type="file" name="upload-file" id="upload-file" />

			</form>

			<?php echo $tooltip; ?>

				Max file size: <?php echo $maxFileSize/1000000 . ' MB'; ?>

			Error: File size exceeded on limit.
			File successfully uploaded.

			<form id="mail-form" method="post">

				Close

					<input type="text" id="email" name="email" value="mail@mail.com" onfocus="this.select()" placeholder="Email"  maxlength="100" autofocus required />

					<input type="text" id="subject" name="subject" value="" placeholder="Subject" maxlength="100" autofocus />

					<textarea id="message" value="" name="message" maxlength="500" placeholder="Message" autofocus required ></textarea>

				Send

			</form>


text:
===========================================================
Welcome to eslint-config-openstack developer documentation!
===========================================================

Introduction
============

OpenStack has a set of style guidelines for clarity. OpenStack is a very large
code base, spanning dozens of git trees, with over a thousand developers contributing
every 6 months. As such, common style helps developers understand code in reviews,
move between projects smoothly, and overall make the code more maintainable.

Even though eslint permits overriding rules on a per-project basis, it should be
the goal of every project to stay as close to the common guidelines as possible.

For Contributor
===============
If you are a new contributor to eslint-config-openstack please refer: :doc:`contributor/contributing`

.. toctree::
   :hidden:

   contributor/contributing

Administrator's Guide
=====================

.. toctree::
  :maxdepth: 1

  Introduction to eslint-config-openstack <readme>
  Installing eslint-config-openstack in your project <installation>
  Contributing to eslint-config-openstack <contributing>
  Releasing a version of eslint-config-openstack <releasing>


text:
#ifndef PANEL_H
#define PANEL_H

#include <X11/Xlib.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>

#include <libintl.h>
#define _(String) gettext(String)
#define c_(String) String

#include "config.h"

#include "bg.h"
#include "ev.h"
#include "xconf.h"

enum { ALLIGN_CENTER, ALLIGN_LEFT, ALLIGN_RIGHT  };
enum { EDGE_BOTTOM, EDGE_LEFT, EDGE_RIGHT, EDGE_TOP };
enum { WIDTH_PERCENT, WIDTH_REQUEST, WIDTH_PIXEL };
enum { HEIGHT_PIXEL, HEIGHT_REQUEST };
enum { POS_NONE, POS_START, POS_END };
enum { HIDDEN, WAITING, VISIBLE };
enum { LAYER_ABOVE, LAYER_BELOW };

#define PANEL_HEIGHT_DEFAULT  26
#define PANEL_HEIGHT_MAX      200
#define PANEL_HEIGHT_MIN      16

#define IMGPREFIX  DATADIR "/fbpanel2/images"

typedef struct _panel
{
    GtkWidget *topgwin;           /* main panel window */
    Window topxwin;               /* and it X window   */
    GtkWidget *lbox;              /* primary layout box */
    GtkWidget *bbox;              /* backgound box for box */
    GtkWidget *box;               /* box that contains all plugins */
    GtkWidget *menu;              /* context menu */
    GtkRequisition requisition;
    GtkWidget *(*my_box_new) (gboolean, gint);
    GtkWidget *(*my_separator_new) ();

    FbBg *bg;
    int alpha;
    guint32 tintcolor;
    GdkColor gtintcolor;
    gchar *tintcolor_name;

    int ax, ay, aw, ah;  /* prefferd allocation of a panel */
    int cx, cy, cw, ch;  /* current allocation (as reported by configure event) allocation */
    int allign, edge, margin;
    GtkOrientation orientation;
    int widthtype, width;
    int heighttype, height;
    int round_corners_radius;
    int max_elem_height;

    gint self_destroy;
    gint setdocktype;
    gint setstrut;
    gint round_corners;
    gint transparent;
    gint autohide;
    gint ah_far;
    gint layer;
    gint setlayer;

    int ah_dx, ah_dy; // autohide shift for x and y
    int height_when_hidden;
    guint hide_tout;

    int spacing;

    guint desknum;
    guint curdesk;
    guint32 *workarea;

    int plug_num;
    GList *plugins;

    gboolean (*ah_state)(struct _panel *);

    xconf *xc;
} panel;

typedef struct {
    unsigned int modal : 1;
    unsigned int sticky : 1;
    unsigned int maximized_vert : 1;
    unsigned int maximized_horz : 1;
    unsigned int shaded : 1;
    unsigned int skip_taskbar : 1;
    unsigned int skip_pager : 1;
    unsigned int hidden : 1;
    unsigned int fullscreen : 1;
    unsigned int above : 1;
    unsigned int below : 1;
} net_wm_state;

typedef struct {
    unsigned int desktop : 1;
    unsigned int dock : 1;
    unsigned int toolbar : 1;
    unsigned int menu : 1;
    unsigned int utility : 1;
    unsigned int splash : 1;
    unsigned int dialog : 1;
    unsigned int normal : 1;
} net_wm_window_type;

typedef struct {
    char *name;
    void (*cmd)(void);
} command;

extern command commands[];

extern gchar *cprofile;

extern Atom a_UTF8_STRING;
extern Atom a_XROOTPMAP_ID;

extern Atom a_WM_STATE;
extern Atom a_WM_CLASS;
extern Atom a_WM_DELETE_WINDOW;
extern Atom a_WM_PROTOCOLS;
extern Atom a_NET_WORKAREA;
extern Atom a_NET_CLIENT_LIST;
extern Atom a_NET_CLIENT_LIST_STACKING;
extern Atom a_NET_NUMBER_OF_DESKTOPS;
extern Atom a_NET_CURRENT_DESKTOP;
extern Atom a_NET_DESKTOP_NAMES;
extern Atom a_NET_DESKTOP_GEOMETRY;
extern Atom a_NET_ACTIVE_WINDOW;
extern Atom a_NET_CLOSE_WINDOW;
extern Atom a_NET_SUPPORTED;
extern Atom a_NET_WM_STATE;
extern Atom a_NET_WM_STATE_SKIP_TASKBAR;
extern Atom a_NET_WM_STATE_SKIP_PAGER;
extern Atom a_NET_WM_STATE_STICKY;
extern Atom a_NET_WM_STATE_HIDDEN;
extern Atom a_NET_WM_STATE_SHADED;
extern Atom a_NET_WM_STATE_ABOVE;
extern Atom a_NET_WM_STATE_BELOW;

#define a_NET_WM_STATE_REMOVE        0    /* remove/unset property */
#define a_NET_WM_STATE_ADD           1    /* add/set property */
#define a_NET_WM_STATE_TOGGLE        2    /* toggle property  */

extern Atom a_NET_WM_WINDOW_TYPE;
extern Atom a_NET_WM_WINDOW_TYPE_DESKTOP;
extern Atom a_NET_WM_WINDOW_TYPE_DOCK;
extern Atom a_NET_WM_WINDOW_TYPE_TOOLBAR;
extern Atom a_NET_WM_WINDOW_TYPE_MENU;
extern Atom a_NET_WM_WINDOW_TYPE_UTILITY;
extern Atom a_NET_WM_WINDOW_TYPE_SPLASH;
extern Atom a_NET_WM_WINDOW_TYPE_DIALOG;
extern Atom a_NET_WM_WINDOW_TYPE_NORMAL;

extern Atom a_NET_WM_DESKTOP;
extern Atom a_NET_WM_NAME;
extern Atom a_NET_WM_VISIBLE_NAME;
extern Atom a_NET_WM_STRUT;
extern Atom a_NET_WM_STRUT_PARTIAL;
extern Atom a_NET_WM_ICON;
extern Atom a_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR;

extern xconf_enum allign_enum[];
extern xconf_enum edge_enum[];
extern xconf_enum widthtype_enum[];
extern xconf_enum heighttype_enum[];
extern xconf_enum bool_enum[];
extern xconf_enum pos_enum[];
extern xconf_enum layer_enum[];

extern int verbose;
extern gint force_quit;
extern FbEv *fbev;
extern GtkIconTheme *icon_theme;
#define FBPANEL_WIN(win)  gdk_window_lookup(win)
void panel_set_wm_strut(panel *p);

gchar *panel_get_profile(void);
gchar *panel_get_profile_file(void);

void ah_start(panel *p);
void ah_stop(panel *p);

#endif


text:
<?php
namespace Xetaravel\Models\Repositories;

use Illuminate\Support\Str;
use Xetaravel\Models\Setting;

class SettingRepository
{
    /**
     * Create a new setting instance.
     *
     * @param array $data The data used to create the setting.
     *
     * @return \Xetaravel\Models\Setting
     */
    public static function create(array $data): Setting
    {
        return Setting::create([
            'name' => Str::slug($data['name'], '.'),
            'value_int' => $data['type'] ==  'value_int' ? (int) $data['value'] : null,
            'value_str' => $data['type'] ==  'value_str' ? (string) $data['value'] : null,
            'value_bool' => $data['type'] ==  'value_bool' ? (bool) $data['value'] : null,
            'description' => $data['description'],
            'is_deletable' => isset($data['is_deletable']) ? true : false,
        ]);
    }

    /**
     * Update the Setting informations after a valid update request.
     *
     * @param array $data The data used to update the setting.
     * @param \Xetaravel\Models\Setting $setting The setting to update.
     *
     * @return bool
     */
    public static function update(array $data, Setting $setting): bool
    {
        $setting->name = Str::slug($data['name'], '.');
        $setting->value_int = $data['type'] ==  'value_int' ? (int) $data['value'] : null;
        $setting->value_str = $data['type'] ==  'value_str' ? (string) $data['value'] : null;
        $setting->value_bool = $data['type'] ==  'value_bool' ? (bool) $data['value'] : null;
        $setting->description = $data['description'];
        $setting->is_deletable = isset($data['is_deletable']) ? true : false;

        return $setting->save();
    }
}


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class frmTic
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.btn1 = New System.Windows.Forms.Button()
        Me.btn9 = New System.Windows.Forms.Button()
        Me.btn8 = New System.Windows.Forms.Button()
        Me.btn7 = New System.Windows.Forms.Button()
        Me.btn4 = New System.Windows.Forms.Button()
        Me.btn3 = New System.Windows.Forms.Button()
        Me.btn2 = New System.Windows.Forms.Button()
        Me.btn5 = New System.Windows.Forms.Button()
        Me.btn6 = New System.Windows.Forms.Button()
        Me.rdnPlayer1 = New System.Windows.Forms.RadioButton()
        Me.rdnPlayer2 = New System.Windows.Forms.RadioButton()
        Me.GroupBox1 = New System.Windows.Forms.GroupBox()
        Me.lblPlayer = New System.Windows.Forms.Label()
        Me.lblDisplay = New System.Windows.Forms.Label()
        Me.btnExit = New System.Windows.Forms.Button()
        Me.btnClear = New System.Windows.Forms.Button()
        Me.GroupBox1.SuspendLayout()
        Me.SuspendLayout()
        '
        'btn1
        '
        Me.btn1.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn1.Location = New System.Drawing.Point(80, 118)
        Me.btn1.Name = "btn1"
        Me.btn1.Size = New System.Drawing.Size(80, 70)
        Me.btn1.TabIndex = 0
        Me.btn1.UseVisualStyleBackColor = True
        '
        'btn9
        '
        Me.btn9.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn9.Location = New System.Drawing.Point(252, 270)
        Me.btn9.Name = "btn9"
        Me.btn9.Size = New System.Drawing.Size(80, 70)
        Me.btn9.TabIndex = 1
        Me.btn9.UseVisualStyleBackColor = True
        '
        'btn8
        '
        Me.btn8.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn8.Location = New System.Drawing.Point(166, 270)
        Me.btn8.Name = "btn8"
        Me.btn8.Size = New System.Drawing.Size(80, 70)
        Me.btn8.TabIndex = 2
        Me.btn8.UseVisualStyleBackColor = True
        '
        'btn7
        '
        Me.btn7.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn7.Location = New System.Drawing.Point(80, 270)
        Me.btn7.Name = "btn7"
        Me.btn7.Size = New System.Drawing.Size(80, 70)
        Me.btn7.TabIndex = 3
        Me.btn7.UseVisualStyleBackColor = True
        '
        'btn4
        '
        Me.btn4.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn4.Location = New System.Drawing.Point(80, 194)
        Me.btn4.Name = "btn4"
        Me.btn4.Size = New System.Drawing.Size(80, 70)
        Me.btn4.TabIndex = 4
        Me.btn4.UseVisualStyleBackColor = True
        '
        'btn3
        '
        Me.btn3.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn3.Location = New System.Drawing.Point(252, 118)
        Me.btn3.Name = "btn3"
        Me.btn3.Size = New System.Drawing.Size(80, 70)
        Me.btn3.TabIndex = 5
        Me.btn3.UseVisualStyleBackColor = True
        '
        'btn2
        '
        Me.btn2.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn2.Location = New System.Drawing.Point(166, 118)
        Me.btn2.Name = "btn2"
        Me.btn2.Size = New System.Drawing.Size(80, 70)
        Me.btn2.TabIndex = 6
        Me.btn2.UseVisualStyleBackColor = True
        '
        'btn5
        '
        Me.btn5.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn5.Location = New System.Drawing.Point(166, 194)
        Me.btn5.Name = "btn5"
        Me.btn5.Size = New System.Drawing.Size(80, 70)
        Me.btn5.TabIndex = 7
        Me.btn5.UseVisualStyleBackColor = True
        '
        'btn6
        '
        Me.btn6.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btn6.Location = New System.Drawing.Point(252, 194)
        Me.btn6.Name = "btn6"
        Me.btn6.Size = New System.Drawing.Size(80, 70)
        Me.btn6.TabIndex = 8
        Me.btn6.UseVisualStyleBackColor = True
        '
        'rdnPlayer1
        '
        Me.rdnPlayer1.AutoSize = True
        Me.rdnPlayer1.Location = New System.Drawing.Point(17, 19)
        Me.rdnPlayer1.Name = "rdnPlayer1"
        Me.rdnPlayer1.Size = New System.Drawing.Size(63, 17)
        Me.rdnPlayer1.TabIndex = 9
        Me.rdnPlayer1.TabStop = True
        Me.rdnPlayer1.Text = "X Turn"
        Me.rdnPlayer1.UseVisualStyleBackColor = True
        '
        'rdnPlayer2
        '
        Me.rdnPlayer2.AutoSize = True
        Me.rdnPlayer2.Location = New System.Drawing.Point(144, 19)
        Me.rdnPlayer2.Name = "rdnPlayer2"
        Me.rdnPlayer2.Size = New System.Drawing.Size(64, 17)
        Me.rdnPlayer2.TabIndex = 10
        Me.rdnPlayer2.TabStop = True
        Me.rdnPlayer2.Text = "O Turn"
        Me.rdnPlayer2.UseVisualStyleBackColor = True
        '
        'GroupBox1
        '
        Me.GroupBox1.Controls.Add(Me.rdnPlayer1)
        Me.GroupBox1.Controls.Add(Me.rdnPlayer2)
        Me.GroupBox1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.GroupBox1.Location = New System.Drawing.Point(80, 41)
        Me.GroupBox1.Name = "GroupBox1"
        Me.GroupBox1.Size = New System.Drawing.Size(252, 57)
        Me.GroupBox1.TabIndex = 11
        Me.GroupBox1.TabStop = False
        Me.GroupBox1.Text = "Select Player"
        '
        'lblPlayer
        '
        Me.lblPlayer.AutoSize = True
        Me.lblPlayer.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblPlayer.Location = New System.Drawing.Point(152, 9)
        Me.lblPlayer.Name = "lblPlayer"
        Me.lblPlayer.Size = New System.Drawing.Size(103, 20)
        Me.lblPlayer.TabIndex = 12
        Me.lblPlayer.Text = "TIc Tac Toe"
        '
        'lblDisplay
        '
        Me.lblDisplay.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblDisplay.Location = New System.Drawing.Point(74, 363)
        Me.lblDisplay.Name = "lblDisplay"
        Me.lblDisplay.Size = New System.Drawing.Size(233, 90)
        Me.lblDisplay.TabIndex = 13
        '
        'btnExit
        '
        Me.btnExit.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnExit.Location = New System.Drawing.Point(313, 411)
        Me.btnExit.Name = "btnExit"
        Me.btnExit.Size = New System.Drawing.Size(92, 42)
        Me.btnExit.TabIndex = 14
        Me.btnExit.Text = "Exit"
        Me.btnExit.UseVisualStyleBackColor = True
        '
        'btnClear
        '
        Me.btnClear.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnClear.Location = New System.Drawing.Point(313, 363)
        Me.btnClear.Name = "btnClear"
        Me.btnClear.Size = New System.Drawing.Size(92, 42)
        Me.btnClear.TabIndex = 15
        Me.btnClear.Text = "Restart"
        Me.btnClear.UseVisualStyleBackColor = True
        Me.btnClear.Visible = False
        '
        'frmTic
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackColor = System.Drawing.Color.Teal
        Me.ClientSize = New System.Drawing.Size(417, 465)
        Me.Controls.Add(Me.btnClear)
        Me.Controls.Add(Me.btnExit)
        Me.Controls.Add(Me.lblDisplay)
        Me.Controls.Add(Me.lblPlayer)
        Me.Controls.Add(Me.GroupBox1)
        Me.Controls.Add(Me.btn6)
        Me.Controls.Add(Me.btn5)
        Me.Controls.Add(Me.btn2)
        Me.Controls.Add(Me.btn3)
        Me.Controls.Add(Me.btn4)
        Me.Controls.Add(Me.btn7)
        Me.Controls.Add(Me.btn8)
        Me.Controls.Add(Me.btn9)
        Me.Controls.Add(Me.btn1)
        Me.Name = "frmTic"
        Me.Text = "Tic Tac Toe"
        Me.GroupBox1.ResumeLayout(False)
        Me.GroupBox1.PerformLayout()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents btn1 As System.Windows.Forms.Button
    Friend WithEvents btn9 As System.Windows.Forms.Button
    Friend WithEvents btn8 As System.Windows.Forms.Button
    Friend WithEvents btn7 As System.Windows.Forms.Button
    Friend WithEvents btn4 As System.Windows.Forms.Button
    Friend WithEvents btn3 As System.Windows.Forms.Button
    Friend WithEvents btn2 As System.Windows.Forms.Button
    Friend WithEvents btn5 As System.Windows.Forms.Button
    Friend WithEvents btn6 As System.Windows.Forms.Button
    Friend WithEvents rdnPlayer1 As System.Windows.Forms.RadioButton
    Friend WithEvents rdnPlayer2 As System.Windows.Forms.RadioButton
    Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
    Friend WithEvents lblPlayer As System.Windows.Forms.Label
    Friend WithEvents lblDisplay As System.Windows.Forms.Label
    Friend WithEvents btnExit As System.Windows.Forms.Button
    Friend WithEvents btnClear As System.Windows.Forms.Button

End Class


text:
<?php

	$t_entity 			= $this->getVar('t_item');
	$vn_entity_id 		= $t_entity->getPrimaryKey();

	$vs_title 			= $this->getVar('label');

	$va_access_values	= $this->getVar('access_values');

if (!$this->request->isAjax()) {
?>

<?php
			if (($this->getVar('is_in_result_list')) && ($vs_back_link = ResultContext::getResultsLinkForLastFind($this->request, 'ca_entities', _t("Back"), ''))) {
				if ($this->getVar('previous_id')) {
					print caNavLink($this->request, "‹ "._t("Previous"), '', 'Detail', 'Entity', 'Show', array('entity_id' => $this->getVar('previous_id')), array('id' => 'previous'));
				}else{
					print "‹ "._t("Previous");
				}
				print "   {$vs_back_link}   ";
				if ($this->getVar('next_id') > 0) {
					print caNavLink($this->request, _t("Next")." ›", '', 'Detail', 'Entity', 'Show', array('entity_id' => $this->getVar('next_id')), array('id' => 'next'));
				}else{
					print _t("Next")." ›";
				}
			}
?>

<?php print unicode_ucfirst($this->getVar('typename')).': '.$vs_title; ?>

<?php
			# --- identifier
			if($t_entity->get('idno')){
				print "
"._t("Identifier").": ".$t_entity->get('idno')."
";
			}
			# --- attributes
			$va_attributes = $this->request->config->get('ca_entities_detail_display_attributes');
			if(is_array($va_attributes) && (sizeof($va_attributes) > 0)){
				foreach($va_attributes as $vs_attribute_code){
					if($t_entity->get("ca_entities.".$vs_attribute_code)){
						print "
".$t_entity->getAttributeLabel($vs_attribute_code).": ".$t_entity->get("ca_entities.".$vs_attribute_code)."
";
					}
				}
			}
			# --- description
			if($this->request->config->get('ca_entities_description_attribute')){
				if($vs_description_text = $t_entity->get("ca_entities.".$this->request->config->get('ca_entities_description_attribute'))){
					print "

".$t_entity->getAttributeLabel($this->request->config->get('ca_entities_description_attribute')).": ".$vs_description_text."

";
?>

<?php
				}
			}
			# --- entities
			$va_entities = $t_entity->get("ca_entities", array("returnAsArray" => 1, 'checkAccess' => $va_access_values));
			if(sizeof($va_entities) > 0){
?>

<?php print _t("Related")." ".((sizeof($va_entities) > 1) ? _t("Entities") : _t("Entity")); ?>

<?php
				foreach($va_entities as $va_entity) {
					print "
".(($this->request->config->get('allow_detail_for_ca_entities')) ? caNavLink($this->request, $va_entity["label"], '', 'Detail', 'Entity', 'Show', array('entity_id' => $va_entity["entity_id"])) : $va_entity["label"])." (".$va_entity['relationship_typename'].")
";
				}
?>

<?php
			}

			# --- occurrences
			$va_occurrences = $t_entity->get("ca_occurrences", array("returnAsArray" => 1, 'checkAccess' => $va_access_values));
			$va_sorted_occurrences = array();
			if(sizeof($va_occurrences) > 0){
				$t_occ = new ca_occurrences();
				$va_item_types = $t_occ->getTypeList();
				foreach($va_occurrences as $va_occurrence) {
					$t_occ->load($va_occurrence['occurrence_id']);
					$va_sorted_occurrences[$va_occurrence['item_type_id']][$va_occurrence['occurrence_id']] = $va_occurrence;
				}

				foreach($va_sorted_occurrences as $vn_occurrence_type_id => $va_occurrence_list) {
?>

<?php print _t("Related")." ".$va_item_types[$vn_occurrence_type_id]['name_singular'].((sizeof($va_occurrence_list) > 1) ? "s" : ""); ?>

<?php
					foreach($va_occurrence_list as $vn_rel_occurrence_id => $va_info) {
						print "
".(($this->request->config->get('allow_detail_for_ca_occurrences')) ? caNavLink($this->request, $va_info["label"], '', 'Detail', 'Occurrence', 'Show', array('occurrence_id' => $vn_rel_occurrence_id)) : $va_info["label"])." (".$va_info['relationship_typename'].")
";
					}
					print "
";
				}
			}
			# --- places
			$va_places = $t_entity->get("ca_places", array("returnAsArray" => 1, 'checkAccess' => $va_access_values));
			if(sizeof($va_places) > 0){
				print "

"._t("Related Place").((sizeof($va_places) > 1) ? "s" : "")."
";
				foreach($va_places as $va_place_info){
					print "
".(($this->request->config->get('allow_detail_for_ca_places')) ? caNavLink($this->request, $va_place_info['label'], '', 'Detail', 'Place', 'Show', array('place_id' => $va_place_info['place_id'])) : $va_place_info['label'])." (".$va_place_info['relationship_typename'].")
";
				}
				print "
";
			}
			# --- collections
			$va_collections = $t_entity->get("ca_collections", array("returnAsArray" => 1, 'checkAccess' => $va_access_values));
			if(sizeof($va_collections) > 0){
				print "

"._t("Related Collection").((sizeof($va_collections) > 1) ? "s" : "")."
";
				foreach($va_collections as $va_collection_info){
					print "
";
					print (($this->request->config->get('allow_detail_for_ca_collections')) ? caNavLink($this->request, $va_collection_info['label'], '', 'Detail', 'Collection', 'Show', array('collection_id' => $va_collection_info['collection_id'])) : $va_collection_info['label'])." (".$va_collection_info['relationship_typename'].")
";
				}
				print "
";
			}
			# --- vocabulary terms
			$va_terms = $t_entity->get("ca_list_items", array("returnAsArray" => 1, 'checkAccess' => $va_access_values));
			if(sizeof($va_terms) > 0){
				print "

"._t("Subject").((sizeof($va_terms) > 1) ? "s" : "")."
";
				foreach($va_terms as $va_term_info){
					print "
".caNavLink($this->request, $va_term_info['label'], '', '', 'Search', 'Index', array('search' => $va_term_info['label']))."
";
				}
				print "
";
			}

?>

<?php
}
	// set parameters for paging controls view
	$this->setVar('other_paging_parameters', array(
		'entity_id' => $vn_entity_id
	));
	print $this->render('related_objects_grid.php');

if (!$this->request->isAjax()) {
?>

<?php
}
?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="entity" class="org.delta.core.metadata.EntityMetadata">
		<!--<property name="pkCode" value="id" />-->
		<property name="name" value="实体元数据" />
		<property name="tableName" value="MD_ENTITY" />
		<property name="fields">
			<list>
                <bean class="org.delta.core.metadata.FieldMetadata">
                    <property name="name" value="ID"/>
                    <property name="code" value="id"/>
                    <property name="columnName" value="ID"/>
                    <property name="dataType" value="string"/>
                    <property name="length" value="32"/>
                    <property name="primaryKey" value="true"/>
                    <property name="mandatory" value="false"/>
                </bean>
                <bean class="org.delta.core.metadata.FieldMetadata">
                    <property name="name" value="编码" />
                    <property name="code" value="code" />
                    <property name="columnName" value="code" />
                    <property name="dataType" value="string" />
                    <property name="length" value="64" />
                    <!--<property name="primaryKey" value="false" />-->
                    <property name="mandatory" value="false" />
                </bean>
				<bean class="org.delta.core.metadata.FieldMetadata">
					<property name="name" value="父键" />
					<property name="code" value="pid" />
					<property name="columnName" value="pid" />
					<property name="dataType" value="integer" />
					<!--<property name="primaryKey" value="false" />-->
					<property name="mandatory" value="false" />
				</bean>
				<bean class="org.delta.core.metadata.FieldMetadata">
					<property name="name" value="名称" />
					<property name="code" value="text" />
					<property name="columnName" value="name" />
					<property name="dataType" value="string" />
					<property name="length" value="64" />
					<!--<property name="primaryKey" value="false" />-->
					<property name="mandatory" value="false" />
				</bean>
				<bean class="org.delta.core.metadata.FieldMetadata">
					<property name="name" value="名称" />
					<property name="code" value="name" />
					<property name="columnName" value="name" />
					<property name="dataType" value="string" />
					<property name="length" value="64" />
					<!--<property name="primaryKey" value="false" />-->
					<property name="mandatory" value="false" />
				</bean>
				<bean class="org.delta.core.metadata.FieldMetadata">
					<property name="name" value="编码别名" />
					<property name="code" value="aliasCode" />
					<property name="columnName" value="alias_code" />
					<property name="dataType" value="string" />
					<property name="length" value="64" />
					<!--<property name="primaryKey" value="false" />-->
					<property name="mandatory" value="false" />
				</bean>
				<bean class="org.delta.core.metadata.FieldMetadata">
					<property name="name" value="表名" />
					<property name="code" value="tableName" />
					<property name="columnName" value="table_name" />
					<property name="dataType" value="string" />
					<property name="length" value="64" />
					<!--<property name="primaryKey" value="false" />-->
					<property name="mandatory" value="false" />
				</bean>
				<bean class="org.delta.core.metadata.FieldMetadata">
					<property name="name" value="删除标记" />
					<property name="code" value="delField" />
					<property name="columnName" value="del_field" />
					<property name="dataType" value="string" />
					<property name="length" value="64" />
					<!--<property name="primaryKey" value="false" />-->
					<property name="mandatory" value="false" />
				</bean>
				<bean class="org.delta.core.metadata.FieldMetadata">
					<property name="name" value="排序" />
					<property name="code" value="seq" />
					<property name="columnName" value="seq" />
					<property name="dataType" value="integer" />
					<!--<property name="primaryKey" value="false" />-->
					<property name="mandatory" value="false" />
				</bean>
                <bean class="org.delta.core.metadata.FieldMetadata">
                    <property name="name" value="备注"/>
                    <property name="code" value="remark"/>
                    <property name="columnName" value="remark"/>
                    <property name="dataType" value="string"/>
                    <!--<property name="primaryKey" value="false"/>-->
                    <property name="mandatory" value="false"/>
                </bean>
			</list>
		</property>
	</bean>
</beans>


text:
package cogx.compiler.codegenerator.opencl.fragments

/** The type of writing that a hyperkernel performs.
  *
  * @author Dick Carter
  */

private[cogx]
sealed abstract class WriteType(val isNonLocal: Boolean)

/** Initialization, before write type known. */
private[cogx]
case object WriteUnknown extends WriteType(false)

/** Kernel does not write at end of execution. */
private[cogx]
case object WriteNull extends WriteType(false)

/** Write, index based on _row, _column, _layer, and possibly _tensorElement */
private[cogx]
case object WriteLocal extends WriteType(false)

/** Write, index based on row, column, layer, and possibly tensorElement */
private[cogx]
case object WriteNonlocal extends WriteType(true)

/** Write, index based on row, column, layer, and tensorElement */
private[cogx]
case object WriteElementNonlocal extends WriteType(true)


text: default_app_config = 'providers.edu.citeseerx.apps.AppConfig'


text:
package com.identityblitz.jwt

import java.net.URI
import java.security.cert.X509Certificate
import com.identityblitz.json._
import scala.annotation.implicitNotFound
import org.apache.commons.codec.binary.Base64
import scala.util.{Failure, Success, Try}
import scala.util.Success
import scala.util.Failure
import com.identityblitz.json.JSuccess
import java.math.BigInteger
import java.security.interfaces.{RSAPublicKey => JRSAPublicKey, ECPublicKey => JECPublicKey}
import com.identityblitz.CryptoUtils
import java.security.{Key, KeyFactory, PrivateKey, PublicKey}
import java.security.spec.{RSAPublicKeySpec, RSAPrivateKeySpec}
import javax.crypto.spec.SecretKeySpec
import javax.crypto.SecretKey

/**
 *
 */
trait JwkToolkit {

  val cryptoService: CryptoService

  implicit object JwkReader extends JReader[JWK] {
    def read(v: JVal): JResult[JWK] = v match {
      case o: JObj => o match {
        case EcPublicKey(e) => JSuccess(e)
        case EcPrivateKey(e) => JSuccess(e)
        case RsaPublicKey(e) => JSuccess(e)
        case RsaPrivateKey(e) => JSuccess(e)
        case SymmetricKey(e) => JSuccess(e)
        case _ => JError("json.error.unknownJwk")
      }
      case _ => JError("json.error.expected.object")
    }
  }

  implicit object JwkWriter extends JWriter[JWK] {
    def write(o: JWK): JVal = throw new UnsupportedOperationException("not realised yet")
  }

  implicit object JX509Reader extends JReader[X509Certificate] {
    def read(v: JVal): JResult[X509Certificate] = v match {
      case JStr(s) => Try(cryptoService.createX509Cert(Base64.decodeBase64(s))) match {
        case Success(cert) => JSuccess(cert)
        case Failure(err) => JError(err.getMessage)
      }
      case _ => JError("json.error.expected.string")
    }
  }

  implicit object JX509Writer extends JWriter[X509Certificate] {
    def write(o: X509Certificate): JVal = throw new UnsupportedOperationException("not realised yet")
  }

  implicit object JBytesReader extends JReader[Array[Byte]] {
    def read(v: JVal): JResult[Array[Byte]] = v match {
      case JStr(s) => JSuccess(Base64.decodeBase64(s))
      case _ => JError("json.error.expected.string")
    }
  }

  implicit object JBytesWriter extends JWriter[Array[Byte]] {
    def write(o: Array[Byte]): JVal = throw new UnsupportedOperationException("not realised yet")
  }

  implicit object JUriReader extends JReader[URI] {
    def read(v: JVal): JResult[URI] = v match {
      case o: JStr => Try(new URI(o)) match {
        case Success(r) => JSuccess(r)
        case Failure(e) => JError(e.getMessage)
      }
      case _ => JError("json.error.expected.string")
    }
  }

  implicit object JUriWriter extends JWriter[URI] {
    def write(o: URI): JVal = JStr(o.toString)
  }

  object Use extends Enumeration {
    type Use = Value
    val sig = Value("sig")
    val enc = Value("enc")

    implicit object JUseReader extends JReader[Use] {
      def read(v: JVal): JResult[Use] = v match {
        case JStr(s) => Use.values.find(_.toString == s).map(JSuccess(_))
          .orElse(Option(JError("json.error.worngValueOfUse"))).get
        case _ => JError("json.error.expected.string")
      }
    }

    implicit object JUseWriter extends JWriter[Use] {
      def write(o: Use): JVal = JStr(o.toString)
    }
  }
  import Use._

  object KeyOps extends Enumeration {
    type KeyOps = Value
    val sign = Value("sign")
    val verify = Value("verify")
    val encrypt = Value("encrypt")
    val decrypt = Value("decrypt")
    val wrapKey = Value("wrapKey")
    val unwrapKey = Value("unwrapKey")
    val deriveKey = Value("deriveKey")
    val deriveBits = Value("deriveBits")

    implicit object JKeyOpsReader extends JReader[KeyOps]{
      def read(v: JVal): JResult[KeyOps] = v match {
        case JStr(s) => KeyOps.values.find(_.toString == s).map(JSuccess(_))
          .orElse(Option(JError("json.error.worngValueOfKeyOps"))).get
        case _ => JError("json.error.expected.string")
      }
    }

    implicit object JKeyOpsWriter extends JWriter[KeyOps] {
      def write(o: KeyOps): JVal = JStr(o.toString)
    }
  }
  import KeyOps._

  trait JWK {

    val kty: String

    val use: Option[Use]

    val key_ops: Option[Set[KeyOps]]

    val alg: Option[String]

    val kid: Option[String]

    val x5u: Option[URI]

    val x5c: Option[Array[X509Certificate]]

    val x5t: Option[Array[Byte]]

    /**
     * Handy methods.
     */

    val unwrapPublicKey: Option[PublicKey] = None

    val unwrapPrivateKey: Option[PrivateKey] = None

    def unwrapSymmetricKey(desiredAlg: String): Option[SecretKey] = None
  }

  object JWK {
    def apply(cert: X509Certificate): JWK = cert.getPublicKey match {
      case rsa: JRSAPublicKey => new RsaPublicKey(rsa.getModulus, rsa.getPublicExponent, None, None, None,
        None, None, Some(Array(cert)), Some(CryptoUtils.calcSha1(cert.getEncoded)))
      case _ => throw new IllegalArgumentException(" certificate with unsupported public key")
    }

  }

  case class EcPublicKey(crv: String,
                         x: Array[Byte],
                         y: Array[Byte],
                         use: Option[Use] = None,
                         key_ops: Option[Set[KeyOps]] = None,
                         alg: Option[String] = None,
                         kid: Option[String] = None,
                         x5u: Option[URI] = None,
                         x5c: Option[Array[X509Certificate]] = None,
                         x5t: Option[Array[Byte]] = None) extends JWK {

    //add some checks

    val kty: String = "EC"

    override val unwrapPublicKey = Option(CryptoUtils.genECPublicKey(crv, x, y))
  }

  object EcPublicKey {

    implicit object JEcPublicKeyReader extends JReader[EcPublicKey] {
      def read(v: JVal): JResult[EcPublicKey] = {
        JSuccess(new EcPublicKey((v \ "crv").as[String],
          Base64.decodeBase64((v \ "x").as[String]),
          Base64.decodeBase64((v \ "y").as[String]),
          (v \ "use").asOpt[Use],
          (v \ "key_ops").asOpt[Array[KeyOps]].map(_.toSet),
          (v \ "alg").asOpt[String],
          (v \ "kid").asOpt[String],
          (v \ "x5u").asOpt[URI],
          (v \ "x5c").asOpt[Array[X509Certificate]],
          (v \ "x5t").asOpt[Array[Byte]]))
      }
    }

    def unapply(jwk: JObj): Option[EcPublicKey] =
      if(jwk("kty").as[String] == "EC" &&
        jwk.fields.contains("crv") &&
        jwk.fields.contains("x") &&
        jwk.fields.contains("y") &&
        !jwk.fields.contains("d")) jwk.asOpt[EcPublicKey] else None

  }

  case class EcPrivateKey(crv: String,
                          x: Array[Byte],
                          y: Array[Byte],
                          d: Array[Byte],
                          use: Option[Use] = None,
                          key_ops: Option[Set[KeyOps]] = None,
                          alg: Option[String] = None,
                          kid: Option[String] = None,
                          x5u: Option[URI] = None,
                          x5c: Option[Array[X509Certificate]] = None,
                          x5t: Option[Array[Byte]] = None) extends JWK {

    //add some checks

    val kty: String = "EC"

    override val unwrapPublicKey = Option(CryptoUtils.genECPublicKey(crv, x, y))
    override val unwrapPrivateKey = Option(CryptoUtils.genECPrivateKey(crv, d))
  }

  object EcPrivateKey {

    implicit object JEcPrivateKeyReader extends JReader[EcPrivateKey] {
      def read(v: JVal): JResult[EcPrivateKey] = {
        JSuccess(new EcPrivateKey((v \ "crv").as[String],
          Base64.decodeBase64((v \ "x").as[String]),
          Base64.decodeBase64((v \ "y").as[String]),
          Base64.decodeBase64((v \ "d").as[String]),
          (v \ "use").asOpt[Use],
          (v \ "key_ops").asOpt[Array[KeyOps]].map(_.toSet),
          (v \ "alg").asOpt[String],
          (v \ "kid").asOpt[String],
          (v \ "x5u").asOpt[URI],
          (v \ "x5c").asOpt[Array[X509Certificate]],
          (v \ "x5t").asOpt[Array[Byte]]
        ))
      }
    }

    def unapply(jwk: JObj): Option[EcPrivateKey] =
      if(jwk.fields.contains("crv") &&
        jwk.fields.contains("x") &&
        jwk.fields.contains("y") &&
        jwk.fields.contains("d")) jwk.asOpt[EcPrivateKey] else None

  }

  case class RsaPublicKey(n: BigInteger,
                          e: BigInteger,
                          use: Option[Use] = None,
                          key_ops: Option[Set[KeyOps]] = None,
                          alg: Option[String] = None,
                          kid: Option[String] = None,
                          x5u: Option[URI] = None,
                          x5c: Option[Array[X509Certificate]] = None,
                          x5t: Option[Array[Byte]] = None) extends JWK {

    x5c.foreach(a => {
      val key = a.head.getPublicKey.asInstanceOf[JRSAPublicKey]
      if(!key.getModulus.equals(n) || !key.getPublicExponent.equals(e))
        throw new IllegalStateException("JWK public key parameters does not match ones from the corresponding X.509 certificate.")
    })

    val kty: String = "RSA"

    override val unwrapPublicKey = Option(KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(n, e)))
  }

  object RsaPublicKey {

    implicit object JRsaPublicKeyReader extends JReader[RsaPublicKey] {
      def read(v: JVal): JResult[RsaPublicKey] = {
        JSuccess(new RsaPublicKey(new BigInteger(1, Base64.decodeBase64((v \ "n").as[String])),
          new BigInteger(1, Base64.decodeBase64((v \ "e").as[String])),
          (v \ "use").asOpt[Use],
          (v \ "key_ops").asOpt[Array[KeyOps]].map(_.toSet),
          (v \ "alg").asOpt[String],
          (v \ "kid").asOpt[String],
          (v \ "x5u").asOpt[URI],
          (v \ "x5c").asOpt[Array[X509Certificate]],
          (v \ "x5t").asOpt[Array[Byte]]))
      }
    }

    def unapply(jwk: JObj): Option[RsaPublicKey] =
      if(jwk("kty").as[String] == "RSA" &&
        jwk.fields.contains("n") &&
        jwk.fields.contains("e") &&
        !jwk.fields.contains("d")) jwk.asOpt[RsaPublicKey] else None

  }

  case class PrimeInfo(r: BigInteger,
                       d: BigInteger,
                       t: BigInteger)

  case class RsaPrivateKey(n: BigInteger,
                           e: BigInteger,
                           d: BigInteger,
                           p: Option[BigInteger] = None,
                           q: Option[BigInteger] = None,
                           dp: Option[BigInteger] = None,
                           dq: Option[BigInteger] = None,
                           qi: Option[BigInteger] = None,
                           oth: Option[Array[PrimeInfo]] = None,
                           use: Option[Use] = None,
                           key_ops: Option[Set[KeyOps]] = None,
                           alg: Option[String] = None,
                           kid: Option[String] = None,
                           x5u: Option[URI] = None,
                           x5c: Option[Array[X509Certificate]] = None,
                           x5t: Option[Array[Byte]] = None) extends JWK {

    x5c.foreach(a => {
      val key = a.head.getPublicKey.asInstanceOf[JRSAPublicKey]
      if(!key.getModulus.equals(n) || !key.getPublicExponent.equals(e))
        throw new IllegalStateException("JWK private key parameters does not match ones from the corresponding X.509 certificate.")
    })

    val kty: String = "RSA"

    override val unwrapPublicKey = Option(KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(n, e)))
    override val unwrapPrivateKey = Option(KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(n, d)))
  }

  object RsaPrivateKey {

    implicit object JPrimeInfo extends JReader[PrimeInfo]{
      def read(v: JVal): JResult[PrimeInfo] = JSuccess(
        new PrimeInfo(new BigInteger(1, Base64.decodeBase64((v \ "r").as[String])),
          new BigInteger(1, Base64.decodeBase64((v \ "d").as[String])),
          new BigInteger(1, Base64.decodeBase64((v \ "t").as[String]))))
    }

    implicit object JRsaPrivateKeyReader extends JReader[RsaPrivateKey] {
      def read(v: JVal): JResult[RsaPrivateKey] = {
        JSuccess(new RsaPrivateKey(new BigInteger(1, Base64.decodeBase64((v \ "n").as[String])),
          new BigInteger(1, Base64.decodeBase64((v \ "e").as[String])),
          new BigInteger(1, Base64.decodeBase64((v \ "d").as[String])),
          (v \ "p").asOpt[String].map(a => new BigInteger(1, Base64.decodeBase64(a))),
          (v \ "q").asOpt[String].map(a => new BigInteger(1, Base64.decodeBase64(a))),
          (v \ "dp").asOpt[String].map(a => new BigInteger(1, Base64.decodeBase64(a))),
          (v \ "dq").asOpt[String].map(a => new BigInteger(1, Base64.decodeBase64(a))),
          (v \ "qi").asOpt[String].map(a => new BigInteger(1, Base64.decodeBase64(a))),
          (v \ "oth").asOpt[Array[PrimeInfo]],
          (v \ "use").asOpt[Use],
          (v \ "key_ops").asOpt[Array[KeyOps]].map(_.toSet),
          (v \ "alg").asOpt[String],
          (v \ "kid").asOpt[String],
          (v \ "x5u").asOpt[URI],
          (v \ "x5c").asOpt[Array[X509Certificate]],
          (v \ "x5t").asOpt[Array[Byte]]))
      }
    }

    def unapply(jwk: JObj): Option[RsaPrivateKey] =
      if(jwk("kty").as[String] == "RSA" &&
        jwk.fields.contains("n") &&
        jwk.fields.contains("e") &&
        jwk.fields.contains("d")) jwk.asOpt[RsaPrivateKey] else None

  }

  case class SymmetricKey(k: Array[Byte],
                          use: Option[Use] = None,
                          key_ops: Option[Set[KeyOps]] = None,
                          alg: Option[String] = None,
                          kid: Option[String] = None,
                          x5u: Option[URI] = None,
                          x5c: Option[Array[X509Certificate]] = None,
                          x5t: Option[Array[Byte]] = None) extends JWK {

    //add some checks

    val kty: String = "oct"

    override def unwrapSymmetricKey(desiredAlg: String): Option[SecretKey] = Option(new SecretKeySpec(k, desiredAlg))
  }

  object SymmetricKey {

    implicit object JSymmetricKeyReader extends JReader[SymmetricKey] {
      def read(v: JVal): JResult[SymmetricKey] = {
        JSuccess(new SymmetricKey(Base64.decodeBase64((v \ "k").as[String]),
          (v \ "use").asOpt[Use],
          (v \ "key_ops").asOpt[Array[KeyOps]].map(_.toSet),
          (v \ "alg").asOpt[String],
          (v \ "kid").asOpt[String],
          (v \ "x5u").asOpt[URI],
          (v \ "x5c").asOpt[Array[X509Certificate]],
          (v \ "x5t").asOpt[Array[Byte]]))
      }
    }

    def unapply(jwk: JObj): Option[SymmetricKey] =
      if(jwk("kty").as[String] == "oct" &&
        jwk.fields.contains("k")) jwk.asOpt[SymmetricKey] else None

  }

  @implicitNotFound("No Kids register found. Try to implement an implicit KidsRegister.")
  trait KidsRegister {

    def apply(kid: String): JWK
    def get(kid: String): Option[JWK]

    def defaultKids(alg: String): Seq[JWK]
    def defaultKids(alg: String, ctx: Map[String, String]): Seq[JWK]

  }

  @implicitNotFound("No cryptographic service found. Try to implement an implicit CryptoService.")
  trait CryptoService {

    def sign(alg: String, jwk: JWK, plainText: Array[Byte]): Array[Byte]

    def sign(desiredAlg: String, key: Key, plainText: Array[Byte]): Array[Byte]

    def verify(desiredAlg: String, key: Key, plainText: Array[Byte], signature: Array[Byte]): Boolean

    def encrypt(alg: String, jwk: JWK, plainText: Array[Byte]): Array[Byte]

    def decrypt(alg: String, jwk: JWK, cipherText: Array[Byte]): Array[Byte]

    def createX509Cert(der: Array[Byte]): X509Certificate

    def verifyX509CertChain(chain: Array[X509Certificate]): Option[X509Certificate]

  }

}


text:
#include <stdint.h>
#include "bacenum.h"
#include "bacdcode.h"
#include "bacdef.h"
#include "abort.h"
/** @file abort.c  Abort Encoding/Decoding */
/* Helper function to avoid needing additional entries in service data structures
 * when passing back abort status.
 * Convert from error code to abort code.
 * Anything not defined converts to ABORT_REASON_OTHER.
 * Will need reworking if it is required to return proprietary abort codes.
 */
BACNET_ABORT_REASON abort_convert_error_code(
    BACNET_ERROR_CODE error_code)
{
    BACNET_ABORT_REASON abort_code = ABORT_REASON_OTHER;

    switch (error_code) {
        case ERROR_CODE_ABORT_BUFFER_OVERFLOW:
            abort_code = ABORT_REASON_BUFFER_OVERFLOW;
            break;
        case ERROR_CODE_ABORT_INVALID_APDU_IN_THIS_STATE:
            abort_code = ABORT_REASON_INVALID_APDU_IN_THIS_STATE;
            break;
        case ERROR_CODE_ABORT_PREEMPTED_BY_HIGHER_PRIORITY_TASK:
            abort_code = ABORT_REASON_PREEMPTED_BY_HIGHER_PRIORITY_TASK;
            break;
        case ERROR_CODE_ABORT_SEGMENTATION_NOT_SUPPORTED:
            abort_code = ABORT_REASON_SEGMENTATION_NOT_SUPPORTED;
            break;
        case ERROR_CODE_ABORT_PROPRIETARY:
            abort_code = (BACNET_ABORT_REASON) FIRST_PROPRIETARY_ABORT_REASON;
            break;
        case ERROR_CODE_ABORT_OTHER:
        default:
            abort_code = ABORT_REASON_OTHER;
            break;
    }

    return (abort_code);
}
int My_Max()
{
	return 110;
}
/* encode service */
int abort_encode_apdu(
    uint8_t * apdu,
    uint8_t invoke_id,
    uint8_t abort_reason,
    bool server)
{
    int apdu_len = 0;   /* total length of the apdu, return value */

    if (apdu) {
        if (server)
            apdu[0] = PDU_TYPE_ABORT | 1;
        else
            apdu[0] = PDU_TYPE_ABORT;
        apdu[1] = invoke_id;
        apdu[2] = abort_reason;
        apdu_len = 3;
    }

    return apdu_len;
}

#if !BACNET_SVC_SERVER
/* decode the service request only */
int abort_decode_service_request(
    uint8_t * apdu,
    unsigned apdu_len,
    uint8_t * invoke_id,
    uint8_t * abort_reason)
{
    int len = 0;

    if (apdu_len > 0) {
        if (invoke_id)
            *invoke_id = apdu[0];
        if (abort_reason)
            *abort_reason = apdu[1];
    }

    return len;
}
#endif

#ifdef TEST
#include <assert.h>
#include <string.h>
#include "ctest.h"

/* decode the whole APDU - mainly used for unit testing */
int abort_decode_apdu(
    uint8_t * apdu,
    unsigned apdu_len,
    uint8_t * invoke_id,
    uint8_t * abort_reason,
    bool * server)
{
    int len = 0;

    if (!apdu)
        return -1;
    /* optional checking - most likely was already done prior to this call */
    if (apdu_len > 0) {
        if ((apdu[0] & 0xF0) != PDU_TYPE_ABORT)
            return -1;
        if (apdu[0] & 1)
            *server = true;
        else
            *server = false;
        if (apdu_len > 1) {
            len =
                abort_decode_service_request(&apdu[1], apdu_len - 1, invoke_id,
                abort_reason);
        }
    }

    return len;
}

void testAbortAPDU(
    Test * pTest,
    uint8_t invoke_id,
    uint8_t abort_reason,
    bool server)
{
    uint8_t apdu[480] = { 0 };
    int len = 0;
    int apdu_len = 0;
    uint8_t test_invoke_id = 0;
    uint8_t test_abort_reason = 0;
    bool test_server = false;

    len = abort_encode_apdu(&apdu[0], invoke_id, abort_reason, server);
    apdu_len = len;
    ct_test(pTest, len != 0);
    len =
        abort_decode_apdu(&apdu[0], apdu_len, &test_invoke_id,
        &test_abort_reason, &test_server);
    ct_test(pTest, len != -1);
    ct_test(pTest, test_invoke_id == invoke_id);
    ct_test(pTest, test_abort_reason == abort_reason);
    ct_test(pTest, test_server == server);

    return;
}

void testAbort(
    Test * pTest)
{
    uint8_t apdu[480] = { 0 };
    int len = 0;
    int apdu_len = 0;
    uint8_t invoke_id = 0;
    uint8_t test_invoke_id = 0;
    uint8_t abort_reason = 0;
    uint8_t test_abort_reason = 0;
    bool server = false;
    bool test_server = false;

    len = abort_encode_apdu(&apdu[0], invoke_id, abort_reason, server);
    ct_test(pTest, len != 0);
    apdu_len = len;
    len =
        abort_decode_apdu(&apdu[0], apdu_len, &test_invoke_id,
        &test_abort_reason, &test_server);
    ct_test(pTest, len != -1);
    ct_test(pTest, test_invoke_id == invoke_id);
    ct_test(pTest, test_abort_reason == abort_reason);
    ct_test(pTest, test_server == server);

    /* change type to get negative response */
    apdu[0] = PDU_TYPE_REJECT;
    len =
        abort_decode_apdu(&apdu[0], apdu_len, &test_invoke_id,
        &test_abort_reason, &test_server);
    ct_test(pTest, len == -1);

    /* test NULL APDU */
    len =
        abort_decode_apdu(NULL, apdu_len, &test_invoke_id, &test_abort_reason,
        &test_server);
    ct_test(pTest, len == -1);

    /* force a zero length */
    len =
        abort_decode_apdu(&apdu[0], 0, &test_invoke_id, &test_abort_reason,
        &test_server);
    ct_test(pTest, len == 0);

    /* check them all...   */
    for (invoke_id = 0; invoke_id < 255; invoke_id++) {
        for (abort_reason = 0; abort_reason < 255; abort_reason++) {
            testAbortAPDU(pTest, invoke_id, abort_reason, false);
            testAbortAPDU(pTest, invoke_id, abort_reason, true);
        }
    }
}

#ifdef TEST_ABORT
int main(
    void)
{
    Test *pTest;
    bool rc;

    pTest = ct_create("BACnet Abort", NULL);
    /* individual tests */
    rc = ct_addTestFunction(pTest, testAbort);
    assert(rc);

    ct_setStream(pTest, stdout);
    ct_run(pTest);
    (void) ct_report(pTest);
    ct_destroy(pTest);

    return 0;
}
#endif /* TEST_ABORT */
#endif /* TEST */


text:
package gov.nih.nci.cabig.caaers.service.migrator.report;

import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.Fixtures;
import gov.nih.nci.cabig.caaers.domain.InterventionSite;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.OtherAEIntervention;
import gov.nih.nci.cabig.caaers.domain.OtherIntervention;
import gov.nih.nci.cabig.caaers.domain.PriorTherapy;
import gov.nih.nci.cabig.caaers.domain.SAEReportPriorTherapy;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.domain.SurgeryIntervention;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import junit.framework.TestCase;

/**
 * User: medav
 * Date: 1/28/13
 */
public class SAEReportPriorTherapyMigratorTest extends TestCase {

	SAEReportPriorTherapyMigrator migrator;
    ExpeditedAdverseEventReport src;
    ExpeditedAdverseEventReport dest;

    public void setUp() throws Exception {
        migrator = new SAEReportPriorTherapyMigrator();
        src = new ExpeditedAdverseEventReport();
        dest = new ExpeditedAdverseEventReport();

        Study study = Fixtures.createStudy("CTEP");
        Organization org = Fixtures.createOrganization("Mayo Clinic");

        StudySite site = Fixtures.createStudySite(org, 26);
        study.addStudySite(site);

        AdverseEventReportingPeriod period = Fixtures.createReportingPeriod();
        StudyParticipantAssignment assignment = Fixtures.createAssignment();
        period.setAssignment(assignment);
        dest.setReportingPeriod(period);

        OtherIntervention oi = new OtherIntervention();
        oi.setStudy(study);
        String desc = "Testing SAE Report Prior Therapy Migrator";

        PriorTherapy therapy = Fixtures.createPriorTherapy("Prior Therapy");
        SAEReportPriorTherapy si = Fixtures.createSAEReportPriorTherapy(desc, null, null, therapy);
        src.getSaeReportPriorTherapies().add(si);

    }

    public void testMigrateWithValues() throws Exception {

    //	migrator.migrate(src,dest,new DomainObjectImportOutcome<ExpeditedAdverseEventReport>());
    //	assertEquals(1, dest.getSaeReportPriorTherapies().size());
    //	assertEquals("Testing SAE Report Prior Therapy Migrator", dest.getSaeReportPriorTherapies().get(0).getOther());
    }
}


text:
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { StackNavigator } from 'react-navigation';

import HelpText from '../assets/help.txt.js';

const styles = StyleSheet.create({
  paragraph: {
    margin: 8,
    fontSize: 16,
  },
});

class HelpView extends Component {
  static navigationOptions = {
    tabBarLabel: 'Help',
    title: 'Help',
    tabBarIcon: ({ tintColor, focused }) =>
      <Ionicons
        name={focused ? 'ios-help-circle' : 'ios-help-circle-outline'}
        size={32}
        style={{ color: tintColor }}
      />,
  };

  render() {
    return (
      <View>
        <Text style={styles.paragraph}>
          {HelpText}
        </Text>
      </View>
    );
  }
}

export default StackNavigator({
  Help: {
    screen: HelpView,
  },
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Blog | Post">
    <meta name="author" content="Alex">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="../stylesheets/default.css">

    <link rel="shortcut icon" href="http://placehold.it/16x16/1abc9c&ext=P" >
    <link rel="icon" type="image/gif" href="hhttp://placehold.it/16x16/1abc9c&text=P" >

    <title>Title | Subtitle </title>

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>
          Alex Green

About Me

Blog

Projects

Contact

JavaScript

Changing Gears

July 12th, 2015

        After spending weeks getting comfortable(somewhat) with Ruby I've now been tasked with doing the same in JavaScript.  It's been a little bit of a difficult task for me - I've gotten used to the syntax and awesome methods available to me with Ruby, and I'm having a little bit of a struggle in feeling like I can accomplish the same things with JavaScript.

      Where to start? I feel as if JavaScript isn't nearly as helpful or easy to read as Ruby - the code feels harder to follow mentally and I've had to make a point of making thoughtful comments where need be to make sure I keep track of exactly what I am doing. From variable declariation - to functions - to even punctuation used, it all feels different. For this post I will look at Ruby hashes compared to Javascript objects.

    In Ruby, when you create a hash it should look something like this

    hash["a" => 1, "b" => 2, "c" => 3]

    In this case your keys would be a,b,c and your values would be 1,2,3.

    In Javascript to create an object it should look something like this

    object{

    a: 1,

    b: 2,

    c: 3

    };

    In this case we would get the same keys(properties) and their values.

Contact Me

              <form class="form-horizontal">

    Name

      <input type="text" class="form-control input-lg" id="Name" placeholder="Name">

    Email

      <input type="Email" class="form-control input-lg" id="Email" placeholder="Email">

    Message

     <textarea class="form-control" id="Message" placeholder="Love? Hate? Let me hear it."rows="3"></textarea>

      <button type="submit" class="btn btn-primary btn-lg pull-right input-lg">Send</button>

</form>

Copyright - All Right Reserved 2015


text:
require 'spec_helper'

TestStepRunner.class_eval do
  include NextStep::Payload

  def modify_one
    @payload += 1
    proceed
  end

  def modify_two
    @payload += 2
    proceed
  end

end

module NextStep

  RSpec.describe Payload do
    it "sets a payload instance variable" do
      runner = TestStepRunner.new
      runner.set_initial_payload(0)
      expect(runner.payload).to eql 0
    end

    it "allows the steps to modify the payload" do
      runner = TestStepRunner.new
      runner.set_initial_payload(0)
      runner.run_symbols([:modify_one, :modify_two])
      expect(runner.payload).to eql 3
    end

    it "saves the payload for each step in the step result" do
      runner = TestStepRunner.new
      runner.set_initial_payload(0)
      runner.run_symbols([:modify_one, :modify_two])

      first_result = runner.step_results.first
      last_result = runner.step_results.last

      expect(first_result.payload).to eql 1
      expect(last_result.payload).to eql 3
    end

    it "returns the final payload" do
      runner = TestStepRunner.new
      runner.set_initial_payload(0)
      runner.run_symbols([:modify_one, :modify_two])
      expect(runner.final_payload).to eql 3
    end
  end
end