text:
package org.apache.struts2.views.jsp;

import com.mockobjects.servlet.MockJspWriter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import junit.textui.TestRunner;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.portlet.PortletConstants;
import org.apache.struts2.portlet.PortletPhase;
import org.apache.struts2.portlet.util.PortletUrlHelper;
import org.jmock.Mock;
import org.jmock.cglib.MockObjectTestCase;
import org.jmock.core.Constraint;

import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static org.apache.struts2.StrutsStatics.STRUTS_PORTLET_CONTEXT;

/**
 */
@SuppressWarnings("unchecked")
public class PortletUrlTagTest extends MockObjectTestCase {

    URLTag tag = new URLTag();

    Mock mockHttpReq = null;

    Mock mockHttpRes = null;

    Mock mockPortletReq = null;

    Mock mockPortletRes = null;

    Mock mockPageCtx = null;

    Mock mockPortletUrl = null;

    MockJspWriter mockJspWriter = null;

    Mock mockCtx = null;

    ValueStack stack = null;

    Mock mockActionProxy = null;

	Mock mockActionInvocation = null;

    public static void main(String[] args) {
        TestRunner.run(PortletUrlTagTest.class);
    }

    public void setUp() throws Exception {
        super.setUp();

        Dispatcher du = new Dispatcher(null, new HashMap());
        du.init();
        Dispatcher.setInstance(du);

        stack = du.getContainer().getInstance(ValueStackFactory.class).createValueStack();
        stack.getContext().put(ActionContext.CONTAINER, du.getContainer());
        ActionContext context = new ActionContext(stack.getContext());
        ActionContext.setContext(context);

    	mockActionInvocation  = mock(ActionInvocation.class);
        mockActionProxy = mock(ActionProxy.class);
        mockHttpReq = mock(HttpServletRequest.class);
        mockHttpRes = mock(HttpServletResponse.class);
        mockPortletReq = mock(RenderRequest.class);
        mockPortletRes = mock(RenderResponse.class);
        mockPageCtx = mock(PageContext.class);
        mockPortletUrl = mock(PortletURL.class);
        mockJspWriter = new MockJspWriter();
        mockCtx = mock(PortletContext.class);

        mockActionProxy.stubs().method("getNamespace").will(returnValue("/view"));
        mockActionInvocation.stubs().method("getProxy").will(returnValue(
                mockActionProxy.proxy()));
        mockPageCtx.stubs().method("getRequest").will(
                returnValue(mockHttpReq.proxy()));
        mockPageCtx.stubs().method("getResponse").will(
                returnValue(mockHttpRes.proxy()));
        mockPageCtx.stubs().method("getOut").will(returnValue(mockJspWriter));

        mockHttpReq.stubs().method("getScheme").will(returnValue("http"));
        mockHttpReq.stubs().method("getAttribute").with(
                eq("struts.valueStack")).will(returnValue(stack));
        mockHttpReq.stubs().method("getAttribute").with(
                eq("javax.portlet.response")).will(
                returnValue(mockPortletRes.proxy()));
        mockHttpReq.stubs().method("getAttribute").with(
                eq("javax.portlet.request")).will(
                returnValue(mockPortletReq.proxy()));
        mockHttpReq.stubs().method("getAttribute").with(
                eq("javax.servlet.include.servlet_path")).will(
                returnValue("/servletPath"));
        mockHttpReq.stubs().method("getParameterMap").will(
                returnValue(Collections.emptyMap()));

        mockPortletReq.stubs().method("getPortletMode").will(returnValue(PortletMode.VIEW));
        mockPortletReq.stubs().method("getWindowState").will(returnValue(WindowState.NORMAL));
        mockPortletReq.stubs().method("getContextPath").will(returnValue("/contextPath"));

        tag.setPageContext((PageContext) mockPageCtx.proxy());

        Map modeMap = new HashMap();
        modeMap.put(PortletMode.VIEW, "/view");
        modeMap.put(PortletMode.HELP, "/help");
        modeMap.put(PortletMode.EDIT, "/edit");
        Map<PortletMode,ActionMapping> actionMap = new HashMap<PortletMode,ActionMapping>();
        actionMap.put(PortletMode.VIEW, new ActionMapping("defaultView", "/view", "execute", new HashMap<String,Object>()));
        actionMap.put(PortletMode.HELP, new ActionMapping("defaultHelp", "/help", "execute", new HashMap<String,Object>()));
        actionMap.put(PortletMode.EDIT, new ActionMapping("defaultEdit", "/edit", "execute", new HashMap<String,Object>()));
        Map sessionMap = new HashMap();
        Map contextMap = new HashMap();
        contextMap.put(ActionContext.SESSION, sessionMap);
        contextMap.put(PortletConstants.REQUEST, mockPortletReq.proxy());
        contextMap.put(PortletConstants.RESPONSE, mockPortletRes.proxy());
        contextMap.put(PortletConstants.PHASE, PortletPhase.RENDER_PHASE);
        contextMap.put(PortletConstants.MODE_NAMESPACE_MAP, modeMap);
        contextMap.put(PortletConstants.DEFAULT_ACTION_MAP, actionMap);
        contextMap.put(STRUTS_PORTLET_CONTEXT, mockCtx.proxy());

        ActionContext ctx = new ActionContext(contextMap);
        ctx.setValueStack(stack);
        ActionInvocation ai = (ActionInvocation)mockActionInvocation.proxy();
    	stack.getContext().put(ActionContext.ACTION_INVOCATION, ai);
        ActionContext.setContext(ctx);

    }

