text:
<?template scope="application"?>
<?php

// No direct access
defined('_JEXEC') or die;

/**
 * {{ project.title }} Component Helper
 *
{# align("\t", '  ') #}
 * @version    Release: {{ project.version }}
 * @package    {{ project.name | class }}
 * @since      1.0.0
{# endalign #}
 */
class {{ project.name | class }}AdminHelper
{
{# override properties #}{# endoverride #}
{# override addSubmenu #}

	/**
	 * Configure the link bar
	 *
{# align("\t", '  ') #}
	 * @param	string	$viewName	  The name of the active view
	 *
	 * @return  void
{# endalign #}
	 */
	public static function addSubmenu($viewName = '')
	{
{% for entity in project.entities %}
{% if entity.role == 'main' %}
		JSubMenuHelper::addEntry(
			JText::_('COM_{{ project.name | constant }}_{{ entity.name | constant }}_SUBMENU'),
			'index.php?option=com_{{ project.name | file }}&view={{ entity.name | plural | file }}',
			$viewName == '{{ entity.name | plural | file }}'
		);

{% if entity.special.category %}
		JSubMenuHelper::addEntry(
			JText::_('COM_{{ project.name | constant }}_{{ entity.name | constant }}_CATEGORIES'),
			'index.php?option=com_categories&extension=com_{{ project.name | file }}',
			$viewName == 'categories'
		);

		if ($viewName == 'categories')
		{
			JToolBarHelper::title(
				JText::sprintf('COM_{{ project.name | constant }}_CATEGORIES_TITLE', JText::_('com_{{ project.name | file }}')),
				'{{ entity.name | plural | file }}-categories'
			);
		}

{% endif %}
{% endif %}
{% endfor %}
{% for entity in project.entities %}
{% if entity.role != 'main' and entity.role != 'map' and entity.role != 'lookup' %}
		JSubMenuHelper::addEntry(
			JText::_('COM_{{ project.name | constant }}_{{ entity.name | constant }}_SUBMENU'),
			'index.php?option=com_{{ project.name | file }}&view={{ entity.name | plural | file }}',
			$viewName == '{{ entity.name | plural | file }}'
		);

{% endif %}
{% endfor %}
		return;
	}
{# endoverride #}
{# override getActions #}
{% for entity in project.entities %}
{% if entity.role == 'main' %}

	/**
	 * Get a list of the actions that can be performed
	 *
{# align("\t", '  ') #}
{% if entity.special.category %}
	 * @param	int	$categoryId	  The category ID
{% endif %}
	 * @param   int  ${{ entity.name | singular | file }}  The {{ entity.name | title }} ID
	 *
	 * @return  JObject
{# endalign #}
	 */
	public static function getActions({% if entity.special.category %}$categoryId = 0, {% endif %}${{ entity.name | singular | file }} = 0)
	{
		$user   = JFactory::getUser();
		$result = new JObject;

		if (empty(${{ entity.name | singular | file }}){% if entity.special.category %} && empty($categoryId){% endif %})
		{
			$assetName = 'com_{{ project.name | file }}';
		}
{% if entity.special.category %}
		elseif (empty(${{ entity.name | singular | file }}))
		{
			$assetName = 'com_{{ project.name | file }}.category.' . (int) $categoryId;
		}
{% endif %}
		else
		{
			$assetName = 'com_{{ project.name | file }}.{{ entity.name | singular | file }}.' . (int) ${{ entity.name | singular | file }};
		}

		$actions = array(
			'core.admin', 'core.manage', 'core.create', 'core.edit', 'core.edit.own', 'core.edit.state', 'core.delete'
		);

		foreach ($actions as $action)
		{
			$result->set($action, $user->authorise($action, $assetName));
		}

		return $result;
	}
{% endif %}
{% endfor %}
{# endoverride #}
{# override truncate #}

	/**
	 * Truncate a string
	 *
	 * If the string is shortened, a horizontal ellipsis is added, and the string is surrounded by a
	 * span with a title containing the complete string.
	 *
	 * ATTN: This method is *not* HTML safe.
	 *
{# align("\t", '  ') #}
	 * @param	string	$str	  The string to be truncated
	 * @param	int	$len	  The maximum length of the truncated string
	 *
	 * @return  string
{# endalign #}
	 */
	public static function truncate($str, $len = 50)
	{
		$str = trim($str);
		$truncated = trim(JString::substr($str, 0, $len - 1));
		if ($truncated != $str)
		{
			$truncated = '' . htmlspecialchars($truncated) . '…';
		}
		return $truncated;
	}
{# endoverride #}
{# override methods #}{# endoverride #}
}


text:
#ifndef HALM_PIN_H_
#error This header should not be included directly
#endif

#ifndef HALM_PLATFORM_STM32_PIN_H_
#define HALM_PLATFORM_STM32_PIN_H_
/*----------------------------------------------------------------------------*/
#undef HEADER_PATH
#define HEADER_PATH <halm/platform/PLATFORM_TYPE/PLATFORM/pin.h>
#include HEADER_PATH
/*----------------------------------------------------------------------------*/
#endif /* HALM_PLATFORM_STM32_PIN_H_ */

redpajama_set_name: RedPajamaGithub


text:
title: "Device Orientation"
description: "Os eventos de orientação e movimento do dispositivo oferecem acesso ao acelerômetro integrado, giroscópio e compasso em dispositivos móveis."
updated_on: 2014-10-21
notes:
  not-stable:
    - "Tenha muito cuidado ao decidir usar os eventos de orientação ou movimento do dispositivo.  Infelizmente, nem todos os navegadores usam o mesmo sistema de coordenadas e podem relatar valores diferentes em situações idênticas."
---

  Os eventos de orientação e movimento do dispositivo oferecem acesso ao acelerômetro integrado, giroscópio e compasso em dispositivos móveis.

Esses eventos podem ser usados para vários fins; por exemplo, nos jogos para
controlar a direção da personagem ou determinar a altura na qual uma personagem
deve pular. Quando usado com a Geolocalização, pode criar um sistema de navegação
giro a giro mais preciso ou fornecer informações sobre onde fica uma loja.

{% include shared/remember.liquid title="Warning" list=page.notes.not-stable %}

## Qual objetivo é utilizado?

Para utilizar os dados retornados pelos eventos de orientação e movimentação do dispositivo,
é importante compreender os valores fornecidos.

### Frame de coordenada terrestre

O frame de coordenada terrestre, descrito através dos valores `X`, `Y` e `Z`, é alinhado
com base na gravidade e na orientação magnética padrão.

    X: representa a direção leste-oeste (onde o leste é positivo).

    Y: representa a direção norte-sul (onde o norte é positivo).

    Z: representa uma direção para cima e para baixo, perpendicular ao chão
    (onde para cima é positivo).

### Frame de coordenada do dispositivo

O frame de coordenada do dispositivo, descrito através dos valores `x`, `y` e `z`, é alinhado
com base no centro do dispositivo.

    x: no plano da tela, positivo para a direita.

    y: no plano da tela, positivo em direção ao topo.

    z: perpendicular à tela ou ao teclado, positivo se estendendo
 .

Em um telefone ou tablet, a orientação do dispositivo é baseada na orientação
típica da tela.  Para telefones e tablets, baseia-se no dispositivo
estando no modo retrato. Para computadores desktop ou laptop, a orientação é
considerada em relação ao teclado.

### Dados de rotação

Os dados de rotação são retornados como [ângulo de Euler](http://en.wikipedia.org/wiki/Euler_angles),
representando o número de graus de diferença entre o frame de coordenada
do dispositivo e o frame de coordenada terrestre.

    alpha: A orientação ao redor do eixo z e é 0° quando o topo do
    dispositivo está apontado diretamente para o norte.  Conforme o dispositivo é girado no sentido anti-horário
    o valor de`alpha` aumenta.

    beta: A orientação ao redor do eixo x e é 0° quando o topo e
    a parte inferior do dispositivo estão equidistantes da superfície terrestre. O valor
    aumenta conforme o topo do dispositivo é inclinado em direção à superfície terrestre.

    gamma: A rotação ao redor do eixo y e é 0° quando a parte direita e
    esquerda do dispositivo estão equidistantes da superfície terrestre.  O valor
    aumenta conforme o lado direito do dispositivo é inclinado em direção à superfície terrestre.


text:
angular.module("proton.authentication", [
    "proton.pmcw",
    "proton.models"
])

.factory('authentication', function(
    pmcw,
    CONSTANTS,
    $state,
    $rootScope,
    $q,
    $http,
    $timeout,
    $log,
    errorReporter,
    url,
    notify,
    CONFIG
) {
    // PRIVATE FUNCTIONS
    var auth = {
        // These headers are used just once for the /cookies route, then we forget them and use cookies and x-pm-session header instead.
        setAuthHeaders: function() {
            // API version
            if ( auth.data.SessionToken ) {
                // we have a session token, so we can remove the old stuff
                $log.debug('setAuthHeaders:1');
                $http.defaults.headers.common["x-pm-session"] = auth.data.SessionToken;
                $http.defaults.headers.common.Authorization = undefined;
                $http.defaults.headers.common["x-pm-uid"] = undefined;
                window.sessionStorage.removeItem(CONSTANTS.OAUTH_KEY + ":AccessToken");
                window.sessionStorage.removeItem(CONSTANTS.OAUTH_KEY + ":Uid");
                window.sessionStorage.removeItem(CONSTANTS.OAUTH_KEY + ":RefreshToken");
            }
            else {
                // we need the old stuff for now
                $log.debug('setAuthHeaders:2');
                $http.defaults.headers.common.Authorization = "Bearer " + auth.data.AccessToken;
                $http.defaults.headers.common["x-pm-uid"] = auth.data.Uid;
            }
        },

        fetchUserInfo: function(uid) {

            var deferred = $q.defer();

            api.user = $http.get(url.get() + "/users", {
                params: {
                    id: uid
                }
            });

            api.user.then(
                function(result) {

                    var user = result.data.User;

                    if (!user.EncPrivateKey) {
                        api.logout();
                        deferred.reject();
                    }
                    else {
                        $q.all([
                            $http.get(url.get() + "/contacts"),
                            $http.get(url.get() + "/labels")
                        ]).then(
                            function(result) {
                                user.Contacts = result[0].data.Contacts;
                                user.Labels = result[1].data.Labels;
                                return deferred.resolve(user);
                            },
                            function() {
                                notify({
                                    classes: 'notification-danger',
                                    message: 'Sorry, but we were unable to fully log you in.'
                                });
                                api.logout();
                            }
                        );
                    }
                },
                function(err) {
                    console.log(err);
                    notify({
                        classes: 'notification-danger',
                        message: 'Sorry, but we were unable to log you in.'
                    });
                    api.logout();
                }
            );

            return deferred.promise;
        },

        saveAuthData: function(data) {
            $log.debug('saveAuthData');
            if ( data.SessionToken ) {
                window.sessionStorage[CONSTANTS.OAUTH_KEY + ":SessionToken"] = pmcw.encode_base64(data.SessionToken);
                auth.data = data;
            }
            else {
                window.sessionStorage[CONSTANTS.OAUTH_KEY + ":Uid"] = data.Uid;
                window.sessionStorage[CONSTANTS.OAUTH_KEY + ":AccessToken"] = data.AccessToken;
                window.sessionStorage[CONSTANTS.OAUTH_KEY + ":RefreshToken"] = data.RefreshToken;
                auth.data = _.pick(data, "Uid", "AccessToken", "RefreshToken");
            }
            auth.setAuthHeaders();
        },

        saveEventId: function(id) {
            window.sessionStorage[CONSTANTS.EVENT_ID] = id;
        }
    };

    // RUN-TIME PUBLIC FUNCTIONS
    var api = {
        detectAuthenticationState: function() {
            var session = window.sessionStorage[CONSTANTS.OAUTH_KEY + ":SessionToken"];
            if (session) {
                auth.data = {
                    SessionToken: session
                };

                auth.mailboxPassword = api.getPassword();

                if (auth.mailboxPassword) {
                    pmcw.setMailboxPassword(auth.mailboxPassword);
                }
            }
        },

        savePassword: function(pwd) {
            // Why is this saved in three different places?
            window.sessionStorage[CONSTANTS.MAILBOX_PASSWORD_KEY] = pmcw.encode_utf8_base64(pwd);
            auth.mailboxPassword = pwd;
            pmcw.setMailboxPassword(pwd);
        },

        getPassword: function() {
            var pwd = window.sessionStorage[CONSTANTS.MAILBOX_PASSWORD_KEY];

            return pmcw.decode_utf8_base64(pwd);
        },

        randomString: function(length)
        {
            var charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var i;
            var result = "";
            var isOpera = Object.prototype.toString.call(window.opera) === '[object Opera]';
            if(window.crypto && window.crypto.getRandomValues)
            {
                values = new Uint32Array(length);
                window.crypto.getRandomValues(values);
                for(i=0; i<length; i++)
                {
                    result += charset[values[i] % charset.length];
                }
                return result;
            }
            else if(isOpera)
            {
                //Opera's Math.random is secure, see http://lists.w3.org/Archives/Public/public-webcrypto/2013Jan/0063.html
                for(i=0; i<length; i++)
                {
                    result += charset[Math.floor(Math.random()*charset.length)];
                }
                return result;
            } else {
                return api.semiRandomString(length);
            }
        },

        semiRandomString: function(size) {
            var string = "",
                i = 0,
                chars = "0123456789ABCDEF";

            while (i++ < size) {
                string += chars[Math.floor(Math.random() * 16)];
            }

            return string;
        },

        getPrivateKey: function() {
            var pw = pmcw.decode_utf8_base64(window.sessionStorage.getItem(CONSTANTS.MAILBOX_PASSWORD_KEY));

            return pmcw.decryptPrivateKey(this.user.EncPrivateKey, pw);
        },

        getRefreshCookie: function() {
            $log.debug('getRefreshCookie');
            return $http.post(url.get() + "/auth/refresh",
            {})
            .then(
                function(response) {
                    $log.debug(response);
                    if (response.data.SessionToken!==undefined) {
                        $log.debug('new token',response.data.SessionToken);
                        $log.debug('before',$http.defaults.headers.common['x-pm-session']);
                        $http.defaults.headers.common['x-pm-session'] = response.data.SessionToken;
                        window.sessionStorage.setItem(CONSTANTS.OAUTH_KEY+':SessionToken', pmcw.encode_base64(response.data.SessionToken));
                        $log.debug('after',$http.defaults.headers.common['x-pm-session']);
                        $rootScope.doRefresh = true;
                    }
                },
                function(err) {
                    $log.error(err);
                }
            );
        },

        setAuthCookie: function(type) {
            var deferred = $q.defer();

            $log.debug('setAuthCookie');

            $http.post(url.get() + "/auth/cookies",
            {
                ResponseType: "token",
                ClientID: CONFIG.clientID,
                GrantType: "refresh_token",
                RefreshToken: $rootScope.TemporaryAccessData.RefreshToken,
                RedirectURI: "https://protonmail.ch",
                State: api.randomString(24)
            })
            .then(
                function(response) {
                    $log.debug(response);

                    if (response.data.Code === 1000) {
                        $log.debug('/auth/cookies:',response);
                        $log.debug('/auth/cookies1: resolved');
                        $rootScope.domoArigato = true;
                        // forget the old headers, set the new ones
                        $log.debug('/auth/cookies2: resolved');
                        deferred.resolve(200);
                        $log.debug('headers change', $http.defaults.headers);

                        var data = {
                            SessionToken: response.data.SessionToken
                        };

                        auth.saveAuthData( data );

                        $rootScope.isLocked = false;
                        $rootScope.doRefresh = true;

                    } else {
                        deferred.reject({message: response.data.Error});
                        $log.error('setAuthCookie1', response);
                    }
                },
                function(err) {
                    $log.error('setAuthCookie2', err);
                    deferred.reject({message: err});
                }
            );

            return deferred.promise;
        },

        loginWithCredentials: function(creds) {
            var deferred = $q.defer();

            if (!creds.Username || !creds.Password) {
                deferred.reject({
                    message: "Username and Password are required to login"
                });
            } else {
                delete $http.defaults.headers.common.Accept;
                $rootScope.creds = creds;
                $http.post(url.get() + "/auth",
                    _.extend(_.pick(creds, "Username", "Password", "HashedPassword"), {
                        ResponseType: "token",
                        ClientID: CONFIG.clientID,
                        ClientSecret: CONFIG.clientSecret,
                        GrantType: "password",
                        RedirectURI: "https://protonmail.ch",
                        State: api.randomString(24),
                        Scope: "full" // 'full' or 'reset'
                    })
                ).then(
                    function(resp) {
                        $rootScope.TemporaryAccessData = resp.data;
                        $rootScope.TemporaryEncryptedAccessToken = resp.data.AccessToken;
                        $rootScope.TemporaryEncryptedPrivateKeyChallenge = resp.data.EncPrivateKey;
                        deferred.resolve(resp);
                        // this is a trick! we dont know if we should go to unlock or step2 because we dont have user's data yet. so we redirect to the login page (current page), and this is determined in the resolve: promise on that state in the route. this is because we dont want to do another fetch info here.
                    },
                    function(error) {
                        console.log(error);
                        deferred.reject({
                            message: error.error_description
                        });
                    }
                );
            }

            return deferred.promise;
        },

        // Whether a user is logged in at all
        isLoggedIn: function() {
            // $log.debug('isLoggedIn');
            // console.log(auth);
            // console.log(auth.data);
            // console.log(api.refreshTokenIsDefined());

            var loggedIn = auth.data && api.sessionTokenIsDefined();

            if (loggedIn && api.user === null) {
                auth.setAuthHeaders();
            }
            // $log.debug('isLoggedIn:',loggedIn);
            return loggedIn;
        },

        sessionTokenIsDefined: function() {
            var isDefined = false;

            if (auth.data && typeof auth.data.SessionToken !== 'undefined' && auth.data.SessionToken !== 'undefined') {
                isDefined = true;
            }

            return isDefined;
        },

        // Whether the mailbox' password is accessible, or if the user needs to re-enter it
        isLocked: function() {
            return !api.isLoggedIn() || _.isUndefined(auth.mailboxPassword);
        },

        // Logged in and MBPW is set
        isSecured: function() {
            return api.isLoggedIn() && !api.isLocked();
        },

        // Return a state name to be in in case some user authentication step is required.
        // This will null if the logged in and unlocked.
        state: function() {
            if (api.isLoggedIn()) {
                return api.isLocked() ? "login.unlock" : null;
            } else {
                return "login";
            }
        },

        // Redirect to a new authentication state, if required
        redirectIfNecessary: function() {
            $log.debug('refreshIfNecessary');
            var newState = api.state();
            if (newState) {
                $state.go(newState);
            }
        },

        // refreshIfNecessary: function(force) {
        //     if ((auth.data && auth.data.shouldRefresh && api.refreshTokenIsDefined()) || !!force) {
        //         $http.post(
        //             url.get() + "/auth/refresh",
        //             _.extend(_.pick(auth.data, "RefreshToken"), {
        //                 ClientID: CONFIG.clientID,
        //                 ClientSecret: CONFIG.clientSecret,
        //                 GrantType: "refresh_token",
        //                 State: api.randomString(24),
        //                 ResponseType: "token",
        //             })
        //         ).then(
        //             function(resp) {
        //                 auth.saveAuthData(_.pick(resp.data, "AccessToken", "RefreshToken", "Uid", "ExpiresIn"));
        //             },
        //             function(resp) {
        //                 if(resp.error) {
        //                     api.logout();
        //                 }
        //                 errorReporter.catcher("Something went wrong with authentication");
        //             }
        //         );
        //     }
        // },

        // Removes all connection data
        logout: function() {
            var sessionToken = window.sessionStorage[CONSTANTS.OAUTH_KEY+":SessionToken"];
            var uid = window.sessionStorage[CONSTANTS.OAUTH_KEY+":Uid"];
            // Completely clear sessionstorage
            window.sessionStorage.clear();

            delete auth.data;
            delete auth.mailboxPassword;

            this.user = null;

            // HACKY ASS BUG
            if(angular.isDefined(sessionToken) || angular.isDefined(uid)) {
                $http.delete(url.get() + "/auth").then( function() {
                    location.reload();
                });
            } else {
                location.reload();
            }

            // THIS SHOULD BE RE-ENABLED WHEN WE FIX THE BUG
            // $rootScope.isLoggedIn = false;
            // $rootScope.isLocked = true;
            // $rootScope.isSecure = false;
            // $rootScope.domoArigato = false;

        },

        // Returns an async promise that will be successful only if the mailbox password
        // proves correct (we test this by decrypting a small blob)
        unlockWithPassword: function(epk, pwd, accessToken, TemporaryAccessData) {

            // console.log(epk, pwd, accessToken, TemporaryAccessData);

            var req = $q.defer();
            var self = this;

            if (pwd) {

                pmcw.checkMailboxPassword(epk, pwd, accessToken)
                .then(
                    function(response) {
                        api.savePassword(pwd);
                        auth.mailboxPassword = pwd;
                        api.receivedCredentials({
                            "AccessToken": response,
                            "RefreshToken": TemporaryAccessData.RefreshToken,
                            "Uid": TemporaryAccessData.Uid,
                            "ExpiresIn": TemporaryAccessData.ExpiresIn,
                            "EventID": TemporaryAccessData.EventID
                        });
                        req.resolve(200);
                    },
                    function(rejection) {
                        // console.log(rejection);
                        req.reject({
                            message: "Wrong decryption password."
                        });
                    }
                );
            }
            else {
                req.reject({
                    message: "Password is required"
                });
            }

            return req.promise;
        },

        receivedCredentials: function(data) {
            auth.saveAuthData(data);
            auth.saveEventId(data.EventID);
        },

        fetchUserInfo: function(uid) {
            var promise = auth.fetchUserInfo(uid);
            return promise.then(
                function(user) {

                    // console.log(user);

                    if (user.DisplayName.length === 0) {
                        user.DisplayName = user.Name;
                    }

                    $rootScope.isLoggedIn = true;
                    $rootScope.user = user;
                    this.user = user;
                    this.user.Theme = atob(user.Theme);

                    return user;
                }.bind(this),
                errorReporter.catcher("Please try again later")
            );
        },

        params: function(params) {
            return params;
        }
    };

    api.user = null;

    return api;
})

.run(function($rootScope, authentication, eventManager, CONFIG) {
    authentication.detectAuthenticationState();
    //authentication.refreshIfNecessary();
    $rootScope.isLoggedIn = authentication.isLoggedIn();
    $rootScope.isLocked = authentication.isLocked();
    $rootScope.logout = function() {
        authentication.logout();
        eventManager.stop();
        $scope.error = null;
    };
});


text:
function bones = createBoneObjects(skel, mot, colorArmature, edgeColorArmature)
% creates the bone objects of to a skeleton
numBones = skel.njoints;
bones = struct('id',[],'parentID',[],'name','','type','',...
    'vertices',[],'vertstream',[],'faces',[],'facecolor',[],'edgecolor',[],...
    'labelHandle',[],'labelStream',[],...
    'objectHandle',[],'headPos',[],'tailPos',[]);
for i = 1:numBones
    bone = skel.nodes(i,1);
    % get the joint trajectories for the positions of the labels
    labelTrajectory = mot.jointTrajectories{i,1};
    % head and tail pos in world coordinates
    headPos = getHeadPos(bone, skel);
    tailPos = (headPos + (bone.direction * bone.length));
    % define the thickness of a bone depending on average length of
    % his childbones or his length if there are no childbones
    if(isempty(bone.children))
        if(bone.length == 0)
            thickness = .1;
        else
            thickness = bone.length/10;
        end
    else
        thickness = .0;
        for b = bone.children'
            thickness = thickness + skel.nodes(b,1).length;
        end
        thickness = thickness / (size((bone.children),1)*10);
    end
    % create bone object and add to bones
    bones(i) = PrimBone(bone.ID, bone.parentID, bone.boneName,...
        headPos', tailPos', thickness, labelTrajectory,...
        colorArmature, edgeColorArmature);
end
% recursive function which returns the head position of a bone in world
% coordinates
    function headPos = getHeadPos(bone, skel)
        % root bone should have no parent
        if (bone.parentID == 0)
            headPos = bone.offset;
        else
            pBone = skel.nodes(bone.parentID,1);
            headPos = pBone.offset + getHeadPos(pBone, skel);
        end
    end
end


text:
package org.diorite.utils.math.noise;

import java.util.Random;

import org.diorite.world.World;

/**
 * Creates perlin noise through unbiased octaves
 * From Bukkit project https://github.com/Bukkit/Bukkit
 */
public class PerlinOctaveGenerator extends OctaveGenerator
{

    /**
     * Creates a perlin octave generator for the given world
     *
     * @param world   World to construct this generator for
     * @param octaves Amount of octaves to create
     */
    public PerlinOctaveGenerator(final World world, final int octaves)
    {
        this(new Random(world.getSeed()), octaves);
    }

    /**
     * Creates a perlin octave generator for the given world
     *
     * @param seed    Seed to construct this generator for
     * @param octaves Amount of octaves to create
     */
    public PerlinOctaveGenerator(final long seed, final int octaves)
    {
        this(new Random(seed), octaves);
    }

    /**
     * Creates a perlin octave generator for the given {@link Random}
     *
     * @param rand    Random object to construct this generator for
     * @param octaves Amount of octaves to create
     */
    public PerlinOctaveGenerator(final Random rand, final int octaves)
    {
        super(createOctaves(rand, octaves));
    }

    private static NoiseGenerator[] createOctaves(final Random rand, final int octaves)
    {
        final NoiseGenerator[] result = new NoiseGenerator[octaves];

        for (int i = 0; i < octaves; i++)
        {
            result[i] = new PerlinNoiseGenerator(rand);
        }

        return result;
    }
}


text:
<?php

namespace spec\NAD\SearchBundle\Controller;

use PhpSpec\ObjectBehavior;

/**
 * @author Mohammadreza Razzaghi <razzaghi229@gmail.com>
 */
class ApiControllerSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->shouldHaveType('\NAD\SearchBundle\Controller\ApiController');
    }

}


text:
---
layout:     post
title:      "JAVA Validation"
subtitle:   " \"Java Validation入门\""
date:       2018-02-06 05:22:00
author:     "WQ"
header-img: "img/blogImg/2018-02-06-2.jpg"
catalog: true
tags:
    - Java
---

# Java Validation

刚接触`JSR bean validation`规范,这里做一个简单的入门。

```
As of now Spring Boot by default comes with  Bean Validation 1.0 (JSR-303) and Bean Validation 1.1 (JSR-349)

Java Bean Validation (JSR 303) is a framework that has been approved by the JCP as of Nov 2009 and is accepted as part of the Java EE 6 specification.
Bean Validation 1.1 (JSR 349) was finished in 2013.It is part of Java EE 7.
Hibernate Validator 6.X on the other hand is the reference implementation Bean Validation 2.0 (JSR 380).

Support for the JSR 310 date/time types for @Pastand@Future

New built-in constraints:@Positive, @PositiveOrZero, @Negative, @NegativeOrZero, @PastOrPresent and @FutureOrPresent

Bean Validation 2.0 will also be part of the Java EE 8 platform.

```

该规范用于对bean对象进行参数校验,使用注解的方式进行规则设计,该规范可以参考`javax.validation.validation-api`,该jar中基本没有什么实现,`Hibernate Validator`是该规范的实现,使用的SPI进行动态拓展,具有很高的灵活性,
同时拓展了一些规范的注解。
在springMVC中也有很多运用。

## 例子

准备工作:

```java
@Data
@AllArgsConstructor
public class User {
    @NotNull(message = "用户的姓名不能为空")
    private String name;

    @NotNull(message = "年龄不能为空")
    @Min(value = 2, message = "年龄必须在2到14岁之间",groups = {GroupTest1.class})
    @Max(value = 14, message = "年龄必须在2到14岁之间",groups = {GroupTest1.class})
    private Integer age;

    @Valid
    @LocationValidation(message = "location 不ok", maxX = 12, maxY = 22,groups = {GroupTest2.class})
    private Location location;
}

@Data
@AllArgsConstructor
class Location {
    private int x;
    private int y;
}

/**
 * 校验的注解,Target的值都是可以的,不仅限于属性
 */
@Target({ElementType.FIELD})
@Constraint(validatedBy = {Temp.class})
@Documented
@Retention(RetentionPolicy.RUNTIME)
@interface LocationValidation {

    // 这3个属性是必须的,规范要求
    // 约束注解验证时的输出消息
    String message() default "";

    // 约束注解在验证时所属的组别
    Class<?>[] groups() default {};

    // 约束注解的有效负载
    Class<? extends Payload>[] payload() default {};

    int maxX() ;
    int maxY() ;

}

/**
 * 标记性接口,单纯的在分组时使用
 */
interface GroupTest1 {
}

interface GroupTest2 {
}

/**
 * 自己定义一些方法添加额外的拓展空间,这样在注解中传入参数,在验证时使用,代码中没有演示
 */
class MyRule implements Payload {

    public boolean isOk(){
        return true;
    }

}

```

```java
/**
 * 实际进行校验的类,必须是public方法
 */
public class Temp implements ConstraintValidator<LocationValidation, Location> {

    private LocationValidation locationValidation;
    @Override
    public void initialize(LocationValidation constraintAnnotation) {
        this.locationValidation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Location value, ConstraintValidatorContext context) {

        if (value == null) {
            System.err.println("Default value :" + context.getDefaultConstraintMessageTemplate());

            //禁用默认的提示信息
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(locationValidation.message()).addConstraintViolation();
            return false;
        } else {
            //禁用默认的提示信息,不清楚原有的是什么样的,可以去掉看看结果
            context.disableDefaultConstraintViolation();
            if (value.getX() > locationValidation.maxX()) {
                context.buildConstraintViolationWithTemplate("x value is bigger than max"+locationValidation.message())
                        .addConstraintViolation();
                return false;
            }

            if (value.getY() > locationValidation.maxY()) {
                context.buildConstraintViolationWithTemplate("y value is bigger than max"+locationValidation.message
                        ()).addConstraintViolation();
                return false;
            }

        }
        return true;
    }
}

```

测试:

```java
public class Main {

    public static void main(String[] args) {
        ValidatorFactory validator = Validation.buildDefaultValidatorFactory();
        Validator vs = validator.getValidator();

        User user = new User(null, 44, new Location(33, 44));

        //groups分为三个组,其中一个为default
        //只会校验name
        go(Default.class, vs, user);

        //校验 age
        go(GroupTest1.class, vs, user);

        //校验Location
        go(GroupTest2.class, vs, user);
    }

    private static void go(Class c,Validator vs,User user) {
        Set<ConstraintViolation<User>> validate = vs.validate(user, c);
        if (validate.size() != 0) {
            validate.forEach(System.out::println);
        }
        System.out.println("-------------------------------------------");
    }
}

```

还有一些高级的使用方法,参考 [Bean Validation 技术规范特性概述](http://beanvalidation.org)。另外,在spring-boot中已经集成了hibernate-validation。


text:
require 'dm-core'

require 'cgi'

module DataMapper
  class Property
    module Legacy
      class HTMLText < Text

        #
        # Unescaped HTML escaped data.
        #
        # @param [String, nil] value
        #   The HTML escaped data.
        #
        # @return [String, nil]
        #   The HTML unescaped data.
        #
        def load(value)
          CGI.unescape_html(value) unless value.nil?
        end

        #
        # HTML escapes data.
        #
        # @param [String, nil] value
        #   The raw data.
        #
        # @return [String, nil]
        #   The HTML escaped data.
        #
        def dump(value)
          CGI.escape_html(value) unless value.nil?
        end

      end
    end
  end
end


text:
<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">

	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="/quickforms/css/quickforms/quickforms.css"/>

	</script>

In Consultation Form

		<form id='visitsForm' action="inConsultation.html">

		Patient
		<select name ="patient" id="patient"><option value="0">Values</option></select>

		Room
		<select name ="room" id="room"><option value="0">Values</option></select>

	    Assessment

		Procedure
		<select name="consultSteps" id="consultSteps" onChange='onChangeValue();'><option value="0">Values</option></select>

		Select a ward
		<select name="ward" id="ward"><option value="1">Values</option></select>

		Select the tests to be performed

		Date
	    <input type = "text" class="dateTime" name ="dischargeDate" id = "dischargeDate"/>

		Assign to
		<select name="providerPhy" id="providerPhy"><option>Values</option></select>

		Reset
		Submit
		Back

		</form>


text:
package com.iskyinfor.duoduo.ui.talkgarden;

import com.iskyinfor.duoduo.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class TalkGardenListAdapter extends BaseAdapter {
	private Context mContext = null;
	LayoutInflater factory = null;

	private String [] userData =
	{
	    "刘维:","好美丽:","黄河:","钟云:","蓝心:","郑梦:","小浩:","龙浩然:","王小骞:","阿芙:"
	};

	private String [] contentData =
	{
		"发个自定义表情看看","我这没有呀,怎么发?","发个自定义表情看看~~~",
		"我这没有呀,怎么发?","我这没有呀,怎么发?",
		"你自己看看自己的东西","是什么让我找到你","你的世界很精彩",
		"找到温暖的回忆","没有我的日子 怎么渡过"
	};

	private String [] timeData =
	{
		"13:15","13:20","13:25","13:29","13:56","14:20","14:36","15:20","16:20","17:20"
	};

	public TalkGardenListAdapter(Context c)
	{
		mContext = c;
		factory = LayoutInflater.from(mContext);
	}

	@Override
	public int getCount()
	{
		return userData.length;
	}

	@Override
	public Object getItem(int position)
	{
		return position;
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}

	@Override
	public View getView(int position, View view, ViewGroup parent)
	{
		ListHolder holder = null ;
		if(view == null)
		{
			view = factory.inflate(R.layout.talk_garden_list_items, null);
			holder = new ListHolder();
			holder.userName = (TextView) view.findViewById(R.id.talk_username_text);
			holder.sendContent = (TextView) view.findViewById(R.id.talk_content_text);
			holder.sendTime = (TextView) view.findViewById(R.id.talk_time_text);
			view.setTag(holder);
		}
		else
		{
			holder = (ListHolder) view.getTag();
		}

		holder.userName.setText(userData[position]);
		holder.sendContent.setText(contentData[position]);
		holder.sendTime.setText(timeData[position]);

		return view;
	}

	static class ListHolder
	{
		TextView userName,sendContent,sendTime;
	}

}


text:
package org.laladev.moneyjinn.service.dao;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.laladev.moneyjinn.service.dao.data.PreDefMoneyflowData;
import org.laladev.moneyjinn.service.dao.mapper.IPreDefMoneyflowDaoMapper;

@Named
public class PreDefMoneyflowDao {

	@Inject
	IPreDefMoneyflowDaoMapper mapper;

	public List<PreDefMoneyflowData> getAllPreDefMoneyflows(final Long userId) {
		return this.mapper.getAllPreDefMoneyflows(userId);
	}

	public PreDefMoneyflowData getPreDefMoneyflowById(final Long userId, final Long id) {
		return this.mapper.getPreDefMoneyflowById(userId, id);
	}

	public Integer countAllPreDefMoneyflows(final Long userId) {
		return this.mapper.countAllPreDefMoneyflows(userId);
	}

	public Long createPreDefMoneyflow(final PreDefMoneyflowData preDefMoneyflowData) {
		this.mapper.createPreDefMoneyflow(preDefMoneyflowData);
		return preDefMoneyflowData.getId();
	}

	public void updatePreDefMoneyflow(final PreDefMoneyflowData preDefMoneyflowData) {
		this.mapper.updatePreDefMoneyflow(preDefMoneyflowData);
	}

	public void deletePreDefMoneyflow(final Long userId, final Long id) {
		this.mapper.deletePreDefMoneyflow(userId, id);
	}

	public List<Long> getAllContractpartnerIds(final Long userId) {
		return this.mapper.getAllContractpartnerIds(userId);
	}

	public void setLastUsed(final Long userId, final Long id) {
		this.mapper.setLastUsed(userId, id);
	}

}


text: Coffee Beans Recommender System


text:
<?php

namespace iksnimak\nestable;

/**
 * NestableInterface is the interface that should be implemented by a class which
 * contain nested elements.
 *
 * This interface can typically be implemented by a menu items model class.
 *
 * Example: //TODO
 * ~~~
 * class MenuItem implements Nestable
 * {
 *    ...
 * }
 * ~~~
 *
 * @author Karol Kaminski
 * @since 2.0
 */
interface NestableInterface
{
	/**
	 * Returns an ActiveRecord object of all child elements of current model.
	 * @return \yii\db\ActiveRecord
	 */
	public function getChildren();
}


text:
package org.djodjo.tarator.testapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;

/**
 * Simple activity used for validating intent sending and UI behavior.
 */
public class SendActivity extends Activity {

  private static final int PICK_CONTACT_REQUEST = 1;  // The request code
  static final String EXTRA_DATA = "com.google.android.apps.common.testing.ui.testapp.DATA";
  static final int PICK_CONTACT = 100;
  private PopupWindow popupWindow;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.send_activity);

    EditText editText = (EditText) findViewById(R.id.enter_data_edit_text);
    editText.setOnKeyListener(new OnKeyListener() {

      @Override
      public boolean onKey(View view, int keyCode, KeyEvent event) {
        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
            (keyCode == KeyEvent.KEYCODE_ENTER)) {
          EditText editText = (EditText) view;
          TextView responseText = (TextView) findViewById(R.id.enter_data_response_text);
          responseText.setText(editText.getText());
          return true;
        } else {
          return false;
        }
      }
    });

    final EditText searchBox = (EditText) findViewById(R.id.search_box);
    searchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
          TextView result = (TextView) findViewById(R.id.search_result);
          result.setText(getString(R.string.searching_for_label) + " " + v.getText());
          result.setVisibility(View.VISIBLE);
          InputMethodManager imm =
              (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.hideSoftInputFromWindow(searchBox.getWindowToken(), 0);
          return true;
        }
        return false;
      }
    });
    AutoCompleteTextView autoComplete = (AutoCompleteTextView) findViewById(
        R.id.auto_complete_text_view);
    String [] completions = new String[] {
      "Pacific Ocean", "Atlantic Ocean", "Indian Ocean", "Southern Ocean", "Artic Ocean",
      "Mediterranean Sea", "Caribbean Sea", "South China Sea", "Bering Sea",
      "Gulf of Mexico", "Okhotsk Sea", "East China Sea", "Hudson Bay", "Japan Sea",
      "Andaman Sea", "North Sea", "Red Sea", "Baltic Sea" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_dropdown_item_1line,
        completions);
    autoComplete.setAdapter(adapter);
  }

  /** Called when user clicks the Send button */
  public void sendData(@SuppressWarnings("unused") View view) {
    Intent intent = new Intent(this, DisplayActivity.class);
    EditText editText = (EditText) findViewById(R.id.send_data_edit_text);
    intent.putExtra(EXTRA_DATA, editText.getText().toString());
    startActivity(intent);
  }

  public void sendDataToCall(@SuppressWarnings("unused") View view) {
    Intent intentToCall = new Intent(Intent.ACTION_CALL);
    EditText editText = (EditText) findViewById(R.id.send_data_to_call_edit_text);
    String number = editText.getText().toString();
    intentToCall.setData(Uri.parse("tel:" + number));
    startActivity(intentToCall);
  }

  public void sendDataToBrowser(@SuppressWarnings("unused") View view) {
    EditText editText = (EditText) findViewById(R.id.send_data_to_browser_edit_text);
    String url = editText.getText().toString();
    Intent intentToBrowser = new Intent(Intent.ACTION_VIEW);
    intentToBrowser.setData(Uri.parse(url));
    intentToBrowser.addCategory(Intent.CATEGORY_BROWSABLE);
    intentToBrowser.putExtra("key1", "value1");
    intentToBrowser.putExtra("key2", "value2");
    startActivity(intentToBrowser);
  }

  public void sendMessage(@SuppressWarnings("unused") View view) {
    Intent sendIntent = new Intent();
    EditText editText = (EditText) findViewById(R.id.send_data_to_message_edit_text);
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, editText.getText().toString());
    sendIntent.setType("text/plain");
    startActivity(sendIntent);
  }

  public void clickToMarket(@SuppressWarnings("unused") View view) {
    Intent marketIntent = new Intent(Intent.ACTION_VIEW);
    EditText editText = (EditText) findViewById(R.id.send_to_market_data);
    marketIntent.setData(Uri.parse(
        "market://details?id=" + editText.getText().toString()));
    startActivity(marketIntent);
  }

  public void clickToGesture(@SuppressWarnings("unused") View view) {
    startActivity(new Intent(this, GestureActivity.class));
  }

  public void clickToScroll(@SuppressWarnings("unused") View view) {
    startActivity(new Intent(this, ScrollActivity.class));
  }

  public void clickToList(@SuppressWarnings("unused") View view) {
    startActivity(new Intent(this, LongListActivity.class));
  }

  public boolean showDialog(@SuppressWarnings("unused") View view) {
    new AlertDialog.Builder(this)
        .setTitle(R.string.dialog_title)
        .setMessage(R.string.dialog_message)
        .setNeutralButton("Fine", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int choice) {
            dialog.dismiss();
          }
        })
        .show();
    return true;
  }

  public boolean showPopupView(View view) {
    View content = getLayoutInflater().inflate(R.layout.popup_window, null, false);
    popupWindow = new PopupWindow(content, LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT, true);
    content.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        popupWindow.dismiss();
      }
    });

    popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

    return true;
  }

  public boolean showPopupMenu(View view) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
      return false;
    }

    PopupMenu popup = new PopupMenu(this, view);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.popup_menu, popup.getMenu());
    popup.show();
    return true;
  }

  public void pickContact(@SuppressWarnings("unused") View view) {
    Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
    pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
    startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICK_CONTACT_REQUEST) {
      if (resultCode == RESULT_OK) {
        // TODO(user): hook this up for real as shown in this example:
        // http://developer.android.com/training/basics/intents/result.html
        TextView textView = (TextView) findViewById(R.id.phone_number);
        textView.setText(data.getExtras().getString("phone"));
      }
    }
  }
}


