text:
Before do
  Capybara.current_driver = :rack_test
end

redpajama_set_name: RedPajamaGithub


text:
package org.xmlcml.ami2.plugins.phylotree;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import nu.xom.Attribute;
import nu.xom.Element;
import nu.xom.Elements;

import org.apache.log4j.Logger;
import org.xmlcml.ami2.plugins.phylotree.nexml.NexmlEdge;
import org.xmlcml.ami2.plugins.phylotree.nexml.NexmlNEXML;
import org.xmlcml.ami2.plugins.phylotree.nexml.NexmlNode;
import org.xmlcml.ami2.plugins.phylotree.nexml.NexmlOtu;
import org.xmlcml.ami2.plugins.phylotree.nexml.NexmlOtus;
import org.xmlcml.ami2.plugins.phylotree.nexml.NexmlTree;
import org.xmlcml.ami2.plugins.phylotree.nexml.NexmlTrees;
import org.xmlcml.euclid.Real;
import org.xmlcml.euclid.Real2;
import org.xmlcml.graphics.svg.SVGElement;
import org.xmlcml.graphics.svg.SVGG;
import org.xmlcml.graphics.svg.SVGLine;
import org.xmlcml.graphics.svg.SVGPolyline;
import org.xmlcml.graphics.svg.SVGSVG;
import org.xmlcml.graphics.svg.SVGText;
import org.xmlcml.graphics.svg.SVGUtil;
import org.xmlcml.graphics.svg.linestuff.ComplexLine.LineOrientation;
import org.xmlcml.graphics.svg.linestuff.ComplexLine.SideOrientation;
import org.xmlcml.graphics.svg.linestuff.LineMerger;
import org.xmlcml.graphics.svg.linestuff.LineMerger.MergeMethod;
import org.xmlcml.xml.XMLConstants;
import org.xmlcml.xml.XMLUtil;

public class SVGXTree extends SVGG {

	private static final String LENGTH = "length";

	private final static Logger LOG = Logger.getLogger(SVGXTree.class);

	private static final String ID = "id";
	private static final String LABEL = "label";
	private static final String NODE= "node";
	static final String OTU = "otu";
	private static final String ROOT_TAXA_BLOCK = "RootTaxaBlock";
	private static final String T = "t";
	private static final String TAX1 = "tax1";
	private static final String TREE = "tree.";
	private static final String TREE1 = "tree1";
	private static final String TREES = "Trees";
	private static final String TREES_BLOCK_FROM_XML = "TreesBlockFromXML";
	private static final String TRUE = "true";

	public static final double EPS = 0.01;

	private double eps;
	SVGElement parentSVGElement;
	private PhyloTreeSVGAnalyzer treeAnalyzer;
	List<SVGXTreeNode> rootNodeList;
	private double edgeLengthFontSize = 6.;
	private String edgeLengthFill = "red";

	private Element xmlTree;
	private List<SVGLine> svgLines;
	private SideOrientation sideOrientation;
	private LineOrientation treeOrientation;

	public SVGXTree(SVGElement parentSVGG) {
		this.eps = EPS;
		this.parentSVGElement = parentSVGG;
		if (parentSVGG != null) {
			this.setId(TREE+parentSVGG.getId());
			this.setId(parentSVGG.getId());
		}
		this.treeAnalyzer = new PhyloTreeSVGAnalyzer(this);
	}

	/** create tree from SVG
	 *
	 * @param container selected SVG container (normally a G or SVG)
	 * @param eps error margin
	 * @param method of line join (try MergeMethod.TOUCHING_LINES)
	 * @return
	 */
	public static SVGXTree makeTree(SVGElement container, double eps, MergeMethod method) {
		SVGPolyline.replacePolyLinesBySplitLines(container);
		List<SVGLine> lines = SVGLine.extractSelfAndDescendantLines(container);
		lines = LineMerger.mergeLines(lines, eps, method);
		SVGXTree tree = new SVGXTree(container);
		PhyloTreeSVGAnalyzer treeAnalyzer = tree.getTreeAnalyzer();
		treeAnalyzer.analyzeBranchesAtLineEnds(lines);
		tree.buildTree();
		return tree;
	}

	public void setEpsilon(double eps) {
		this.eps = eps;
	}

	public LineOrientation getTreeOrientation() {
		return getTreeAnalyzer().getTreeOrientation();
	}

	public List<SVGXTreeEdge> getEdgeList() {
		return getTreeAnalyzer().getEdgeList();
	}

	public List<SVGXTreeNode> getNodeList() {
		return getTreeAnalyzer().getNodeList();
	}

	public SVGXTreeNode getRootNode() {
		ensureRootNodeList();
		return (rootNodeList.size() == 1) ? rootNodeList.get(0): null;
	}

	public void buildTree() {
		getTreeAnalyzer().buildTree();
		treeAnalyzer.addLinkLinesLengthsAndWords();
		addLengthsToSVG();
		Element xmlTree = buildXMLTree();
		if (xmlTree != null) {
			LOG.trace("TREE "+xmlTree.toXML());
			XMLUtil.outputQuietly(xmlTree, new File("target/temp.tree.xml"), 1);
			displayTree("target/temp.svg");
		}
	}

	private Element buildXMLTree() {
		if (xmlTree == null) {
			xmlTree = null;
			SVGXTreeNode rootNode = getRootNode();
			// FIXME
			xmlTree = createElementAndAddDescendants(rootNode);
		}
		return xmlTree;
	}

	public String createNewick() {
		buildXMLTree();
		String s = "no tree";
		if (xmlTree != null) {
			StringBuilder sb = new StringBuilder();
			Element element = xmlTree;
			sb.insert(0,  XMLConstants.S_SEMICOLON);
			processElement(sb, element);
			s = sb.toString();
		}
		return s;
	}

	void processElement(StringBuilder sb, Element element) {
		String label = element.getAttributeValue(LABEL);
		if (label == null) {
			label = element.getAttributeValue(ID);
		}
		sb.insert(0, label);
		Elements childElements = element.getChildElements();
		if (childElements.size() > 0) {
			sb.insert(0,XMLConstants.S_RBRAK);
			for (int i = 0; i < childElements.size(); i++) {
				if (i > 0) {
					sb.insert(0,  XMLConstants.S_COMMA);
				}
				processElement(sb, childElements.get(i));
			}
			sb.insert(0,XMLConstants.S_LBRAK);
		}
	}

	private Element createElementAndAddDescendants(SVGXTreeNode treeNode) {
		Element node = null;
		if (treeNode !=null) {
			node = new Element(NODE);
			if (treeNode.getId() != null) {
				node.addAttribute(new Attribute(ID, treeNode.getId()));
				LOG.trace("ID "+treeNode.getId());
			}
			if (treeNode.text != null) {
				node.addAttribute(new Attribute(LABEL, treeNode.text.getValue()));
			}
			if (treeNode.childNodeList != null) {
				for (SVGXTreeNode childTreeNode : treeNode.childNodeList) {
					Element childNode = createElementAndAddDescendants(childTreeNode);
					node.appendChild(childNode);
				}
			}
		}
		return node;
	}