    public void testEnsureParamsAreStringArrays() {
        Map params = new HashMap();
        params.put("param1", "Test1");
        params.put("param2", new String[] { "Test2" });

        Map result = PortletUrlHelper.ensureParamsAreStringArrays(params);
        assertEquals(2, result.size());
        assertTrue(result.get("param1") instanceof String[]);
    }

    public void testSetWindowState() throws Exception {

        PortletMode mode = PortletMode.VIEW;

        mockHttpReq.stubs().method("getQueryString").will(returnValue(""));

        mockPortletRes.expects(once()).method("createRenderURL").will(
                returnValue(mockPortletUrl.proxy()));
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));

        Map paramMap = new HashMap();
        paramMap.put(PortletConstants.ACTION_PARAM, new String[]{"/view/testAction"});
        paramMap.put(PortletConstants.MODE_PARAM, new String[]{mode.toString()});

        mockPortletUrl.expects(once()).method("setParameters").with(new ParamMapConstraint(paramMap));
        mockPortletUrl.expects(once()).method("setWindowState").with(eq(WindowState.MAXIMIZED));
        mockPortletUrl.expects(once()).method("setPortletMode").with(eq(PortletMode.VIEW));

        tag.setAction("testAction");
        tag.setWindowState("maximized");
        tag.doStartTag();
        tag.doEndTag();

    }

    public void testSetPortletMode() throws Exception  {

        PortletMode mode = PortletMode.HELP;

        mockHttpReq.stubs().method("getQueryString").will(returnValue(""));

        mockPortletRes.expects(once()).method("createRenderURL").will(
                returnValue(mockPortletUrl.proxy()));
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));

        Map paramMap = new HashMap();
        paramMap.put(PortletConstants.ACTION_PARAM, new String[]{"/help/testAction"});
        paramMap.put(PortletConstants.MODE_PARAM, new String[]{mode.toString()});

        mockPortletUrl.expects(once()).method("setParameters").with(new ParamMapConstraint(paramMap));
        mockPortletUrl.expects(once()).method("setPortletMode").with(eq(PortletMode.HELP));
        mockPortletUrl.expects(once()).method("setWindowState").with(eq(WindowState.NORMAL));

        tag.setNamespace("/help");
        tag.setAction("testAction");
        tag.setPortletMode("help");
        tag.doStartTag();
        tag.doEndTag();
    }

    public void testWhenPortletModeDiffersFromCurrentAndNoParametersAreSetRenderTheDefaults()
    		 throws Exception {
        PortletMode mode = PortletMode.HELP;

        mockHttpReq.stubs().method("getQueryString").will(returnValue(""));

        mockPortletRes.expects(once()).method("createRenderURL").will(
                returnValue(mockPortletUrl.proxy()));
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));

        Map paramMap = new HashMap();
        paramMap.put(PortletConstants.ACTION_PARAM, new String[]{"/help/defaultHelp"});
        paramMap.put(PortletConstants.MODE_PARAM, new String[]{mode.toString()});

        mockPortletUrl.expects(once()).method("setParameters").with(new ParamMapConstraint(paramMap));
        mockPortletUrl.expects(once()).method("setPortletMode").with(eq(PortletMode.HELP));
        mockPortletUrl.expects(once()).method("setWindowState").with(eq(WindowState.NORMAL));

        tag.setPortletMode("help");
        tag.doStartTag();
        tag.doEndTag();
    }

    public void testUrlWithQueryParams() throws Exception {

        PortletMode mode = PortletMode.VIEW;

        mockHttpReq.stubs().method("getQueryString").will(returnValue(""));

        mockPortletRes.expects(once()).method("createRenderURL").will(
                returnValue(mockPortletUrl.proxy()));
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));

        Map paramMap = new HashMap();
        paramMap.put(PortletConstants.ACTION_PARAM, new String[]{"/view/testAction"});
        paramMap.put("testParam1", new String[]{"testValue1"});
        paramMap.put(PortletConstants.MODE_PARAM, new String[]{mode.toString()});

        mockPortletUrl.expects(once()).method("setParameters").with(new ParamMapConstraint(paramMap));
        mockPortletUrl.expects(once()).method("setPortletMode").with(eq(PortletMode.VIEW));
        mockPortletUrl.expects(once()).method("setWindowState").with(eq(WindowState.NORMAL));

        tag.setAction("testAction?testParam1=testValue1");
        tag.doStartTag();
        tag.doEndTag();
    }

    public void testActionUrl() throws Exception {

        PortletMode mode = PortletMode.VIEW;

        mockHttpReq.stubs().method("getQueryString").will(returnValue(""));

        mockPortletRes.expects(once()).method("createActionURL").will(
                returnValue(mockPortletUrl.proxy()));
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));

        Map paramMap = new HashMap();
        paramMap.put(PortletConstants.ACTION_PARAM, new String[]{"/view/testAction"});
        paramMap.put(PortletConstants.MODE_PARAM, new String[]{mode.toString()});

        mockPortletUrl.expects(once()).method("setParameters").with(new ParamMapConstraint(paramMap));
        mockPortletUrl.expects(once()).method("setPortletMode").with(eq(PortletMode.VIEW));
        mockPortletUrl.expects(once()).method("setWindowState").with(eq(WindowState.NORMAL));

        tag.setNamespace("/view");
        tag.setAction("testAction");
        tag.setPortletUrlType("action");
        tag.doStartTag();
        tag.doEndTag();
    }

    public void testResourceUrl() throws Exception {
        mockHttpReq.stubs().method("getQueryString").will(returnValue(""));
        mockPortletRes.expects(once()).method("encodeURL").will(returnValue("/contextPath/image.gif"));
        mockJspWriter.setExpectedData("/contextPath/image.gif");
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));
        tag.setValue("image.gif");
        tag.doStartTag();
        tag.doEndTag();
        mockJspWriter.verify();
    }

    public void testResourceUrlWithNestedParam() throws Exception {
        mockHttpReq.stubs().method("getQueryString").will(returnValue(""));
        mockPortletRes.expects(once()).method("encodeURL").with(eq("/contextPath/image.gif?testParam1=testValue1")).will(returnValue("/contextPath/image.gif?testParam1=testValue1"));
        mockJspWriter.setExpectedData("/contextPath/image.gif?testParam1=testValue1");
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));

        ParamTag paramTag = new ParamTag();
        paramTag.setPageContext((PageContext)mockPageCtx.proxy());
        paramTag.setParent(tag);
        paramTag.setName("testParam1");
        paramTag.setValue("'testValue1'");
        tag.setValue("image.gif");
        tag.doStartTag();
        paramTag.doStartTag();
        paramTag.doEndTag();
        tag.doEndTag();
        mockJspWriter.verify();
    }

    public void testResourceUrlWithTwoNestedParam() throws Exception {
        mockHttpReq.stubs().method("getQueryString").will(returnValue(""));
        mockPortletRes.expects(once()).method("encodeURL").with(eq("/contextPath/image.gif?testParam1=testValue1&testParam2=testValue2")).will(returnValue("/contextPath/image.gif?testParam1=testValue1&testParam2=testValue2"));
        mockJspWriter.setExpectedData("/contextPath/image.gif?testParam1=testValue1&testParam2=testValue2");
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));

        ParamTag paramTag = new ParamTag();
        paramTag.setPageContext((PageContext)mockPageCtx.proxy());
        paramTag.setParent(tag);
        paramTag.setName("testParam1");
        paramTag.setValue("'testValue1'");
        ParamTag paramTag2 = new ParamTag();
        paramTag2.setPageContext((PageContext)mockPageCtx.proxy());
        paramTag2.setParent(tag);
        paramTag2.setName("testParam2");
        paramTag2.setValue("'testValue2'");
        tag.setValue("image.gif");
        tag.doStartTag();
        paramTag.doStartTag();
        paramTag.doEndTag();
        paramTag2.doStartTag();
        paramTag2.doEndTag();
        tag.doEndTag();
        mockJspWriter.verify();
    }

    public void testUrlWithMethod() throws Exception {
    	PortletMode mode = PortletMode.VIEW;
    	mockHttpReq.stubs().method("getQueryString").will(returnValue(""));
        mockPortletRes.expects(once()).method("createRenderURL").will(
                returnValue(mockPortletUrl.proxy()));
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));
    	tag.setAction("testAction");
    	Map paramMap = new HashMap();
        paramMap.put(PortletConstants.ACTION_PARAM, new String[]{"/view/testAction!input"});
        paramMap.put(PortletConstants.MODE_PARAM, new String[]{mode.toString()});
        mockPortletUrl.expects(once()).method("setParameters").with(new ParamMapConstraint(paramMap));
        mockPortletUrl.expects(once()).method("setPortletMode").with(eq(PortletMode.VIEW));
        mockPortletUrl.expects(once()).method("setWindowState").with(eq(WindowState.NORMAL));
    	tag.setMethod("input");
    	tag.doStartTag();
    	tag.doEndTag();
    }

    public void testUrlWithNoActionOrMethod() throws Exception {
    	PortletMode mode = PortletMode.VIEW;
    	mockHttpReq.stubs().method("getQueryString").will(returnValue(""));
        mockPortletRes.expects(once()).method("createRenderURL").will(
                returnValue(mockPortletUrl.proxy()));
        mockCtx.expects(atLeastOnce()).method("getMajorVersion").will(returnValue(1));
    	Map paramMap = new HashMap();

    	mockActionProxy.stubs().method("getActionName").will(returnValue("currentExecutingAction"));

    	paramMap.put(PortletConstants.ACTION_PARAM, new String[]{"/view/currentExecutingAction"});
        paramMap.put(PortletConstants.MODE_PARAM, new String[]{mode.toString()});
        mockPortletUrl.expects(once()).method("setParameters").with(new ParamMapConstraint(paramMap));
        mockPortletUrl.expects(once()).method("setPortletMode").with(eq(PortletMode.VIEW));
        mockPortletUrl.expects(once()).method("setWindowState").with(eq(WindowState.NORMAL));
    	tag.doStartTag();
    	tag.doEndTag();
    }

    private static class ParamMapConstraint implements Constraint {

        private Map myExpectedMap = null;
        private Map myActualMap = null;

        public ParamMapConstraint(Map expectedMap) {
            if(expectedMap == null) {
                throw new IllegalArgumentException("Use an isNull constraint instead!");
            }
            myExpectedMap = expectedMap;
        }

        /* (non-Javadoc)
         * @see org.jmock.core.Constraint#eval(java.lang.Object)
         */
        public boolean eval(Object val) {
            myActualMap = (Map)val;
            boolean result = false;
            if(val != null) {
                if(myExpectedMap.size() == myActualMap.size()) {
                    Iterator keys = myExpectedMap.keySet().iterator();
                    boolean allSame = true;
                    while(keys.hasNext()) {
                        Object key = keys.next();
                        if(!myActualMap.containsKey(key)) {
                            allSame = false;
                            break;
                        }
                        else {
                            String[] expected = (String[])myExpectedMap.get(key);
                            String[] actual = (String[])myActualMap.get(key);
                            if(!Arrays.equals(expected, actual)) {
                                allSame = false;
                                break;
                            }
                        }
                    }
                    result = allSame;
                }
            }
            return result;
        }

        /* (non-Javadoc)
         * @see org.jmock.core.SelfDescribing#describeTo(java.lang.StringBuffer)
         */
        public StringBuffer describeTo(StringBuffer sb) {
        	sb.append("\n Expected: ");
        	describeTo(myExpectedMap, sb);
        	sb.append("\n Actual: ");
        	describeTo(myActualMap, sb);

            return sb;
        }

        private StringBuffer describeTo(Map map,StringBuffer sb) {
        	Iterator<String> it = map.keySet().iterator();
        	while(it.hasNext()) {
        		String key = it.next();
        		sb.append(key).append("=");
        		String[] value = (String[])map.get(key);
        		sb.append(value[0]);
        		if(it.hasNext()) {
        			sb.append(", ");
        		}
        	}
            return sb;
        }

    }

}