text:
import { SignalType } from '../../context.type'
import { docAction } from '../../Data/actions/docAction'
import { save } from '../../Data/signals/save'
import { status } from '../../Status/actions/status'
import * as set from 'cerebral-addons/set'

export const name: SignalType =
[ set ( 'output:/type', 'project' )
, set ( 'output:/key', 'name' )
// close editing on data save
, set ( 'state:/$factory.project.close', true )
, docAction
, ... save
]


text:
package brooklyn.location.jclouds;

import java.util.Map;

import org.jclouds.compute.domain.NodeMetadata;

import brooklyn.location.basic.SupportsPortForwarding.RequiresPortForwarding;

public abstract class AbstractJcloudsSubnetSshMachineLocation extends JcloudsSshMachineLocation implements RequiresPortForwarding {

    public AbstractJcloudsSubnetSshMachineLocation() {
    }

    /** @deprecated since 0.6.0 use no-arg constructor, as per parent */
    @Deprecated
    public AbstractJcloudsSubnetSshMachineLocation(Map flags, JcloudsLocation parent, NodeMetadata node) {
        super(flags, parent, node);
    }

}


text:
package org.marketcetera.saclient.rpc;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.marketcetera.module.ModuleInfo;
import org.marketcetera.module.ModuleURN;
import org.marketcetera.saclient.CreateStrategyParameters;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/* $License$ */