	private void addLengthsToSVG() {
		for (SVGXTreeEdge edge : getEdgeList()) {
			SVGLine line = edge.getLine();
			Real2 mid = line.getBoundingBox().getCentroid();
			double d = edge.getLength();
			SVGText text = new SVGText(mid, ""+(int)d);
			text.setFontSize(edgeLengthFontSize);
			text.setFill(edgeLengthFill);
			this.appendChild(text);
		}
	}

	private void displayTree(String filename) {
		SVGSVG svg = new SVGSVG();
		svg.appendChild(this.copy());
		try {
			SVGUtil.debug(svg, new FileOutputStream(filename), 1);
		} catch (Exception e) {
			throw new RuntimeException("Cannot write: ", e);
		}
	}

	public PhyloTreeSVGAnalyzer getTreeAnalyzer() {
		return treeAnalyzer;
	}

	void createFromChildren(SVGG svgg, String xpath, double eps) {
		List<SVGElement> lineElements = SVGUtil.getQuerySVGElements(svgg, xpath);
		if (lineElements.size() != 0) {
			LOG.trace("making tree with "+lineElements.size()+" lines");
			List<SVGLine> svgLines = SVGLine.extractLines(lineElements);
			treeAnalyzer.analyzeBranchesAtLineEnds(svgLines, eps);
			buildTree();
			svgg.appendChild(this);
		}
	}

	public NexmlNEXML createNEXML() {
		NexmlNEXML nexml = createNexmlNEXMLElement();
		NexmlOtus otus = createNexmlOtusElement(nexml);
		NexmlTrees trees = createNexmlTreesElement(nexml);
		NexmlTree tree = createNexmlTreeElement(trees);
		addNodesAndOtus(otus, tree);
		addEdges(tree);
		return nexml;
	}

	private NexmlTree createNexmlTreeElement(Element trees) {
		NexmlTree tree = new NexmlTree();
		tree.setId(TREE1);
		tree.setLabel(TREE1);
		tree.setType(NexmlNEXML.FLOAT_TREE);
		trees.appendChild(tree);
		return tree;
	}

	private NexmlTrees createNexmlTreesElement(Element nexml) {
		NexmlTrees trees = new NexmlTrees();
		trees.setLabel(TREES_BLOCK_FROM_XML);
		trees.setId(TREES);
		trees.setOtus(TAX1);
		nexml.appendChild(trees);
		return trees;
	}

	private NexmlOtus createNexmlOtusElement(Element nexml) {
		NexmlOtus otus = new NexmlOtus();
		otus.setId(TAX1);
		otus.setLabel(ROOT_TAXA_BLOCK);
		nexml.appendChild(otus);
		return otus;
	}

	private NexmlNEXML createNexmlNEXMLElement() {
		NexmlNEXML nexml = new NexmlNEXML();
		nexml.setId(this.getId());
		return nexml;
	}

	private void addNodesAndOtus(Element otus, Element tree) {
		int otuCount = 0;
		for (SVGXTreeNode svgxNode : getNodeList()) {
			NexmlNode node = new NexmlNode();
			tree.appendChild(node);
			node.setId(svgxNode.getId());
			node.setLabel(svgxNode.getId());
			if (svgxNode.getParentTreeNode() == null) {
				node.setRoot(TRUE);
			}
			List<SVGElement> elements = SVGUtil.getQuerySVGElements(svgxNode, "./svg:text[@title='"+OTU+"']");
			if (elements.size() == 1) {
				otuCount = addOtu(otus, otuCount, node, elements);
			}
		}
	}

	private int addOtu(Element otus, int otuCount, NexmlNode node,
			List<SVGElement> elements) {
		String otuId = T+(++otuCount);
		node.setOtuRef(otuId);
		NexmlOtu otu = new NexmlOtu();
		otu.setId(otuId);
		node.setLabel(elements.get(0).getValue());
		otus.appendChild(otu);
		return otuCount;
	}

	private void addEdges(Element tree) {
		for (SVGXTreeEdge svgxEdge : getEdgeList()) {
			NexmlEdge edge = new NexmlEdge();
			tree.appendChild(edge);
			edge.setId(svgxEdge.getId());
			edge.setLabel(svgxEdge.getId());
			String parentId = svgxEdge.getAttributeValue(SVGXTreeEdge.PARENT);
			if (parentId != null) {
				edge.setSource(parentId);
			}
			String childId = svgxEdge.getAttributeValue(SVGXTreeEdge.CHILD);
			if (childId != null) {
				edge.setTarget(childId);
			}
			Double length = Real.normalize(svgxEdge.getLength(), 3);
			if (length != null) {
				edge.addAttribute(new Attribute(SVGX_PREFIX+":"+LENGTH, SVGX_NS, String.valueOf(length)));
			}
		}
	}

	public void replacePolyLinesBySplitLines() {
		SVGPolyline.replacePolyLinesBySplitLines(parentSVGElement);
	}

	public void analyzeBranchesAtLineEnds() {
		this.svgLines = SVGLine.extractSelfAndDescendantLines(parentSVGElement);
		treeAnalyzer.analyzeBranchesAtLineEnds(svgLines);
	}