text:
package wikt.stat.printer;

import wikokit.base.wikt.constant.POS;
import wikt.stat.POSAndPolysemyTableAll.POSStat;

import java.util.Map;
import wikokit.base.wikipedia.language.LanguageType;

/** Statistics of parts of speech and polysemy of the parsed Wiktionary.
 *
 * The result could be inserted into the Wiktionary page.
 * @see http://ru.wiktionary.org/wiki/User:AKA MBG/Статистика:POS
 * @see http://wordnet.princeton.edu/wordnet/man/wnstats.7WN.html
 */
public class POSAndPolysemyPrinter {

    /** Prints
     * (1) statistics about parts of speech.
     * (2) names of POS in English (with templates) and in Russian (with templates).
     *
     * @param m_lang_rel_n map of maps with number of synonyms, antonyms, etc.
     * in English, Russian etc. (lang -> relations -> count)
     *
     * @param m_lang_entries_number number of (Language & POS level) entries per language
     */
    public static void printPOSWordsAndSensesTable (
                        LanguageType native_lang,
                        Map<POS,POSStat> m_lang_pos,
                        boolean print_templates_and_short_names)
    {
        if(null == m_lang_pos)
            return;

        System.out.println("{| class=\"sortable prettytable\" style=\"text-align: center;\"");
        System.out.print("! Unique Strings || Total Word-Sense Pairs || POS");

        if(LanguageType.en != native_lang)
            System.out.print(" || POS in " + native_lang.getName());

        if(print_templates_and_short_names)
            System.out.print(" || Short name || Templates");

        System.out.print(" || Max Senses || Entry");

        // print values
        for(POS pos : m_lang_pos.keySet()) {

            POSStat pos_stat = m_lang_pos.get(pos);// Map<POS,POSStat> m_lang_pos

            System.out.print("\n|-\n| " +
                    pos_stat.getNumberOfUniquesStrings() + " || " +
                    pos_stat.getNumberOfWordSensePairs() + " || " +
                    pos.toString());

            if(LanguageType.en != native_lang)
                System.out.print(" || " + pos.toString(native_lang));

            if(print_templates_and_short_names)
                System.out.print(" || " + pos.getShortName(native_lang) +
                                 " || " + pos.getTemplates(", ", native_lang));

            System.out.print(" || " + pos_stat.getMaxSenses() +
                             " || " + pos_stat.getWikifiedWordWithMaxSenses());
        }
        System.out.println("\n|}");
    }