/**
 * Provides an implementation of SAClientServiceAdapter for testing.
 *
 * @author Colin DuPlantis
 * @version $Id$
 * @since $Release$
 */
public class MockSAClientServiceAdapter
        implements SAServiceAdapter
{
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#getProviders()
     */
    @Override
    public List<ModuleURN> getProviders()
    {
        providersCount.incrementAndGet();
        return providersToReturn;
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#getInstances(org.marketcetera.module.ModuleURN)
     */
    @Override
    public List<ModuleURN> getInstances(ModuleURN inProvider)
    {
        instancesRequests.add(inProvider);
        return instancesToReturn;
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#getModuleInfo(org.marketcetera.module.ModuleURN)
     */
    @Override
    public ModuleInfo getModuleInfo(ModuleURN inInstance)
    {
        moduleInfoRequests.add(inInstance);
        return moduleInfoToReturn;
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#start(org.marketcetera.module.ModuleURN)
     */
    @Override
    public void start(ModuleURN inInstance)
    {
        startRequests.add(inInstance);
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#stop(org.marketcetera.module.ModuleURN)
     */
    @Override
    public void stop(ModuleURN inInstance)
    {
        stopRequests.add(inInstance);
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#delete(org.marketcetera.module.ModuleURN)
     */
    @Override
    public void delete(ModuleURN inInstance)
    {
        deleteRequests.add(inInstance);
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#getProperties(org.marketcetera.module.ModuleURN)
     */
    @Override
    public Map<String,Object> getProperties(ModuleURN inInstance)
    {
        propertiesRequests.add(inInstance);
        return propertiesToReturn;
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#setProperties(org.marketcetera.module.ModuleURN, java.util.Map)
     */
    @Override
    public Map<String,Object> setProperties(ModuleURN inInstance,
                                            Map<String,Object> inProperties)
    {
        propertiesRequests.add(inInstance);
        return inProperties;
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#createStrategy(org.marketcetera.saclient.CreateStrategyParameters)
     */
    @Override
    public ModuleURN createStrategy(CreateStrategyParameters inParameters)
    {
        createStrategyRequests.add(inParameters);
        return createModuleURNToReturn;
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#getStrategyCreateParms(org.marketcetera.module.ModuleURN)
     */
    @Override
    public CreateStrategyParameters getStrategyCreateParms(ModuleURN inInstance)
    {
        strategyCreateParmsRequests.add(inInstance);
        return parametersToReturn;
    }
    /* (non-Javadoc)
     * @see org.marketcetera.saclient.rpc.SAClientServiceAdapter#sendData(java.lang.Object)
     */
    @Override
    public void sendData(Object inData)
    {
        sentData = inData;
    }
    /**
     * Get the providersToReturn value.
     *
     * @return a List<ModuleURN> value
     */
    public List<ModuleURN> getProvidersToReturn()
    {
        return providersToReturn;
    }
    /**
     * Get the providersCount value.
     *
     * @return an AtomicInteger value
     */
    public AtomicInteger getProvidersCount()
    {
        return providersCount;
    }
    /**
     * Get the instancesToReturn value.
     *
     * @return a List<ModuleURN> value
     */
    public List<ModuleURN> getInstancesToReturn()
    {
        return instancesToReturn;
    }
    /**
     * Get the instancesRequests value.
     *
     * @return a List<ModuleURN> value
     */
    public List<ModuleURN> getInstancesRequests()
    {
        return instancesRequests;
    }
    /**
     * Get the moduleInfoToReturn value.
     *
     * @return a ModuleInfo value
     */
    public ModuleInfo getModuleInfoToReturn()
    {
        return moduleInfoToReturn;
    }
    /**
     * Sets the moduleInfoToReturn value.
     *
     * @param inModuleInfoToReturn a ModuleInfo value
     */
    public void setModuleInfoToReturn(ModuleInfo inModuleInfoToReturn)
    {
        moduleInfoToReturn = inModuleInfoToReturn;
    }
    /**
     * Get the moduleInfoRequests value.
     *
     * @return a List<ModuleURN> value
     */
    public List<ModuleURN> getModuleInfoRequests()
    {
        return moduleInfoRequests;
    }
    /**
     * Get the startRequests value.
     *
     * @return a List<ModuleURN> value
     */
    public List<ModuleURN> getStartRequests()
    {
        return startRequests;
    }
    /**
     * Get the stopRequests value.
     *
     * @return a List<ModuleURN> value
     */
    public List<ModuleURN> getStopRequests()
    {
        return stopRequests;
    }
    /**
     * Get the deleteRequests value.
     *
     * @return a List<ModuleURN> value
     */
    public List<ModuleURN> getDeleteRequests()
    {
        return deleteRequests;
    }
    /**
     * Get the propertiesRequests value.
     *
     * @return a List<ModuleURN> value
     */
    public List<ModuleURN> getPropertiesRequests()
    {
        return propertiesRequests;
    }
    /**
     * Sets the propertiesRequests value.
     *
     * @param inPropertiesRequests a List<ModuleURN> value
     */
    public void setPropertiesRequests(List<ModuleURN> inPropertiesRequests)
    {
        propertiesRequests = inPropertiesRequests;
    }
    /**
     * Get the propertiesToReturn value.
     *
     * @return a Map<String,Object> value
     */
    public Map<String,Object> getPropertiesToReturn()
    {
        return propertiesToReturn;
    }
    /**
     * Get the createModuleURNToReturn value.
     *
     * @return a ModuleURN value
     */
    public ModuleURN getCreateModuleURNToReturn()
    {
        return createModuleURNToReturn;
    }
    /**
     * Sets the createModuleURNToReturn value.
     *
     * @param inCreateModuleURNToReturn a ModuleURN value
     */
    public void setCreateModuleURNToReturn(ModuleURN inCreateModuleURNToReturn)
    {
        createModuleURNToReturn = inCreateModuleURNToReturn;
    }
    /**
     * Get the createStrategyRequests value.
     *
     * @return a List<CreateStrategyParameters> value
     */
    public List<CreateStrategyParameters> getCreateStrategyRequests()
    {
        return createStrategyRequests;
    }
    /**
     * Get the parametersToReturn value.
     *
     * @return a CreateStrategyParameters value
     */
    public CreateStrategyParameters getParametersToReturn()
    {
        return parametersToReturn;
    }
    /**
     * Sets the parametersToReturn value.
     *
     * @param inParametersToReturn a CreateStrategyParameters value
     */
    public void setParametersToReturn(CreateStrategyParameters inParametersToReturn)
    {
        parametersToReturn = inParametersToReturn;
    }
    /**
     * Get the strategyCreateParmsRequests value.
     *
     * @return a List<ModuleURN> value
     */
    public List<ModuleURN> getStrategyCreateParmsRequests()
    {
        return strategyCreateParmsRequests;
    }
    /**
     * Get the sentData value.
     *
     * @return an Object value
     */
    public Object getSentData()
    {
        return sentData;
    }
    /**
     * Sets the sentData value.
     *
     * @param inSentData an Object value
     */
    public void setSentData(Object inSentData)
    {
        sentData = inSentData;
    }
    /**
     * Resets test values.
     */
    public void reset()
    {
        providersToReturn.clear();
        providersCount.set(0);
        instancesToReturn.clear();
        instancesRequests.clear();
        moduleInfoRequests.clear();
        moduleInfoToReturn = null;
        startRequests.clear();
        stopRequests.clear();
        deleteRequests.clear();
        propertiesRequests.clear();
        propertiesToReturn.clear();
        createStrategyRequests.clear();
        createModuleURNToReturn = null;
        parametersToReturn = null;
        strategyCreateParmsRequests.clear();
        sentData = null;
    }
    /**
     * provides to return value
     */
    private final List<ModuleURN> providersToReturn = Lists.newArrayList();
    /**
     * count of providers invocation
     */
    private final AtomicInteger providersCount = new AtomicInteger(0);
    /**
     * instances to return value
     */
    private final List<ModuleURN> instancesToReturn = Lists.newArrayList();
    /**
     * instances requests
     */
    private final List<ModuleURN> instancesRequests = Lists.newArrayList();
    /**
     * module info requests
     */
    private final List<ModuleURN> moduleInfoRequests = Lists.newArrayList();
    /**
     * module info to return
     */
    private ModuleInfo moduleInfoToReturn;
    /**
     * start requests value
     */
    private final List<ModuleURN> startRequests = Lists.newArrayList();
    /**
     * stop requests value
     */
    private final List<ModuleURN> stopRequests = Lists.newArrayList();
    /**
     * delete requests value
     */
    private final List<ModuleURN> deleteRequests = Lists.newArrayList();
    /**
     * properties requests value
     */
    private List<ModuleURN> propertiesRequests = Lists.newArrayList();
    /**
     * properties to return value
     */
    private final Map<String,Object> propertiesToReturn = Maps.newHashMap();
    /**
     * create strategy requests value
     */
    private final List<CreateStrategyParameters> createStrategyRequests = Lists.newArrayList();
    /**
     * create module urn to return
     */
    private ModuleURN createModuleURNToReturn;
    /**
     * create strategy parameters to return
     */
    private CreateStrategyParameters parametersToReturn;
    /**
     * create strategy params requests
     */
    private final List<ModuleURN> strategyCreateParmsRequests = Lists.newArrayList();
    /**
     * object sent to {@link #sendData(Object)}
     */
    private Object sentData;
}


text:
package com.microsoft.azure.documentdb.spark;

import java.io.Serializable;

import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaSparkContext;
import org.junit.After;
import org.junit.Before;

import com.microsoft.azure.documentdb.DocumentClient;

public abstract class JavaRequiresDocumentDB implements Serializable {

    private transient JavaSparkContext jsc;

    private static final DocumentDBDefaults documentDBDefaults = new DocumentDBDefaults();

    public DocumentClient getDocumentClient() {
        return documentDBDefaults.getDocumentClient();
    }

    public SparkConf getSparkConf() {
        return getSparkConf(getCollectionName());
    }

    public SparkConf getSparkConf(final String collectionName) {
        return documentDBDefaults.getSparkConf(collectionName);
    }

    public JavaSparkContext getJavaSparkContext() {
        if (jsc != null) {
            jsc.stop();
        }
        jsc = new JavaSparkContext(new SparkContext(getSparkConf()));
        return jsc;
    }

    public JavaSparkContext getJavaSparkContext(final String collectionName) {
        if (jsc != null) {
            jsc.stop();
        }
        jsc = new JavaSparkContext(new SparkContext(getSparkConf(collectionName)));
        return jsc;
    }

    public String getDatabaseName() {
        return documentDBDefaults.DATABASE_NAME();
    }

    public String getCollectionName() {
        return this.getClass().getName();
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }
}