	void ensureRootNodeList() {
		if (rootNodeList == null) {
			rootNodeList = new ArrayList<SVGXTreeNode>();
		}
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Module tablero</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc">

Overview

Module tablero

Description

Function Index

Function Details

   Este módulo implementa el tablero individual para un jugador de erlwars.

Copyright © (C) 2014

Authors: Alejandro Pernas Pan (<tt>alejandro.pernas@udc.es</tt>), Laura Otero Méndez (<tt>inslom01@udc.es</tt>), Javier Toja Alamancos (<tt>insjta00@udc.es</tt>), Sergio Cores Acha (<tt>sergio.cores@udc.es</tt>).

Description

   Este módulo implementa el tablero individual para un jugador de erlwars. En este
   tablero se ubican las naves del jugador. Cada posición del tablero admite 4 estados.

Estados de las celdas del tablero

?VACIO: La celda del tablero está vacía y no alberga ninguna nave.

?NAVE: La celda del tablero representa una nave del jugador que aún no ha sido abatida.

?NAVEALCANZADA: La celda del tablero representa una nave del jugador que ha sido abatida.

?NAVE: La celda del tablero representa una nave del jugador que aún no ha sido abatida.

?NAVE: Otro jugador ha disparado a la posición, representada por la celda, pero no existía ninguna nave ubicada en ella.

Function Index

disparo/3
   Esta función permite disparar a una posición, en el tablero del jugador pasado como parámetro, en las coordenadas (Y,X).

estan_naves_posicionadas/1
   Esta función permite saber si un jugador ha terminado de colocar sus naves en el tablero.

get_posiciones/1
   Esta función devuelve un diccionario con el estado de las posiciones del tablero pasado como parámetro.

get_resultado/3
   Esta función permite obtener el estado actual de una celda del tablero.

posicionar_nave/3
   Esta función permite posicionar una nave en el tablero del jugador, pasado como parámetro, en las coordenadas (Y,X).

start_link/0
   Esta función crea un nuevo proceso tablero.

todo_destruido/1
   Esta función permite saber si todas las naves de un determinado tablero han sido alcanzadas.

Function Details

disparo/3

<tt>tablero:disparo(Tablero::pid(), X::integer(), Y::integer()) -> atom()</tt>

   Esta función permite disparar a una posición, en el tablero del jugador pasado como parámetro, en las coordenadas (Y,X).
   Para ello envía un mensaje con la información necesaria al tablero del jugador.

Valor de retorno

   Esta función retorna ?VACIO, ?NAVE, ?NAVEALCANZADA, ?DISPARADO o ?ERROR, en función del estado en el que se encuentre
   el tablero del jugador.

estan_naves_posicionadas/1

<tt>tablero:estan_naves_posicionadas(Tablero::pid()) -> atom()</tt>

   Esta función permite saber si un jugador ha terminado de colocar sus naves en el tablero.

Valor de retorno

true: Si el jugador ha terminado de posicionar todas sus naves en el tablero.

false: En caso contrario.

get_posiciones/1

<tt>tablero:get_posiciones(Tablero::pid()) -> dict()</tt>

   Esta función devuelve un diccionario con el estado de las posiciones del tablero pasado como parámetro.

Parámetros

Tablero: Pid del proceso tablero objetivo.

Valor de retorno

   Un diccionario cuya clave es la tupla {X,Y} (coordenada de una celda del tablero) y cuyo valor es uno de
   los estados en el que se puede encontrar la celda: ?VACIO, ?NAVE, ?NAVEALCANZADA, ?DISPARADO.

get_resultado/3

<tt>tablero:get_resultado(Tablero::pid(), X::integer(), Y::integer()) -> {atom(), atom()} | atom()</tt>

   Esta función permite obtener el estado actual de una celda del tablero.

Parámetros

X,Y: Coordenadas de la celda del tablero.

Tablero: Pid del proceso tablero objetivo.

Valor de retorno

   Esta función retorna:
   {ok,?VACIO}, {ok,?NAVE}, {ok,?NAVEALCANZADA}, {ok,?DISPARADO} o ?ERROR, en función del estado en el que se encuentre
   la celda del tablero del jugador.

posicionar_nave/3

<tt>tablero:posicionar_nave(Tablero::pid(), X::integer(), Y::integer()) -> atom()</tt>

   Esta función permite posicionar una nave en el tablero del jugador, pasado como parámetro, en las coordenadas (Y,X).
   Para ello envía un mensaje con la información necesaria al tablero del jugador.

Valor de retorno

ok: Retorna siempre ?OK (predefinido al átomo ok).

start_link/0

<tt>tablero:start_link() -> pid()</tt>

   Esta función crea un nuevo proceso tablero.

Valor de retorno

Pid: El pid del nuevo proceso creado.

todo_destruido/1

<tt>tablero:todo_destruido(Tablero::pid()) -> atom()</tt>

   Esta función permite saber si todas las naves de un determinado tablero han sido alcanzadas.

Valor de retorno

true: Si todas las naves han sido destruidas.

false: En caso contrario.

Overview

Generated by EDoc, Jan 11 2014, 16:48:29.


text:
<?php
namespace Beech\Absence\Controller;

/*                                                                        *
 * This script belongs to beechit/mrmaks.                                 *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License as published by the *
 * Free Software Foundation, either version 3 of the License, or (at your *
 * option) any later version.                                             *
 *                                                                        *
 * This script is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser       *
 * General Public License for more details.                               *
 *                                                                        *
 * You should have received a copy of the GNU Lesser General Public       *
 * License along with the script.                                         *
 * If not, see http://www.gnu.org/licenses/lgpl.html                      *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use TYPO3\Flow\Annotations as Flow;

/**
 * AbsenceArrangement controller for the Beech.Absence package
 *
 * @Flow\Scope("singleton")
 */
class AbsenceArrangementController extends \Beech\Ehrm\Controller\AbstractManagementController {

	/**
	 * @var string
	 */
	protected $entityClassName = 'Beech\Absence\Domain\Model\AbsenceArrangement';

	/**
	 * @var string
	 */
	protected $repositoryClassName = 'Beech\Absence\Domain\Repository\AbsenceArrangementRepository';
}

?>


text:
#pragma once

#include "il2cpp-config.h"
#include "il2cpp-object-internals.h"

struct Il2CppComObject;
struct Il2CppGuid;
struct Il2CppIUnknown;

namespace il2cpp
{
namespace vm
{
    class LIBIL2CPP_CODEGEN_API RCW
    {
    public:
        static void Register(Il2CppComObject* rcw);
        static Il2CppObject* GetOrCreateFromIUnknown(Il2CppIUnknown* unknown, Il2CppClass* fallbackClass);
        static Il2CppObject* GetOrCreateFromIInspectable(Il2CppIInspectable* inspectable, Il2CppClass* fallbackClass);
        static Il2CppObject* GetOrCreateForSealedClass(Il2CppIUnknown* unknown, Il2CppClass* objectClass);
        static void Cleanup(Il2CppComObject* rcw);
        static bool CacheQueriedInterface(Il2CppComObject* rcw, const Il2CppGuid& iid, Il2CppIUnknown* queriedInterface);
        static const VirtualInvokeData* GetComInterfaceInvokeData(Il2CppComObject* rcw, const Il2CppClass* targetInterface, Il2CppMethodSlot slot);

        template<bool throwOnError>
        inline static Il2CppIUnknown* QueryInterfaceNoAddRef(Il2CppComObject* rcw, const Il2CppGuid& iid)
        {
            IL2CPP_ASSERT(rcw);
            IL2CPP_ASSERT(rcw->identity);

            Il2CppIUnknown* result = QueryInterfaceCached(rcw, iid);
            if (result != NULL)
                return result;

            const il2cpp_hresult_t hr = rcw->identity->QueryInterface(iid, reinterpret_cast<void**>(&result));
            if (IL2CPP_HR_FAILED(hr))
            {
                if (throwOnError)
                    Exception::Raise(hr, true);

                return NULL;
            }

            IL2CPP_ASSERT(result);
            if (!CacheQueriedInterface(rcw, iid, result))
            {
                // We lost the race - another thread won it.
                result->Release();
                return QueryInterfaceCached(rcw, iid);
            }

            return result;
        }

    private:
        static Il2CppIUnknown* QueryInterfaceCached(Il2CppComObject* rcw, const Il2CppGuid& iid);
        static const VirtualInvokeData* GetComInterfaceInvokeData(Il2CppClass* queriedInterface, const Il2CppClass* targetInterface, Il2CppMethodSlot slot);
    };
} /* namespace vm */
} /* namespace il2cpp */


text:
package org.encog;

/**
 * This class allows for Encog jobs to report their current status, as they run.
 */
public interface StatusReportable {

    /**
     * Report on current status.
     * <p/>
     * @param total
     *                The total amount of units to process.
     * @param current
     *                The current unit being processed.
     * @param message
     *                The message to currently display.
     */
    void report(int total, int current, String message);
}


text:
/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * Basic initialization for the CC2650 System on Chip.
 */

#include <toolchain/gcc.h>
#include <init.h>
#include <sys_io.h>

#include "soc.h"

#define CCFG_SIZE	88

/* The bootloader of the SoC (in ROM) reads configuration
 * data (CCFG) at a fixed address (last page of flash).
 * The most notable information being whether to run the
 * code stored in flash or not.
 *
 * We put configuration data in a specific section so that
 * the linker script can map it accordingly.
 */
const u32_t
__ti_ccfg_section
ti_ccfg[CCFG_SIZE / sizeof(u32_t)] = {
	0x00008001, /* EXT_LF_CLK: default values */
	0xFF13FFFF, /* MODE_CONF_1: default values */
	0x0058FFFF, /* SIZE_AND_DIS_FLAGS: 88 bytes long, no external osc. */
	0xFFFFFFFF, /* MODE_CONF: default values */
	0xFFFFFFFF, /* VOLT_LOAD_0: default values */
	0xFFFFFFFF, /* VOLT_LOAD_1: default values */
	0xFFFFFFFF, /* RTC_OFFSET: default values */
	0xFFFFFFFF, /* FREQ_OFFSET: default values */
	0xFFFFFFFF, /* IEEE_MAC_0: use MAC address from FCFG */
	0xFFFFFFFF, /* IEEE_MAC_1: use MAC address from FCFG */
	0xFFFFFFFF, /* IEEE_BLE_0: use BLE address from FCFG */
	0xFFFFFFFF, /* IEEE_BLE_1: use BLE address from FCFG */
	/* BL_CONFIG: disable backdoor and bootloader,
	 * default pin, default active level (high)
	 */
	CC2650_CCFG_BACKDOOR_DISABLED |
		(0xFF << CC2650_CCFG_BL_CONFIG_BL_PIN_NUMBER_POS) |
		(0x1  << CC2650_CCFG_BL_CONFIG_BL_LEVEL_POS) |
		0x00FE0000 | /* reserved */
		CC2650_CCFG_BOOTLOADER_DISABLED,
	0xFFFFFFFF, /* ERASE_CONF: default values (banks + chip erase) */
	/* CCFG_TI_OPTIONS: disable TI failure analysis */
	CC2650_CCFG_TI_FA_DISABLED |
		0xFFFFFF00, /* reserved */
	0xFFC5C5C5, /* CCFG_TAP_DAP_0: default values */
	0xFFC5C5C5, /* CCFG_TAP_DAP_1: default values */
	/* IMAGE_VALID_CONF: authorize program on flash to run */
	CC2650_CCFG_IMAGE_IS_VALID,
	/* Make all flash chip programmable + erasable
	 * (which is default)
	 */
	0xFFFFFFFF, /* CCFG_PROT_31_0 */
	0xFFFFFFFF, /* CCFG_PROT_61_32 */
	0xFFFFFFFF, /* CCFG_PROT_95_64 */
	0xFFFFFFFF  /* CCFG_PROT_127_96 */
};

/* PRCM Registers */
static const u32_t clkloadctl =
	REG_ADDR(TI_CC2650_PRCM_40082000_BASE_ADDRESS,
		 CC2650_PRCM_CLKLOADCTL);
static const u32_t gpioclkgr =
	REG_ADDR(TI_CC2650_PRCM_40082000_BASE_ADDRESS,
		 CC2650_PRCM_GPIOCLKGR);
static const u32_t pdctl0 =
	REG_ADDR(TI_CC2650_PRCM_40082000_BASE_ADDRESS,
		 CC2650_PRCM_PDCTL0);
static const u32_t pdstat0 =
	REG_ADDR(TI_CC2650_PRCM_40082000_BASE_ADDRESS,
		 CC2650_PRCM_PDSTAT0);
#ifdef CONFIG_SERIAL
static const u32_t uartclkgr =
	REG_ADDR(TI_CC2650_PRCM_40082000_BASE_ADDRESS,
		 CC2650_PRCM_UARTCLKGR);
#endif

/* Setup power and clock for needed hardware modules. */
static void setup_modules_prcm(void)
{
#if defined(CONFIG_GPIO_CC2650) || \
	defined(CONFIG_SERIAL)

	/* Setup power */
#if defined(CONFIG_GPIO_CC2650)
	sys_set_bit(pdctl0, CC2650_PRCM_PDCTL0_PERIPH_ON_POS);
#endif
#ifdef CONFIG_SERIAL
	sys_set_bit(pdctl0, CC2650_PRCM_PDCTL0_SERIAL_ON_POS);
#endif

	/* Setup clocking */
#ifdef CONFIG_GPIO_CC2650
	sys_set_bit(gpioclkgr, CC2650_PRCM_GPIOCLKGR_CLK_EN_POS);
#endif
#ifdef CONFIG_SERIAL
	sys_set_bit(uartclkgr, CC2650_PRCM_UARTCLKGR_CLK_EN_POS);
#endif
	/* Reload clocking configuration for device */
	sys_set_bit(clkloadctl, CC2650_PRCM_CLKLOADCTL_LOAD_POS);

	/* Wait for power to be completely on, to avoid bus faults
	 * when accessing modules' registers.
	 */
#if defined(CONFIG_GPIO_CC2650)
	while (!(sys_read32(pdstat0) &
	       BIT(CC2650_PRCM_PDSTAT0_PERIPH_ON_POS))) {
		continue;
	}
#endif
#if defined(CONFIG_SERIAL)
	while (!(sys_read32(pdstat0) &
	       BIT(CC2650_PRCM_PDSTAT0_SERIAL_ON_POS))) {
		continue;
	}
#endif

#endif
}

static int ti_cc2650(struct device *dev)
{
	ARG_UNUSED(dev);

	NMI_INIT();
	setup_modules_prcm();
	return 0;
}

SYS_INIT(ti_cc2650, PRE_KERNEL_1, 0);

int bit_is_set(u32_t reg, u8_t bit)
{
	return sys_read32(reg) & BIT(bit);
}


text:
package net.fortuna.ical4j.model.property;

import junit.framework.TestSuite;
import net.fortuna.ical4j.model.PropertyTest;
import net.fortuna.ical4j.model.Recur;

import java.text.ParseException;

/**
 * $Id$
 *
 * Created on: 24/11/2008
 *
 * @author fortuna
 */
public class RRuleTest extends PropertyTest {

    /**
     * @param property
     * @param expectedValue
     */
    public RRuleTest(RRule rule, String expectedValue) {
        super(rule, expectedValue);
    }

    /**
	 * @param testMethod
	 * @param property
	 */
	public RRuleTest(String testMethod, RRule property) {
		super(testMethod, property);
	}

	/**
     * @return
     * @throws ParseException
     */
    public static TestSuite suite() {
        TestSuite suite = new TestSuite();
        RRule rule = new RRule(new Recur.Builder().frequency(Recur.Frequency.WEEKLY).count(3).build());
        suite.addTest(new RRuleTest(rule, "FREQ=WEEKLY;COUNT=3"));
        suite.addTest(new RRuleTest("testValidation", rule));
        suite.addTest(new RRuleTest("testEquals", rule));
        return suite;
    }

}


text:
{% extends "layout.html" %}
{% block body %}

    {% if problem %}
        {% set problem_id=problem.id %}

修改题目

    {% else %}
        {% set problem_id=0 %}

上传题目

    {% endif %}
    <form class="am-form" method="post" action="{{url_for('edit_problem',problem_id=problem_id)}}">

                    编辑

                    预览

                    <fieldset>

                            题目名称
                            <input type="text" class="am-form-field" id="title" name="title"
                                   value="{% if problem %}{{problem.title}}{% endif %}">

                            题目描述
                            <textarea class="" rows="5" id="description" name="description">{% if problem %}{{problem.description}}{% endif %}</textarea>

                            输入格式
                            <textarea class="" rows="5" id="input" name="input_format">{% if problem %}{{problem.input_format}}{% endif %}</textarea>

                            输出格式
                            <textarea class="" rows="5" id="output" name="output_format">{% if problem %}{{problem.output_format}}{% endif %}</textarea>

                            样例
                            <textarea class="" rows="5" id="example" name="example">{% if problem %}{{problem.example}}{% endif %}</textarea>

                            数据范围与提示
                            <textarea class="" rows="5" id="hint" name="limit_and_hint">{% if problem %}{{problem.limit_and_hint}}{% endif %}</textarea>

                    </fieldset>

题目描述

输入格式

输出格式

测试样例

数据范围与提示

        <button type="submit" class="am-btn am-btn-default">提交</button>
    </form>

{% endblock %}

{% block script %}

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min.css">

{% endblock %}


text: CS3219 Assignment 1


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Umbraco.Core.Models.Entities;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Core.Models
{
    /// <summary>
    /// Implements <see cref="IDataType"/>.
    /// </summary>
    [Serializable]
    [DataContract(IsReference = true)]
    public class DataType : TreeEntityBase, IDataType
    {
        private static PropertySelectors _selectors;

        private IDataEditor _editor;
        private ValueStorageType _databaseType;
        private object _configuration;
        private bool _hasConfiguration;
        private string _configurationJson;

        /// <summary>
        /// Initializes a new instance of the <see cref="DataType"/> class.
        /// </summary>
        public DataType(IDataEditor editor, int parentId = -1)
        {
            _editor = editor ?? throw new ArgumentNullException(nameof(editor));
            ParentId = parentId;

            // set a default configuration
            Configuration = _editor.GetConfigurationEditor().DefaultConfigurationObject;
        }

        private static PropertySelectors Selectors => _selectors ?? (_selectors = new PropertySelectors());

        private class PropertySelectors
        {
            public readonly PropertyInfo Editor = ExpressionHelper.GetPropertyInfo<DataType, IDataEditor>(x => x.Editor);
            public readonly PropertyInfo DatabaseType = ExpressionHelper.GetPropertyInfo<DataType, ValueStorageType>(x => x.DatabaseType);
            public readonly PropertyInfo Configuration = ExpressionHelper.GetPropertyInfo<DataType, object>(x => x.Configuration);
        }

        /// <inheritdoc />
        [IgnoreDataMember]
        public IDataEditor Editor
        {
            get => _editor;
            set
            {
                // ignore if no change
                if (_editor.Alias == value.Alias) return;
                OnPropertyChanged(Selectors.Editor);

                // try to map the existing configuration to the new configuration
                // simulate saving to db and reloading (ie go via json)
                var configuration = Configuration;
                var json = JsonConvert.SerializeObject(configuration);
                _editor = value;
                Configuration = _editor.GetConfigurationEditor().FromDatabase(json);
            }
        }

        /// <inheritdoc />
        [DataMember]
        public string EditorAlias => _editor.Alias;

        /// <inheritdoc />
        [DataMember]
        public ValueStorageType DatabaseType
        {
            get => _databaseType;
            set => SetPropertyValueAndDetectChanges(value, ref _databaseType, Selectors.DatabaseType);
        }

        /// <inheritdoc />
        [DataMember]
        public object Configuration
        {
            get
            {
                // if we know we have a configuration (which may be null), return it
                // if we don't have an editor, then we have no configuration, return null
                // else, use the editor to get the configuration object

                if (_hasConfiguration) return _configuration;

                _configuration = _editor.GetConfigurationEditor().FromDatabase(_configurationJson);
                _hasConfiguration = true;
                _configurationJson = null;

                return _configuration;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException(nameof(value));

                // we don't support re-assigning the same object
                // configurations are kinda non-mutable, mainly because detecting changes would be a pain
                if (_configuration == value) // reference comparison
                    throw new ArgumentException("Configurations are kinda non-mutable. Do not reassign the same object.", nameof(value));

                // validate configuration type
                if (!_editor.GetConfigurationEditor().IsConfiguration(value))
                    throw new ArgumentException($"Value of type {value.GetType().Name} cannot be a configuration for editor {_editor.Alias}, expecting.", nameof(value));

                // extract database type from configuration object, if appropriate
                if (value is IConfigureValueType valueTypeConfiguration)
                    DatabaseType = ValueTypes.ToStorageType(valueTypeConfiguration.ValueType);

                // extract database type from dictionary, if appropriate
                if (value is IDictionary<string, object> dictionaryConfiguration
                    && dictionaryConfiguration.TryGetValue(Constants.PropertyEditors.ConfigurationKeys.DataValueType, out var valueTypeObject)
                    && valueTypeObject is string valueTypeString
                    && ValueTypes.IsValue(valueTypeString))
                    DatabaseType = ValueTypes.ToStorageType(valueTypeString);

                _configuration = value;
                _hasConfiguration = true;
                _configurationJson = null;

                // it's always a change
                OnPropertyChanged(Selectors.Configuration);
            }
        }

        /// <summary>
        /// Lazily set the configuration as a serialized json string.
        /// </summary>
        /// <remarks>
        /// <para>Will be de-serialized on-demand.</para>
        /// <para>This method is meant to be used when building entities from database, exclusively.
        /// It does NOT register a property change to dirty. It ignores the fact that the configuration
        /// may contain the database type, because the datatype DTO should also contain that database
        /// type, and they should be the same.</para>
        /// <para>Think before using!</para>
        /// </remarks>
        internal void SetLazyConfiguration(string configurationJson)
        {
            _hasConfiguration = false;
            _configuration = null;
            _configurationJson = configurationJson;
        }

        /// <summary>
        /// Gets a lazy configuration.
        /// </summary>
        /// <remarks>
        /// <para>The configuration object will be lazily de-serialized.</para>
        /// <para>This method is meant to be used when creating published datatypes, exclusively.</para>
        /// <para>Think before using!</para>
        /// </remarks>
        internal Lazy<object> GetLazyConfiguration()
        {
            // note: in both cases, make sure we capture what we need - we don't want
            // to capture a reference to this full, potentially heavy, DataType instance.

            if (_hasConfiguration)
            {
                // if configuration has already been de-serialized, return
                var capturedConfiguration = _configuration;
                return new Lazy<object>(() => capturedConfiguration);
            }
            else
            {
                // else, create a Lazy de-serializer
                var capturedConfiguration = _configurationJson;
                var capturedEditor = _editor;
                return new Lazy<object>(() => capturedEditor.GetConfigurationEditor().FromDatabase(capturedConfiguration));
            }
        }
    }
}


text:
package edu.umkc.permitme.repository;

import edu.umkc.permitme.domain.SocialUserConnection;

import org.springframework.social.connect.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.*;
import java.util.stream.Collectors;

public class CustomSocialConnectionRepository implements ConnectionRepository {

    private String userId;

    private SocialUserConnectionRepository socialUserConnectionRepository;

    private ConnectionFactoryLocator connectionFactoryLocator;

    public CustomSocialConnectionRepository(String userId, SocialUserConnectionRepository socialUserConnectionRepository, ConnectionFactoryLocator connectionFactoryLocator) {
        this.userId = userId;
        this.socialUserConnectionRepository = socialUserConnectionRepository;
        this.connectionFactoryLocator = connectionFactoryLocator;
    }

    @Override
    public MultiValueMap<String, Connection<?>> findAllConnections() {
        List<SocialUserConnection> socialUserConnections = socialUserConnectionRepository.findAllByUserIdOrderByProviderIdAscRankAsc(userId);
        List<Connection<?>> connections = socialUserConnectionsToConnections(socialUserConnections);
        MultiValueMap<String, Connection<?>> connectionsByProviderId = new LinkedMultiValueMap<>();
        Set<String> registeredProviderIds = connectionFactoryLocator.registeredProviderIds();
        for (String registeredProviderId : registeredProviderIds) {
            connectionsByProviderId.put(registeredProviderId, Collections.emptyList());
        }
        for (Connection<?> connection : connections) {
            String providerId = connection.getKey().getProviderId();
            if (connectionsByProviderId.get(providerId).size() == 0) {
                connectionsByProviderId.put(providerId, new LinkedList<>());
            }
            connectionsByProviderId.add(providerId, connection);
        }
        return connectionsByProviderId;
    }

    @Override
    public List<Connection<?>> findConnections(String providerId) {
        List<SocialUserConnection> socialUserConnections = socialUserConnectionRepository.findAllByUserIdAndProviderIdOrderByRankAsc(userId, providerId);
        return socialUserConnectionsToConnections(socialUserConnections);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <A> List<Connection<A>> findConnections(Class<A> apiType) {
        List<?> connections = findConnections(getProviderId(apiType));
        return (List<Connection<A>>) connections;
    }

    @Override
    public MultiValueMap<String, Connection<?>> findConnectionsToUsers(MultiValueMap<String, String> providerUserIdsByProviderId) {
        if (providerUserIdsByProviderId == null || providerUserIdsByProviderId.isEmpty()) {
            throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
        }

        MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<>();
        for (Map.Entry<String, List<String>> entry : providerUserIdsByProviderId.entrySet()) {
            String providerId = entry.getKey();
            List<String> providerUserIds = entry.getValue();
            List<Connection<?>> connections = providerUserIdsToConnections(providerId, providerUserIds);
            connections.forEach(connection -> connectionsForUsers.add(providerId, connection));
        }
        return connectionsForUsers;
    }

    @Override
    public Connection<?> getConnection(ConnectionKey connectionKey) {
        SocialUserConnection socialUserConnection = socialUserConnectionRepository.findOneByUserIdAndProviderIdAndProviderUserId(userId, connectionKey.getProviderId(), connectionKey.getProviderUserId());
        return Optional.ofNullable(socialUserConnection)
            .map(this::socialUserConnectionToConnection)
            .orElseThrow(() -> new NoSuchConnectionException(connectionKey));
    }

    @Override
    @SuppressWarnings("unchecked")
    public <A> Connection<A> getConnection(Class<A> apiType, String providerUserId) {
        String providerId = getProviderId(apiType);
        return (Connection<A>) getConnection(new ConnectionKey(providerId, providerUserId));
    }

    @Override
    @SuppressWarnings("unchecked")
    public <A> Connection<A> getPrimaryConnection(Class<A> apiType) {
        String providerId = getProviderId(apiType);
        Connection<A> connection = (Connection<A>) findPrimaryConnection(providerId);
        if (connection == null) {
            throw new NotConnectedException(providerId);
        }
        return connection;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <A> Connection<A> findPrimaryConnection(Class<A> apiType) {
        String providerId = getProviderId(apiType);
        return (Connection<A>) findPrimaryConnection(providerId);
    }

    @Override
    @Transactional
    public void addConnection(Connection<?> connection) {
        Long rank = getNewMaxRank(connection.getKey().getProviderId()).longValue();
        SocialUserConnection socialUserConnectionToSave = connectionToUserSocialConnection(connection, rank);
        socialUserConnectionRepository.save(socialUserConnectionToSave);
    }

    @Override
    @Transactional
    public void updateConnection(Connection<?> connection) {
        SocialUserConnection socialUserConnection = socialUserConnectionRepository.findOneByUserIdAndProviderIdAndProviderUserId(userId, connection.getKey().getProviderId(), connection.getKey().getProviderUserId());
        if (socialUserConnection != null) {
            SocialUserConnection socialUserConnectionToUdpate =  connectionToUserSocialConnection(connection, socialUserConnection.getRank());
            socialUserConnectionToUdpate.setId(socialUserConnection.getId());
            socialUserConnectionRepository.save(socialUserConnectionToUdpate);
        }
    }

    @Override
    @Transactional
    public void removeConnections(String providerId) {
        socialUserConnectionRepository.deleteByUserIdAndProviderId(userId, providerId);
    }

    @Override
    @Transactional
    public void removeConnection(ConnectionKey connectionKey) {
        socialUserConnectionRepository.deleteByUserIdAndProviderIdAndProviderUserId(userId, connectionKey.getProviderId(), connectionKey.getProviderUserId());
    }

    private Double getNewMaxRank(String providerId) {
        List<SocialUserConnection> socialUserConnections = socialUserConnectionRepository.findAllByUserIdAndProviderIdOrderByRankAsc(userId, providerId);
        return socialUserConnections.stream()
            .mapToDouble(SocialUserConnection::getRank)
            .max()
            .orElse(0D) + 1D;
    }

    private Connection<?> findPrimaryConnection(String providerId) {
        List<SocialUserConnection> socialUserConnections = socialUserConnectionRepository.findAllByUserIdAndProviderIdOrderByRankAsc(userId, providerId);
        if (socialUserConnections.size() > 0) {
            return socialUserConnectionToConnection(socialUserConnections.get(0));
        } else {
            return null;
        }
    }

    private SocialUserConnection connectionToUserSocialConnection(Connection<?> connection, Long rank) {
        ConnectionData connectionData = connection.createData();
        return new SocialUserConnection(
            userId,
            connection.getKey().getProviderId(),
            connection.getKey().getProviderUserId(),
            rank,
            connection.getDisplayName(),
            connection.getProfileUrl(),
            connection.getImageUrl(),
            connectionData.getAccessToken(),
            connectionData.getSecret(),
            connectionData.getRefreshToken(),
            connectionData.getExpireTime()
        );
    }

    private List<Connection<?>> providerUserIdsToConnections(String providerId, List<String> providerUserIds) {
        List<SocialUserConnection> socialUserConnections = socialUserConnectionRepository.findAllByUserIdAndProviderIdAndProviderUserIdIn(userId, providerId, providerUserIds);
        return socialUserConnectionsToConnections(socialUserConnections);
    }

    private List<Connection<?>> socialUserConnectionsToConnections(List<SocialUserConnection> socialUserConnections) {
        return socialUserConnections.stream()
            .map(this::socialUserConnectionToConnection)
            .collect(Collectors.toList());
    }

    private Connection<?> socialUserConnectionToConnection(SocialUserConnection socialUserConnection) {
        ConnectionData connectionData = new ConnectionData(socialUserConnection.getProviderId(),
            socialUserConnection.getProviderUserId(),
            socialUserConnection.getDisplayName(),
            socialUserConnection.getProfileURL(),
            socialUserConnection.getImageURL(),
            socialUserConnection.getAccessToken(),
            socialUserConnection.getSecret(),
            socialUserConnection.getRefreshToken(),
            socialUserConnection.getExpireTime());
        ConnectionFactory<?> connectionFactory = connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId());
        return connectionFactory.createConnection(connectionData);
    }

    private <A> String getProviderId(Class<A> apiType) {
        return connectionFactoryLocator.getConnectionFactory(apiType).getProviderId();
    }
}


text:
package org.mifos.accounts.savings.persistence;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mifos.accounts.business.AccountActionDateEntity;
import org.mifos.accounts.business.AccountPaymentEntity;
import org.mifos.accounts.business.AccountStateEntity;
import org.mifos.accounts.business.AccountTestUtils;
import org.mifos.accounts.persistence.AccountPersistence;
import org.mifos.accounts.productdefinition.business.SavingsOfferingBO;
import org.mifos.accounts.productdefinition.util.helpers.RecommendedAmountUnit;
import org.mifos.accounts.savings.SavingBOTestUtils;
import org.mifos.accounts.savings.business.SavingsBO;
import org.mifos.accounts.savings.business.SavingsTrxnDetailEntity;
import org.mifos.accounts.savings.util.helpers.SavingsConstants;
import org.mifos.accounts.savings.util.helpers.SavingsTestHelper;
import org.mifos.accounts.util.helpers.AccountActionTypes;
import org.mifos.accounts.util.helpers.AccountState;
import org.mifos.accounts.util.helpers.AccountStates;
import org.mifos.accounts.util.helpers.AccountTypes;
import org.mifos.accounts.util.helpers.PaymentStatus;
import org.mifos.application.master.business.CustomFieldDefinitionEntity;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.config.business.Configuration;
import org.mifos.customers.business.CustomerBO;
import org.mifos.customers.checklist.business.AccountCheckListBO;
import org.mifos.customers.personnel.business.PersonnelBO;
import org.mifos.customers.personnel.persistence.PersonnelPersistence;
import org.mifos.customers.personnel.util.helpers.PersonnelConstants;
import org.mifos.customers.util.helpers.CustomerStatus;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
import org.mifos.security.util.UserContext;

public class SavingsPersistenceIntegrationTest extends MifosIntegrationTestCase {

    private final int SAVINGS_CUSTOMFIELDS_NUMBER = 1;

    private UserContext userContext;
    private SavingsPersistence savingsPersistence;
    private AccountPersistence accountPersistence;
    private CustomerBO group;
    private CustomerBO center;
    private SavingsBO savings;
    private SavingsBO savings1;
    private SavingsBO savings2;
    private SavingsOfferingBO savingsOffering;
    private SavingsOfferingBO savingsOffering2;
    @SuppressWarnings("unused")
    private AccountCheckListBO accountCheckList;

    @Before
    public void setUp() throws Exception {
        savingsPersistence = new SavingsPersistence();
        accountPersistence = new AccountPersistence();
        userContext = TestUtils.makeUser();

    }

    @After
    public void tearDown() throws Exception {
        savings = null;
        if (savings1 != null) {
            savings1 = null;
        }
        if (savings2 != null) {
            savings2 = null;
            savingsOffering2 = null;
        }

        group = null;
        center = null;
        accountCheckList = null;
        TestObjectFactory.removeObject(savingsOffering2);
        StaticHibernateUtil.flushSession();
    }

    @Test
    public void testRetrieveCustomFieldsDefinition() throws Exception {
        List<CustomFieldDefinitionEntity> customFields = savingsPersistence
                .retrieveCustomFieldsDefinition(SavingsConstants.SAVINGS_CUSTOM_FIELD_ENTITY_TYPE);
        Assert.assertNotNull(customFields);
        Assert.assertEquals(SAVINGS_CUSTOMFIELDS_NUMBER, customFields.size());
    }

    @Test
    public void testFindById() throws Exception {
        createInitialObjects();
        Date currentDate = new Date(System.currentTimeMillis());
        savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd1", "xdsa", currentDate,
                RecommendedAmountUnit.COMPLETE_GROUP);
        savings = createSavingsAccount("FFFF", savingsOffering);
        SavingsBO savings1 = savingsPersistence.findById(savings.getAccountId());
        Assert.assertEquals(savingsOffering.getRecommendedAmount(), savings1.getRecommendedAmount());
    }

    @Test
    public void testGetAccountStatus() throws Exception {
        AccountStateEntity accountState = savingsPersistence.getAccountStatusObject(AccountStates.SAVINGS_ACC_CLOSED);
        Assert.assertNotNull(accountState);
        Assert.assertEquals(accountState.getId().shortValue(), AccountStates.SAVINGS_ACC_CLOSED);
    }

    @Test
    public void testRetrieveAllAccountStateList() throws NumberFormatException, PersistenceException {
        List<AccountStateEntity> accountStateEntityList = accountPersistence.retrieveAllAccountStateList(Short
                .valueOf("2"));
        Assert.assertNotNull(accountStateEntityList);
        Assert.assertEquals(6, accountStateEntityList.size());
    }

    @Test
    public void testRetrieveAllActiveAccountStateList() throws NumberFormatException, PersistenceException {
        List<AccountStateEntity> accountStateEntityList = accountPersistence.retrieveAllActiveAccountStateList(Short
                .valueOf("2"));
        Assert.assertNotNull(accountStateEntityList);
        Assert.assertEquals(6, accountStateEntityList.size());
    }

    @Test
    public void testGetStatusChecklist() throws Exception {
        accountCheckList = TestObjectFactory.createAccountChecklist(AccountTypes.SAVINGS_ACCOUNT.getValue(),
                AccountState.SAVINGS_PARTIAL_APPLICATION, Short.valueOf("1"));
        List<AccountCheckListBO> statusCheckList = accountPersistence.getStatusChecklist(Short.valueOf("13"), AccountTypes.SAVINGS_ACCOUNT
                .getValue());
        Assert.assertNotNull(statusCheckList);

        Assert.assertEquals(1, statusCheckList.size());
    }

    @Test
    public void testFindBySystemId() throws Exception {
        createInitialObjects();
        Date currentDate = new Date(System.currentTimeMillis());
        savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd1", "v1ws", currentDate,
                RecommendedAmountUnit.COMPLETE_GROUP);
        savings = createSavingsAccount("kkk", savingsOffering);
        SavingsBO savings1 = savingsPersistence.findBySystemId(savings.getGlobalAccountNum());
        Assert.assertEquals(savings.getAccountId(), savings1.getAccountId());
        Assert.assertEquals(savingsOffering.getRecommendedAmount(), savings1.getRecommendedAmount());
    }

    @Test
    public void testRetrieveLastTransaction() throws Exception {
        try {
            SavingsTestHelper helper = new SavingsTestHelper();
            createInitialObjects();
            PersonnelBO createdBy = new PersonnelPersistence().getPersonnel(userContext.getId());
            savingsOffering = helper.createSavingsOffering("effwe", "231");
            savings = new SavingsBO(userContext, savingsOffering, group, AccountState.SAVINGS_ACTIVE, savingsOffering
                    .getRecommendedAmount(), null);

            AccountPaymentEntity payment = helper.createAccountPaymentToPersist(savings, new Money(Configuration
                    .getInstance().getSystemConfig().getCurrency(), "700.0"), new Money(Configuration.getInstance()
                    .getSystemConfig().getCurrency(), "1700.0"), helper.getDate("15/01/2006"),
                    AccountActionTypes.SAVINGS_DEPOSIT.getValue(), savings, createdBy, group);
            AccountTestUtils.addAccountPayment(payment, savings);
            savings.save();
            StaticHibernateUtil.flushSession();

            payment = helper.createAccountPaymentToPersist(savings, new Money(Configuration.getInstance()
                    .getSystemConfig().getCurrency(), "1000.0"), new Money(Configuration.getInstance()
                    .getSystemConfig().getCurrency(), "2700.0"), helper.getDate("20/02/2006"),
                    AccountActionTypes.SAVINGS_DEPOSIT.getValue(), savings, createdBy, group);
            AccountTestUtils.addAccountPayment(payment, savings);
            savings.update();
            StaticHibernateUtil.flushSession();

            savings = savingsPersistence.findById(savings.getAccountId());
            savings.setUserContext(userContext);
            payment = helper.createAccountPaymentToPersist(savings, new Money(Configuration.getInstance()
                    .getSystemConfig().getCurrency(), "500.0"), new Money(Configuration.getInstance().getSystemConfig()
                    .getCurrency(), "2200.0"), helper.getDate("10/03/2006"), AccountActionTypes.SAVINGS_WITHDRAWAL
                    .getValue(), savings, createdBy, group);
            AccountTestUtils.addAccountPayment(payment, savings);
            savings.update();
            StaticHibernateUtil.flushSession();

            savings = savingsPersistence.findById(savings.getAccountId());
            savings.setUserContext(userContext);
            payment = helper.createAccountPaymentToPersist(savings, new Money(Configuration.getInstance()
                    .getSystemConfig().getCurrency(), "1200.0"), new Money(Configuration.getInstance()
                    .getSystemConfig().getCurrency(), "3400.0"), helper.getDate("15/03/2006"),
                    AccountActionTypes.SAVINGS_DEPOSIT.getValue(), savings, createdBy, group);
            AccountTestUtils.addAccountPayment(payment, savings);
            savings.update();
            StaticHibernateUtil.flushSession();

            savings = savingsPersistence.findById(savings.getAccountId());
            savings.setUserContext(userContext);
            payment = helper.createAccountPaymentToPersist(savings, new Money(Configuration.getInstance()
                    .getSystemConfig().getCurrency(), "2500.0"), new Money(Configuration.getInstance()
                    .getSystemConfig().getCurrency(), "900.0"), helper.getDate("25/03/2006"),
                    AccountActionTypes.SAVINGS_WITHDRAWAL.getValue(), savings, createdBy, group);
            AccountTestUtils.addAccountPayment(payment, savings);
            savings.update();
            StaticHibernateUtil.flushSession();

            savings = savingsPersistence.findById(savings.getAccountId());
            savings.setUserContext(userContext);
            SavingsTrxnDetailEntity trxn = savingsPersistence.retrieveLastTransaction(savings.getAccountId(), helper
                    .getDate("12/03/2006"));
            Assert.assertEquals(TestUtils.createMoney("500"), trxn.getAmount());
            group = savings.getCustomer();
            center = group.getParentCustomer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testGetMissedDeposits() throws Exception {
        SavingsTestHelper helper = new SavingsTestHelper();
        MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
        center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
        group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
        savingsOffering = helper.createSavingsOffering("SavingPrd1", "wsed", Short.valueOf("1"), Short.valueOf("1"));
        savings = TestObjectFactory.createSavingsAccount("43245434", group, Short.valueOf("16"), new Date(System
                .currentTimeMillis()), savingsOffering);

        AccountActionDateEntity accountActionDateEntity = savings.getAccountActionDate((short) 1);
        SavingBOTestUtils.setActionDate(accountActionDateEntity, offSetCurrentDate(7));

        savings.update();
        StaticHibernateUtil.flushSession();

        savings = savingsPersistence.findById(savings.getAccountId());
        savings.setUserContext(userContext);
        StaticHibernateUtil.flushSession();
        Calendar currentDateCalendar = new GregorianCalendar();
        java.sql.Date currentDate = new java.sql.Date(currentDateCalendar.getTimeInMillis());

        Assert.assertEquals(savingsPersistence.getMissedDeposits(savings.getAccountId(), currentDate), 1);
    }

    @Test
    public void testGetMissedDepositsPaidAfterDueDate() throws Exception {
        SavingsTestHelper helper = new SavingsTestHelper();
        MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
        center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
        group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
        savingsOffering = helper.createSavingsOffering("SavingPrd1", "cvfg", Short.valueOf("1"), Short.valueOf("1"));
        ;
        savings = TestObjectFactory.createSavingsAccount("43245434", group, Short.valueOf("16"), new Date(System
                .currentTimeMillis()), savingsOffering);

        AccountActionDateEntity accountActionDateEntity = savings.getAccountActionDate((short) 1);
        SavingBOTestUtils.setActionDate(accountActionDateEntity, offSetCurrentDate(7));
        accountActionDateEntity.setPaymentStatus(PaymentStatus.PAID);
        Calendar currentDateCalendar = new GregorianCalendar();
        java.sql.Date currentDate = new java.sql.Date(currentDateCalendar.getTimeInMillis());

        SavingBOTestUtils.setPaymentDate(accountActionDateEntity, currentDate);
        savings.update();
        StaticHibernateUtil.flushSession();
        savings = savingsPersistence.findById(savings.getAccountId());
        savings.setUserContext(userContext);
        StaticHibernateUtil.flushSession();
        Assert.assertEquals(savingsPersistence.getMissedDepositsPaidAfterDueDate(savings.getAccountId()), 1);
    }

    @Test
    public void testGetAllSavingsAccount() throws Exception {
        createInitialObjects();
        Date currentDate = new Date(System.currentTimeMillis());
        savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd1", "v1ws", currentDate,
                RecommendedAmountUnit.COMPLETE_GROUP);
        savings = createSavingsAccount("kkk", savingsOffering);

        List<SavingsBO> savingsAccounts = savingsPersistence.getAllSavingsAccount();
        Assert.assertNotNull(savingsAccounts);
        Assert.assertEquals(1, savingsAccounts.size());

    }

    private void createInitialObjects() {
        MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
        center = TestObjectFactory.createWeeklyFeeCenter("Center_Active_test", meeting);
        group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);

    }

    private SavingsBO createSavingsAccount(String globalAccountNum, SavingsOfferingBO savingsOffering)
            throws NumberFormatException, Exception {
        UserContext userContext = new UserContext(Locale.getDefault(), Short.valueOf("1"));
        userContext.setId(PersonnelConstants.SYSTEM_USER);
        userContext.setBranchGlobalNum("1001");
        return TestObjectFactory.createSavingsAccount(globalAccountNum, group, AccountState.SAVINGS_PENDING_APPROVAL,
                new Date(), savingsOffering, userContext);
    }

    private java.sql.Date offSetCurrentDate(int noOfDays) {
        Calendar currentDateCalendar = new GregorianCalendar();
        int year = currentDateCalendar.get(Calendar.YEAR);
        int month = currentDateCalendar.get(Calendar.MONTH);
        int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
        currentDateCalendar = new GregorianCalendar(year, month, day - noOfDays);
        return new java.sql.Date(currentDateCalendar.getTimeInMillis());
    }
}