     public static void printPOSPolysemyTable (
                            LanguageType native_lang,
                            Map<POS,POSStat> m_lang_pos)
    {
        System.out.println("{| class=\"sortable prettytable\" style=\"text-align: center;\"");
        System.out.print("! POS");

        if(LanguageType.en != native_lang)
            System.out.print(" || POS in " + native_lang.getName());

        System.out.print(" || Monosemous Words and Senses || Polysemous Words || Polysemous Senses");
        System.out.print(" || Average Polysemy Including Monosemous Words || Average Polysemy Excluding Monosemous Words");

        // print values
        for(POS pos : m_lang_pos.keySet()) {

            POSStat pos_stat = m_lang_pos.get(pos);// Map<POS,POSStat> m_lang_pos

            System.out.print("\n|-\n| " + pos.toString());

            if(LanguageType.en != native_lang)
                System.out.print(" || " + pos.toString(native_lang));

            System.out.print(   " || " + pos_stat.getMonosemous() +
                " || " + pos_stat.getPolysemousWords() +
                " || " + pos_stat.getPolysemousSenses() +
                " || " + System.out.format("%.2f", pos_stat.calcAveragePolysemyIncludingMonosemousWords()) + // + new PrintfFormat("%.2lg").sprintf(pos_stat.calcAveragePolysemyIncludingMonosemousWords()) +
                " || " + System.out.format("%.2f", pos_stat.calcAveragePolysemyExcludingMonosemousWords()));  //" || " + new PrintfFormat("%.2lg").sprintf(pos_stat.calcAveragePolysemyExcludingMonosemousWords()))
        }
        System.out.println("\n|}");
    }

     /**
      * @param m_lang_unknown_pos number of unknown POS for each language
      */
    public static void printPOS (
                        LanguageType native_lang,
                        LanguageType current_lang,
                        Map<LanguageType, Map<POS,POSStat>> map_lang_pos_all,
                        Map<LanguageType, Integer> m_lang_unknown_pos,
                        boolean print_templates_and_short_names)
    {
        Map<POS,POSStat> m_lang_pos = map_lang_pos_all.get(current_lang);
        if(null == m_lang_pos)
            return;

        if(null != m_lang_unknown_pos)
            System.out.println("\nNumber of words with unknown POS: " + m_lang_unknown_pos.get(current_lang));

        printPOSSensesAndPolysemy(native_lang, m_lang_pos, print_templates_and_short_names);
    }

    public static void printPOSSensesAndPolysemy (
                        LanguageType native_lang,
                        Map<POS,POSStat> m_lang_pos,
                        boolean print_templates_and_short_names)
    {
        if(null == m_lang_pos)
            return;

        // !print header line before this function
        System.out.println("\n=== Number of words and senses ===");

        int lang_pos_size = 0;
        if(null != m_lang_pos)
            lang_pos_size = m_lang_pos.size();

        System.out.println("\nRows in the table: " + lang_pos_size + "\n");
        printPOSWordsAndSensesTable(native_lang,
                                    m_lang_pos,
                                    print_templates_and_short_names);

        System.out.println("\n=== Polysemy information ===");
        System.out.println("\nRows in the table: " + m_lang_pos.size() + "\n");

        printPOSPolysemyTable ( native_lang,
                                m_lang_pos);
    }

    /** Maximum "number of relations" will be printed in the table:
     * (2) Number of words per number of relations
     * @see http://en.wiktionary.org/wiki/User:AKA_MBG/Statistics:Semantic_relations#Number_of_words_per_number_of_relations
     */
    //static final Integer max_relations_to_print = 50;

    /** Prints statistics-histogram about number of meanings in Wiktionary.
     *
     * @param max_values_to_print values histogram[0..max_values_to_print-1] will be printed
     * @param total_histogram with total number of meanings for all languages
     * @param m_lang_histogram number of meanings for each language
     * @param m_lang_unknown_pos number of unknown parts of speech for each language
     */
    public static void printHistogramPerlanguage (int[] total_histogram, int max_values_to_print,
            Map<LanguageType, Integer[]> m_lang_histogram) {

        // maximum number of meanings [0..max] to be printed in the table
        // max := first non-zero value in total_histogram[] from the end of array
        int max = Math.min(total_histogram.length, max_values_to_print);
        for(int i=max-1; i>=0; i--) {
            if(0 != total_histogram[i]) {
                max = i;
                break;
            }
        }
        if (0 == max)
            return;

        // print header line
        System.out.println("\n=== Number of words having different number of meanings / definitions ===\n");

        System.out.println("Table description:");
        System.out.println("* column 0 - number of words with empty definitions (total and for each language)");
        System.out.println("* column 1 - number of monosemous words (total and for each language)");
        System.out.println("* column 2 - number of words with two meanings, etc.");
        System.out.println("* last column (\"Total\") - total number of words for this language.");

        System.out.println("\nOnly the first " + max + " meanings (columns) are presented in the table.");

        System.out.println("{| class=\"sortable prettytable\" style=\"text-align: center;\"");

        System.out.print("! || Number of meanings: ");
        for(int i=0; i<=max; i++)
            System.out.print("||" + i);
        System.out.print("||Total");

        // System.out.print("\n|-");
        // System.out.print("\n! Language name || Language code || colspan=\""+(max+2)+"\"|  ");
        System.out.print("\n|-");
        System.out.print("\n! code || Total (all languages) :");
        int cur_total = 0;
        for(int i=0; i<=max; i++) {
            System.out.print("||" + total_histogram[i]);
            cur_total += total_histogram[i];
        }
        System.out.print("||" + cur_total);

        for(LanguageType lang : m_lang_histogram.keySet()) {
            System.out.println("\n|-\n! " + lang.getCode() + " || " + lang.getName());

            cur_total = 0;
            Integer[] h = m_lang_histogram.get(lang);
            for(int i=0; i<=max; i++) {
                System.out.print("||" + h[i]);
                cur_total += h[i];
            }
            System.out.print("||" + cur_total);
        }

        // Total (all languages)

        System.out.println("\n|}");

    }
}

redpajama_set_name: RedPajamaGithub


text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide utilities to allow configuration of values for BCE.
//
//@CLASSES:
//  bslmt::Configuration: namespace for utilities managing default BCE values
//
//@SEE_ALSO: bslmt_threadattributes, bslmt_threadutil
//
//@DESCRIPTION: This component defines a utility 'struct',
// 'bslmt::Configuration', that is a name space for pure functions used for
// providing access to, and configuring, default values for BCE-relevant
// parameters.  The 'bslmt::Configuration' utility currently provides static
// methods to access and modify the BCE library's default stack size, as well
// as functions that access the platform's native default stack size and guard
// size.  The BCE default stack size is initially configured to
// 'bslmt::ThreadAttributes::BSLMT_UNSET_STACK_SIZE', in which case thread
// creation is to use the native default thread stack size.
//
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Demonstrate Accessing & Modifying the Default Thread Stack Size
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// In this example we demonstrate how to access both the platform's native and
// BCE configured default stack sizes, and then to set the default stack size
// used by BCE.  Note that the value returned by 'defaultThreadStackSize' may
// be adjusted from that provided by the underlying operating system to reflect
// the actual amount of stack memory available to a created thread.  Note that
// operations creating a thread should perform a similar inverse adjustment
// when configuring the new thread's stack size (see 'bslmt_threadutil').
//
// First, we examine the platform's native thread stack size:
//..
//  const int nativeDefault =
//                        bslmt::Configuration::nativeDefaultThreadStackSize();
//
//  assert(nativeDefault > 0);
//..
// Then, we verify that 'defaultThreadStackSize' is unset.
//..
//  assert(bslmt::ThreadAttributes::e_UNSET_STACK_SIZE ==
//                             bslmt::Configuration::defaultThreadStackSize());
//..
// Next, we define 'newDefaultStackSize' to some size other than the platform's
// native default stack size:
//..
//  const int newDefaultStackSize = nativeDefault * 2;
//..
// Now, we set the default size for BCE to the new size:
//..
//  bslmt::Configuration::setDefaultThreadStackSize(newDefaultStackSize);
//..
// Finally, we verify that BCE's default thread stack size has been set to the
// value we specified:
//..
//  assert(bslmt::Configuration::defaultThreadStackSize() ==
//                                                        newDefaultStackSize);
//  assert(bslmt::Configuration::defaultThreadStackSize() != nativeDefault);
//..

#include <bslscm_version.h>

namespace BloombergLP {
namespace bslmt {

                           // ====================
                           // struct Configuration
                           // ====================

struct Configuration {
    // This 'struct' provides a namespace for a suite of functions that are
    // used to manage the configuration of default values used in 'bslmt'.
    // Specifically, these functions manage the default value of thread stack
    // size and provide access to the platform's native guard size, but may be
    // extended to govern more traits in the future.

    // CLASS METHODS
    static int defaultThreadStackSize();
        // Return the value set by the last call to
        // 'setDefaultThreadStackSize'; if 'setDefaultThreadStackSize' has
        // never been called, return 'ThreadAttributes::BSLMT_UNSET_STACK_SIZE'
        // which will signal thread creation to use the thread stack size
        // native to the platform.

    static int nativeDefaultThreadStackSize();
        // Return the "native" default thread stack size (in bytes) as
        // determined by the underlying platform.  Note that this value may be
        // influenced by the choice of platform, environment variables,
        // compiler/linker options, or shell configuration, and typically
        // varies wildly among different platforms.

    static int nativeDefaultThreadGuardSize();
        // Return the default thread stack guard size (in bytes) determined by
        // the underlying platform.  Note that this value reflects semantics,
        // and may be influenced by the choice of platform, environment
        // variables, compiler/linker options, or shell configuration, and may
        // vary somewhat among different platforms.

    static int recommendedDefaultThreadStackSize();
        // Return a "reasonable" value for the default thread stack size (in
        // bytes), which, unlike 'nativeDefaultThreadStackSize', is constant
        // across all platforms of a given word size.  This value is large
        // enough to guarantee that an automatic array of at least 250 * 1024
        // pointers may be declared in the top level routine of the thread.

    static void setDefaultThreadStackSize(int numBytes);
        // Set the default thread stack size to the specified 'numBytes'.  If a
        // minimum thread stack size is known for the underlying platform (i.e.
        // 'PTHREAD_STACK_MIN' is defined) and 'numBytes' is below that
        // minimum, the stack size will be that minimum.  The behavior is
        // undefined unless '0 <= numBytes'.
};

}  // close package namespace
}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
guice-ext
=========
a guice ext for auto bind and install module

annotation-detector:https://github.com/rmuller/infomas-asl

reflect:https://github.com/jOOQ/jOOR

logging:https://github.com/netty/netty/tree/master/common/src/main/java/io/netty/util/internal/logging

=========
1.``@AutoBind`` , ``@Named``
````
@AutoBind
@Named("mysql")
public class MysqlBaseDAOImpl implements BaseDAO{
	....
}

@AutoBind
@Named("oracle")
public class OracleBaseDAOImpl implements BaseDAO{
	....
}

````
if you don't want to bind class use ``@NoBind``.

2.inject use
````
public class BaseServiceImpl implements BaseService{
	@Inject
	@Named("mysql")
	private BaseDAO mysqlDAO;

	@Inject
	@Named("oracle")
	private BaseDAO oracleDAO;

	public void test(){
		mysqlDAO.test();
		oracleDAO.test();
	}
}
````
3.``@GuiceModule``
````
@GuiceModule
public class ExampleModule extends AbstractModule {

	@Override
	protected void configure() {
		bind(ExampleDAO.class).to(ExampleDAOImpl.class);
		//or other things
	}
}
````
4.guice init
````
install(new AutoBindModule());
install(new AutoInstallModule());
````

0.0.1 :https://github.com/fivesmallq/guice-ext/releases/download/0.1/guice-ext-0.0.1-SNAPSHOT.jar


text:
define(function () {
    return {
        BAR: 'Static Bar',
        BUBBLE: 'Global Notification Bubbles',
        OBJECT: 'Notification Bubbles for Each Form Field',
        DYNAMIC_DOM: 'Dynamic Notification Bar'
    };
});


text:
//-----------------------------------------------------------------------------
// PhotoTree.java
//
// A simple example of displaying Swing ImageIcons in a JTree.
//
// This example shows how to override the renderer in a tree, so
// you can show your own type of nodes.
//
// It also shows how you can create tree nodes of any type by
// implementing the DefaultMutableTreeNode interface.
//
// This program requires:
//    Java JDK level 1.1.0 or higher.
//    Swing version 0.8 or higher.
//
// Demonstrates use of these classes/interfaces:
//    com.sun.java.swing.JFrame
//    com.sun.java.swing.JTree
//    com.sun.java.swing.tree.TreeNode
//    com.sun.java.swing.DefaultMutableTreeNode
//    com.sun.java.swing.plaf.basic.BasicTreeCellRenderer;
//    com.sun.java.swing.JLabel
//    com.sun.java.swing.JScrollPane
//    com.sun.java.swing.ImageIcon
//
// Authors:
//    Kelvin R Lawrence
//    Dan O. Becker
//
// History:
//    13-Jan-1998 -KRL-  Created example based on JFCTrees
//    28-Mar-1998 -DOB-  Updated to use ImageIcons and images.
//
//-----------------------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import java.util.Enumeration;
import com.sun.java.swing.*;
import com.sun.java.swing.event.* ;
import com.sun.java.swing.tree.*;
import com.sun.java.swing.plaf.basic.*;

/**
 * PhotoTree
 *

 * A simple example of displaying Swing ImageIcons in a JTree.
 *

 * This example shows how to override the renderer in a tree, so
 * you can show your own type of nodes.
 *

 * It also shows how you can create tree nodes of any type by
 * implementing the DefaultMutableTreeNode interface.
 *
 * @author  Dan O. Becker
 * @version 28Mar1998
 */
public class PhotoTree extends JFrame
{
   //-------------------------------------------------------------------------
   // Constants
   // Immutable objects for this class
   //-------------------------------------------------------------------------

   //--------------------------------------------------------------------
   // main()
   // The entry point into the program.
   //--------------------------------------------------------------------
   public static void main( String [] args ) {
      // Construct a frame with the given title
      PhotoTree frame = new PhotoTree( "Photo Tree", args );

      // Add anonymous class to handle window exiting.
      frame.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent event ) { System.exit( 0 ); }
         }
      );

      // Center and show on SVGA screens.
      frame.setBounds( 50, 50, 700, 500 );
      frame.show();
   }

   //-------------------------------------------------------------------------
   // Constructors
   // Create instances of this class
   //-------------------------------------------------------------------------
   public PhotoTree( String s, String [] args )
   {
      // Initialize frame with given title.
      super(s);

      if ( args.length == 0 ) {
         System.out.println( "Provide command line arguments for additional photos for the tree. For example:" );
         System.out.println( "    java PhotoTree ../../images/harriet.jpg ../../images/swimming.jpg" );
      } /* endif */

      // Remember content pane for future use. Default layout is BorderLayout.
      content = getContentPane();

      // Add a root node for the tree.
      DefaultMutableTreeNode top = new DefaultMutableTreeNode( "Photos" );

      // Add a few default branches in the tree.
      DefaultMutableTreeNode graphics = new DefaultMutableTreeNode( "Graphics" );
      top.add( graphics );
      graphics.add( new PhotoTreeNode( "../../images/javalogo.gif" ) );
      graphics.add( new PhotoTreeNode( "../../images/olympic.gif" ) );
      DefaultMutableTreeNode dogs = new DefaultMutableTreeNode( "Dog Pictures" );
      top.add( dogs );
      dogs.add( new PhotoTreeNode( "../../images/harriet.jpg" ) );
      dogs.add( new PhotoTreeNode( "../../images/swimming.jpg" ) );
      DefaultMutableTreeNode planes = new DefaultMutableTreeNode( "Plane Pictures" );
      top.add( planes );
      planes.add( new PhotoTreeNode( "../../images/737-500.gif" ) );
      DefaultMutableTreeNode others = new DefaultMutableTreeNode( "Other Pictures" );
      top.add( others );

      // Fetch images for each command line argument.
      for ( int i = 0; i < args.length; i++ )
         others.add( new PhotoTreeNode( args[ i ] ));

      // Instantiate the tree and add it to this frame.
      JTree tree = new JTree( top );
      // System.out.println( "Default tree cell renderer=" + tree.getCellRenderer() );
      // Change the tree cell renderer so we can draw images.
      tree.setCellRenderer( new ExtendedTreeCellRenderer() );
      content.add( "Center", new JScrollPane( tree ) );
   }

   //-------------------------------------------------------------------------
   // PhotoTreeNode
   // A node for a JTree that extends a JLabel so that is can show
   // a text or an image label.
   // This node does not support children and only can be used as a leaf.
   //-------------------------------------------------------------------------
   public class PhotoTreeNode implements MutableTreeNode {
      //-------------------------------------------------------------------------
      // Constants
      // Immutable objects for this class
      //-------------------------------------------------------------------------
      public final IllegalArgumentException noKids =
         new IllegalArgumentException( "A PhotoTreeNode does not support children." );

      //-------------------------------------------------------------------------
      // Constructors
      // Create instances of this class
      //-------------------------------------------------------------------------
      public PhotoTreeNode( String fileName ) {
         // Create the view of the image.
         ImageIcon image = new ImageIcon( fileName );
         if (( image.getIconWidth() > 0 ) && ( image.getIconHeight() > 0 ))
            nodeView = new JLabel( image );
         else
            System.out.println( "Got a bad image for argument \"" + fileName + "\"." );
      }

      //-------------------------------------------------------------------------
      // TreeNode role
      // Since a PhotoTreeNode supports no children, many methods simply throw
      // an exception, and others simply return legal default values.
      //-------------------------------------------------------------------------
      public TreeNode getChildAt( int childIndex ) { throw noKids; }
      public int getChildCount() { return 0; }
      public int getIndex(TreeNode node) { return -1; }
      public Enumeration children() { throw noKids; }
      public boolean getAllowsChildren() { return false; }
      public boolean isLeaf() { return true; }
      public TreeNode getParent() { return parent; }

      //-------------------------------------------------------------------------
      // MutableTreeNode role
      // Since a PhotoTreeNode supports no children, many methods simply throw
      // an exception, and others simply return legal default values.
      //-------------------------------------------------------------------------
      public void insert( MutableTreeNode child, int index ) { throw noKids; }
      public void remove( int index ) { throw noKids; }
      public void remove( MutableTreeNode node ){ throw noKids; }
      public void setUserObject( Object object ) {}
      public void removeFromParent() {}
      public void setParent( MutableTreeNode newParent ) { this.parent = newParent; }
      // Not part of Mutable tree node, but it seems needed.
      public Object getUserObject( ) {
         System.out.println( "getUseObject called" );
         return nodeView;
      }

      public MutableTreeNode parent;
      public JLabel nodeView;
   }

   //-------------------------------------------------------------------------
   // ExtendedTreeCellRenderer
   // This renderer extends the capabilities of the BasicTreeCellRenderer.
   // Normally the renderer displays a default icon for the tree node.
   // Here, we look if the tree node supports photos and, if yes, return that.
   //-------------------------------------------------------------------------
   public class ExtendedTreeCellRenderer extends BasicTreeCellRenderer implements TreeCellRenderer {
      //-------------------------------------------------------------------------
      // TreeCellRenderer role
      // This is the call that actually draws the tree cell.
      //-------------------------------------------------------------------------
      public Component getTreeCellRendererComponent(
         JTree tree, Object value,
         boolean selected, boolean expanded,
         boolean leaf, int row, boolean hasFocus ) {

         // If this is a photo node, render it with the photo.
         if ( value instanceof PhotoTreeNode )
            return ((PhotoTreeNode)value).nodeView;

         // Otherwise, render the  node with the default tree renderer.
         return super.getTreeCellRendererComponent(
            tree, value, selected, expanded, leaf, row, hasFocus );
      }
  }

   //-------------------------------------------------------------------------
   // Fields
   // Objects that describe the state and information of this object.
   //-------------------------------------------------------------------------
   private Container content;
   private JTree tree;
}


text:
package com.r0adkll.slidr.example;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ftinc.kit.util.SizeUtils;
import com.ftinc.kit.util.Utils;
import com.ftinc.kit.widget.AspectRatioImageView;
import com.r0adkll.slidr.Slidr;
import com.r0adkll.slidr.example.model.AndroidOS;
import com.r0adkll.slidr.model.SlidrConfig;
import com.r0adkll.slidr.model.SlidrPosition;

import butterknife.ButterKnife;
import butterknife.BindView;
import butterknife.OnClick;

public class ViewerActivity extends AppCompatActivity {

    public static final String EXTRA_OS = "extra_os_version";

    @BindView(R.id.toolbar) Toolbar mToolbar;
    @BindView(R.id.cover) AspectRatioImageView mCover;
    @BindView(R.id.title) TextView mTitle;
    @BindView(R.id.description) TextView mDescription;
    @BindView(R.id.date) TextView mDate;
    @BindView(R.id.version) TextView mVersion;
    @BindView(R.id.sdk) TextView mSdk;
    @BindView(R.id.position) TextView mPosition;

    private AndroidOS mOS;
    private SlidrConfig mConfig;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewer);
        ButterKnife.bind(this);

        // Get the status bar colors to interpolate between
        int primary = getResources().getColor(R.color.primaryDark);
        int secondary = getResources().getColor(R.color.red_500);

        // Build the slidr config
        int numPositions = SlidrPosition.values().length;
        SlidrPosition position = SlidrPosition.values()[Utils.getRandom().nextInt(numPositions)];
        mPosition.setText(position.name());

        mConfig = new SlidrConfig.Builder()
                .primaryColor(primary)
                .secondaryColor(secondary)
                .position(SlidrPosition.VERTICAL)
                .velocityThreshold(2400)
//                .distanceThreshold(.25f)
//                .edge(true)
                .touchSize(SizeUtils.dpToPx(this, 32))
                .build();

        // Attach the Slidr Mechanism to this activity
        Slidr.attach(this, mConfig);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mOS = getIntent().getParcelableExtra(EXTRA_OS);
        if(savedInstanceState != null) mOS = savedInstanceState.getParcelable(EXTRA_OS);

        // Set layout contents
        mTitle.setText(mOS.name);
        mDescription.setText(mOS.description);
        mDate.setText(String.valueOf(mOS.year));
        mVersion.setText(mOS.version);
        mSdk.setText(String.valueOf(mOS.sdk_int));

        // Load header image
        Glide.with(this)
                .load(mOS.image_url)
                .crossFade()
                .into(mCover);
    }

    @OnClick({R.id.color1, R.id.color2, R.id.color3, R.id.color4, R.id.color5})
    void onColorClicked(View v){
        int color = ((ColorDrawable)v.getBackground()).getColor();
        getWindow().setStatusBarColor(color);
        mConfig.setColorSecondary(color);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(EXTRA_OS, mOS);
    }
}