text:
/* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
  padding-top: 70px;
  padding-bottom: 30px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
  text-align: center;
}

/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */

body > .container {
  padding: 60px 15px 0;
}
.container .text-muted {
  margin: 20px 0;
}

.footer > .container {
  padding-right: 15px;
  padding-left: 15px;
}

code {
  font-size: 80%;
}

th {
    cursor: pointer;
}

th.selected {
    background-color: #D8D8D8;
}

.circle20 {
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: inline-block;
}

.circle20.red {
    background: red;
}

.circle20.green {
    background: green;
}

.circle20.yellow {
    background: yellow;
}

.circle20.blue {
    background: blue;
}


text:
float g_smart_cover_animation_speed_factor = 1.f;

using smart_cover::animation_selector;
using smart_cover::action_base;
using smart_cover::wait_after_exit;

animation_selector::animation_selector(CAI_Stalker* object)
    : m_object(object), m_callback_called(false), m_first_time(true), m_previous_time(flt_max) {
    m_skeleton_animated = smart_cast<IKinematicsAnimated*>(object->Visual());
    VERIFY(m_skeleton_animated);
    m_planner = xr_new<animation_planner>(object, "animation planner");
}

animation_selector::~animation_selector() { xr_delete(m_planner); }

void animation_selector::initialize() {
    m_planner->initialize();

    // we need this, since we could change bone callbacks
    // which needs animation blends
    // but blends are not accessible since
    // we didn't called animation().update()
    // which is called on UpdateCL
    // and in case of RayQuery
    // our bone callback could be called
    // but UpdateCL is not called yet
    // and we will have
    // VERIFY	(*parameter->m_blend);
    m_callback_called = true;
    m_object->animation().update();

    m_first_time = true;
}

void animation_selector::finalize() {
    if (!m_planner->initialized())
        return;

    m_planner->finalize();
}

action_base* animation_selector::current_operator() const {
    return (&smart_cast<smart_cover::action_base&>(m_planner->current_action()));
}

MotionID animation_selector::select_animation(bool& animation_movement_controller) {
    animation_movement_controller = true;

    if (m_callback_called) {
        if (m_planner->initialized()) {
            current_operator()->on_animation_end();
            m_callback_called = false;

            m_previous_time = 0.f;
            if (!m_planner->initialized()) {
                //				Msg				("%6d no planner update,
                //planner is not initialized, exiting", Device.dwTimeGlobal);
                return (
                    m_object->animation().assign_global_animation(animation_movement_controller));
            }
        }

        //		Msg					("%6d updating planner",
        //Device.dwTimeGlobal);
        m_planner->update();

        if (!m_planner->initialized()) {
            //			Msg				("%6d planner is not initialized after update, exiting",
            //Device.dwTimeGlobal);
            return (m_object->animation().assign_global_animation(animation_movement_controller));
        }

        current_operator()->on_no_mark();
        if (!current_operator()->is_animated_action())
            return (m_object->animation().assign_global_animation(animation_movement_controller));

        current_operator()->select_animation(m_animation);

        VERIFY(m_object->movement().current_params().cover());
        if (!m_object->movement().current_params().cover()->can_fire())
            return (m_skeleton_animated->ID_Cycle(m_animation.c_str()));

#if 0  // ndef MASTER_GOLD
		if (!psAI_Flags.test((u32)aiUseSmartCoversAnimationSlot))
			return			(m_skeleton_animated->ID_Cycle( m_animation.c_str()));

		VERIFY				( m_object->inventory().ActiveItem() );
		CHudItem* const		hud_item = smart_cast<CHudItem*>(m_object->inventory().ActiveItem());
		VERIFY				( hud_item );

		string16			animation_slot_string;
		R_ASSERT			( !_itoa_s( hud_item->animation_slot(), animation_slot_string, sizeof(animation_slot_string), 10 ) );

		LPSTR				result;
		STRCONCAT			( result, m_animation, "_slot_", animation_slot_string);

		MotionID			animation_id = m_skeleton_animated->ID_Cycle_Safe( result );
		if (animation_id)
			return			(animation_id);

		STRCONCAT			( result, m_animation, "_slot_2" );
		animation_id		= m_skeleton_animated->ID_Cycle_Safe( result );
		VERIFY				(animation_id);
		return				(animation_id);
#else  // #ifndef MASTER_GOLD
        return (m_skeleton_animated->ID_Cycle(m_animation.c_str()));
#endif // #ifndef MASTER_GOLD
    }

    VERIFY(m_animation._get());
    //	VERIFY				(m_first_time || m_object->animation().global().blend());
    MotionID result = m_skeleton_animated->ID_Cycle(m_animation.c_str());
    if (m_first_time) {
        m_first_time = false;
        m_previous_time = 0.f;
        current_operator()->on_no_mark();
        return (result);
    }

    CBlend const* const blend = m_object->animation().global().blend();
    if (!blend) {
        m_previous_time = 0.f;
        current_operator()->on_no_mark();
        return (result);
    }

    VERIFY(blend->motionID == result);
    CMotionDef* motion_def = m_skeleton_animated->LL_GetMotionDef(result);

    typedef xr_vector<motion_marks> Marks;
    Marks const& marks = motion_def->marks;
    if (marks.size() < 3) {
        current_operator()->on_no_mark();
        return (result);
    }

    float previous_time = m_previous_time;
    float time_current = blend->timeCurrent + .1f;
    m_previous_time = time_current;
    // Slipch told me, that timeCurrent can decrease (setup to 0.f) during animation playing
    // therefore we need here to clamp previous value
    clamp(previous_time, 0.f, time_current);
    // first 2 should be footsteps
    if (!marks[2].is_mark_between(previous_time, time_current)) {
        current_operator()->on_no_mark();
        return (result);
    }

    //	Msg					( "%d on_mark", Device.dwTimeGlobal );
    current_operator()->on_mark();
    return (result);
}

void animation_selector::on_animation_end() {
    VERIFY(!m_callback_called);
    m_callback_called = true;
}

void animation_selector::modify_animation(CBlend* blend) {
    if (!blend)
        return;

    CMotionDef* motion_def = m_skeleton_animated->LL_GetMotionDef(blend->motionID);
    VERIFY(motion_def);
    blend->speed = motion_def->Speed() * g_smart_cover_animation_speed_factor;
}

void animation_selector::save(NET_Packet& packet) { m_planner->save(packet); }

void animation_selector::load(IReader& packet) { m_planner->load(packet); }

void animation_selector::setup(CAI_Stalker* object, CPropertyStorage* storage) {
    m_planner->setup(object, storage);
}

redpajama_set_name: RedPajamaGithub


text:
package cms

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// SlsParameters is a nested struct in cms response
type SlsParameters struct {
	SlsParameter []SlsParameter `json:"SlsParameter" xml:"SlsParameter"`
}


text:
"""
@todo: Refactor data, name, aliases
    --> name: getter, setter, deleter
    --> aliases: getter, setter, deleter
    --> data: getter only - returning [name] + aliases
    @todo: Requires changing the way validation determines whether to
        extract name from 'data'. I will have to carefully think about this case:
            state.data = ['attempting', 'attempt', 'attempted']
            #? Should this change the name? IE be the same as:
            state = EnumGroup(['attempting', 'attempt', 'attempted'])
        --YES--  hence,
        self.data = ['a','b','c']
            ==
        self.name, self.aliases = self._validate(data, name=name)
    @todo: EnumGroupInterface: self._validate_name, self._validate_aliases
        Difference between _validate(data, name=None) and _validate_data(data)
            is _validate_data *assumes* it will pop off the front to make a name
        _validate(data, name=None)
        _validate_data(data)
        _validate_aliases(aliases)
        _validate_name(name)

@todo: Allow EnumGroup __init__ to accept *args, **kwargs:
    EnumGroup('attempting', 'attempt', 'attempted')
@todo: Consider making (optional) hooks from EnumGroup back to it's parent.
    So each group would know it's .parent, and .index
@todo: Make EnumGroup count as child of it's parent somehow (to isinstance?)

------ Future: --------
@todo: RegexEnum() + RegexEnumGroup()
@todo: support 'simplify'ing functions (like str.lower()), via a callback mechanism.
    --> SmartEnum()/TransformEnum()
    Should maintain a list of callbacks that it applies before comparison.
    Will have to apply the callbacks on the 'name' and 'aliases' after updating callback list.
    @todo: Implement this via: self._keytransform(key) - used only inside
        __getitem__, __setitem__, __delitem__ (and maybe whatever sets the initial data)

Hard issue:
    I would like States['attempting'] to be valid syntax.
    But... this gets complicated because what if the name or alias
        for a group is an integer?
    (actually, this is a similar issue to atlas's)
    SOLUTION: (inelegant, but workable)
        (1) if isinstance(key, int):
            index = key
        (2) else:
            index =
            #check alias
        (3) throw error if a name is ever an integer
"""

import collections
from abc import ABCMeta, abstractproperty, abstractmethod
#----
from local_packages import rich_collections
from local_packages import rich_core

#==============================================================================
#        Interfaces
#==============================================================================

class EnumInterface(collections.MutableSequence):
    __metaclass__ = ABCMeta

    groups = abstractproperty(lambda self: NotImplemented)
    names = abstractproperty(lambda self: NotImplemented)
    aliases = abstractproperty(lambda self: NotImplemented)

    _find_group = abstractmethod(lambda self, alias: NotImplemented) #returns EnumGroup()
    group = abstractmethod(lambda self, alias: NotImplemented) #returns EnumGroup(). Same as _find_group
    _find_all = abstractmethod(lambda self, alias: NotImplemented) #yields EnumGroup()
    index = abstractmethod(lambda self, alias: NotImplemented) #returns integer

    _make_group = abstractmethod(lambda self, data, name=None: NotImplemented) #constructor for groups

    keys = abstractmethod(lambda: NotImplemented)
    values = abstractmethod(lambda: NotImplemented)

class EnumGroupInterface(collections.Sequence):
    """
    Complication:
    self.data: returns self.name + self.alias
    self.alias: is stored in self._data (because of inheritance from BasicMutableSequence)

    @todo: Refactor data, name, aliases
        --> name: getter, setter, deleter
        --> aliases: getter, setter, deleter
        --> data: getter only - returning [name] + aliases

    """
    __metaclass__ = ABCMeta
    name = abstractproperty(lambda: NotImplemented)
    __eq__ = abstractmethod(lambda: NotImplemented)

    #--- Name property and validation
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self, value):
        self._name = self._validate_name(value)
    @name.deleter
    def name(self):
        del self._name
    def _validate_name(self, value):
        if isinstance(value, int):
            raise TypeError(str.format(
                "{0} 'name' cannot be an integer, because it conflicts with Sequence indexes.",
                self.__class__.__name__
            ))
        return value
    #--- Aliases property and validation
    aliases = abstractproperty(lambda self: NotImplemented)
    #--- Data property and validation
    data = abstractproperty(lambda self: NotImplemented)

#==============================================================================
#        Concrete Classes
#==============================================================================

class Enum(EnumInterface, rich_collections.BasicMutableSequence):
    """
    A sequence of EnumGroups.

    Potentially complicated 'corner-case' error:
        If name of a group is an integer
        Since that integer could also be the index of a different group

    @todo: Consider moving the group validiation from EnumGroup._validate()
        into here (Enum._validate_group())
    """
    def __init__(self, data):
        self.data = self._validate(data)

    def _validate(self, data):
        """
        """
        rich_core.AssertKlass(data,
            (rich_core.NonStringSequence, collections.Mapping), name='data'
        )
        if isinstance(data, collections.Mapping):
            return [
                self._validate_group(group, name=name)
                for name, group in data.items()
            ]
        elif isinstance(data, rich_core.NonStringSequence):
            return [
                self._validate_group(group)
                for group in data
            ]
        else:
            raise TypeError("Switch error on type of 'data' ({0}).".format(type(data)))
    def _validate_group(self, group, name=None):
        """Ensure sequence is a valid group."""
        return self._make_group(group, name=name)

    def _make_group(self, data, name=None):
        """Constructor for a single group."""
        return EnumGroup(data, name=name)
    @property
    def groups(self):
        """Alias to self.data property."""
        return self.data
    @groups.setter
    def groups(self, value):
        """Alias to self.data property setter."""
        self.data = value
    @groups.deleter
    def groups(self):
        """Alias to self.data property deleter."""
        del self.data
    @property
    def names(self):
        return [group.name for group in self]
    @property
    def aliases(self):
        return [group.aliases for group in self]
    #--------------------------------------------------------------------------
    #        Problematic Item Getter/Setter functions
    #--------------------------------------------------------------------------
    #__getitem__, __setitem__, __delitem__
    #... these are best (partly) resolved, by first, resolving keys/aliases to
    #an index number, then calling the normal __getitem__ functions. Example:
    #def __getitem__(self, key):
    #    index = self.index(key)
    #    return self.data[index]

    def _resolve_index(self, key):
        if isinstance(key, int):
            return key
        else:
            return self.index(key)
    def __getitem__(self, key):
        return self.data[self._resolve_index(key)]
    def __setitem__(self, key, value):
        self.data[self._resolve_index(key)]
    def __delitem__(self, key):
        self.data[self._resolve_index(key)]

    def _find_group(self, alias):
        """Find first group matching alias.
        Primarily, this matches on name, but allows for the
        possibility of groups which accept alternatives."""
        return self._find_all(alias).next()
    def _find_all(self, alias):
        """Find all groups matching alias. Iterator."""
        for group in self:
            if alias in group:
                yield group
    def group(self, alias):
        """Find first group matching alias (~name)."""
        return self._find_group(alias)
    def keys(self):
        return self.names
    def values(self):
        return [elm for group in self.groups for elm in group]
    def items(self):
        return [(group.name, group.aliases) for group in self.groups]
    def index(self, alias):
        """Find index for alias."""
        for i, group in enumerate(self):
            if alias in group:
                return i
        raise ValueError("alias not contained in any group.")
    def __eq__(self, other):
        return (self.groups == other)

class EnumGroup(rich_collections.BasicMutableSequence, EnumGroupInterface):
    """

    Organization of data, names, aliases is confusing:

    @todo: Refactor data, name, aliases
        --> name: getter, setter, deleter
        --> aliases: getter, setter, deleter
        --> data: getter only - returning [name] + aliases
        @todo: Requires changing the way validation determines whether to
            extract name from 'data'. I will have to carefully think about this case:
                state.data = ['attempting', 'attempt', 'attempted']
                #? Should this change the name? IE be the same as:
                state = EnumGroup(['attempting', 'attempt', 'attempted'])
            --YES--  hence,
            self.data = ['a','b','c']
                ==
            self.name, self.aliases = self._validate(data, name=name)

    """
    def __init__(self, data, name=None):
        """Initialize groups contained in
        If name == None, then first entry of data is used as name.
        """
        #self.name, self.aliases = self._validate(data, name=name)
        self.name, self.data = self._validate(data, name=name)

    def _validate(self, data, name=None):
        data = _ensure_list(data)
        rich_core.AssertKlass(data, collections.MutableSequence, name='data')

        # If name misisng, using the first entry in data
        if name == None:
            assert(len(data) > 0), "If 'name' not provided, data must be non-empty."
            name = data.pop(0)
        else:
            name = name

        # If name exists in data, remove it.
        try:
            data.pop(data.index(name))
        except ValueError:
            pass

        return name, data

    def _validate_data(self, data, name=None):
        """
        Difference between _validate(data, name=None) and _validate_data(data)
            is _validate_data *assumes* it will pop off the front to make a name
        """
        #[] Process name - if not provided, extract from data
        #[] Assign remaining to aliases
        return self._validate_name(name), self._validate_aliases(aliases)

    #Special case for delitem: if length == 1, ie consists only of name
    @property
    def data(self):
        return [self._name] + self._data
    @data.setter
    def data(self, value):
        self._data = value
    @data.deleter
    def data(self):
        del self._data
    @property
    def aliases(self):
        return self._data

class BasicEnumGroup(EnumGroupInterface, rich_collections.BasicSequence):
    """Very simple. Only consists of name."""
    #def __init__(self, data, name=None):
    def __init__(self, *data, **kwargs):
        """name is an unused keyword in BasicEnumGroup."""
        self.data = data
    def __eq__(self, other):
        return (self.data == other)

    #@todo: self._validate_name, self._validate_aliases
    #-- Getters
    @property
    def data(self):
        return tuple([self.name]) + self.aliases
    @data.setter
    def data(self, value):
        self.name, self.aliases = self._validate_data(value)
    @data.deleter
    def data(self):
        del self.name
        del self.aliases
    def _validate_data(self, data):
        rich_core.AssertKlass(data, rich_core.NonStringSequence, name='data')
        assert(len(data) == 1), "'data' must be length 1."
        return data[0], tuple() #name, aliases

    @property
    def aliases(self):
        return self._aliases
    @aliases.setter
    def aliases(self, value):
        self._aliases = self._validate_aliases(value)
    @aliases.deleter
    def aliases(self):
        del self._aliases
    def _validate_aliases(self, aliases):
        rich_core.AssertKlass(aliases, rich_core.NonStringSequence, name='aliases')
        return aliases

#------------------------------------------------------------------------------
#    Local Utility Functions
#------------------------------------------------------------------------------
def _ensure_list(value):
    """Return value as a list; if not a NonStringSequence, wraps in a list."""
    if isinstance(value, list):
        return value
    elif isinstance(value, rich_core.NonStringSequence):
        return list(value)
    else:
        return [value]

import unittest
import operator
class BasicEnumGroupTests(unittest.TestCase):
    constructor = BasicEnumGroup
    def setUp(self):
        self.g1a = self.constructor('attempting')
        self.g1b = self.constructor('attempting')
        self.g1c = self.constructor('attempting')
        self.g2  = self.constructor('attempt')

    def test_group_equality(self):

        self.assertEqual(self.g1a, self.g1b)
        self.assertEqual(self.g1a, self.g1c)
        self.assertEqual(self.g1b, self.g1c)
        self.assertNotEqual(self.g1a, self.g2)

    def test_contains(self):
        self.assert_(
            'attempt' not in self.g1a
        )
        self.assert_(
            'attempt' in self.g2
        )
        self.assert_(
            'non' not in self.g1a
        )
    def test_name(self):
        self.assertEqual(self.g1a.name, 'attempting')
        self.assertEqual(self.g1b.name, 'attempting')
        self.assertEqual(self.g2.name, 'attempt')
    def test_string_comparison(self):
        pass
    def test_errors(self):
        self.assertRaises(TypeError, lambda: self.g1a['attempting'])
        self.assertRaises(IndexError, lambda: self.g1b[1])
        self.assertRaises(TypeError, lambda: operator.delitem(self.g1c, 0) )

class EnumGroupTests(unittest.TestCase):
    constructor = EnumGroup
    def setUp(self):
        self.g1a = self.constructor(('attempting',))
        self.g1b = self.constructor(['attempting'])
        self.g1c = self.constructor('attempting',)
        self.g2  = self.constructor('attempt',)
    def test_group_equality(self):
        self.assert_(self.g1a == self.g1b)
        self.assert_(self.g1a == self.g1c)
        self.assert_(self.g1b == self.g1c)
        self.assert_(self.g1a != self.g2)
    def test_contains(self):
        self.assert_(
            'attempt' not in self.g1a
        )
        self.assert_(
            'attempt' in self.g2
        )
        self.assert_(
            'non' not in self.g1a
        )
    def test_name(self):
        self.assertEqual(self.g1a.name, 'attempting')
        self.assertEqual(self.g1b.name, 'attempting')
        self.assertEqual(self.g2.name, 'attempt')
    def test_string_comparison(self):
        pass
    def test_errors(self):
        self.assertRaises(TypeError, lambda: self.g1a['attempting'])
        self.assertRaises(IndexError, lambda: self.g1b[1])

class EnumTests(unittest.TestCase):
    def setUp(self):
        self.States = Enum((
            ('attempting', 'attempt','attempted'),
            ('errored', 'error'),
            ('completed', 'complete')
        ))
        self.expected = [
            ['attempting', 'attempt','attempted'],
            ['errored', 'error'],
            ['completed', 'complete']
        ]
        self.groups = [
            EnumGroup(['attempting', 'attempt','attempted']),
            EnumGroup(['errored', 'error']),
            EnumGroup(['completed', 'complete'])
        ]

    def test_getitem_repr(self):
        state = self.States['attempting']
        self.assert_(isinstance(state, EnumGroup),
            "Is not instance of EnumGroup"
        )
        self.assertEqual(
            repr(state),
            "['attempting', 'attempt', 'attempted']",
            "States does not match repr of expectation."
        )

    def test_iter(self):
        names = ['attempting','errored','completed']
        for state, name, expected in zip(self.States,self.States.names, names):
            self.assert_(
                state.name == name == expected,
                "Inequality among: {0}, {1}, {2}".format(
                    state.name, name, expected
                )
            )

    def test_group_comparison(self):
        #For Enum
        self.assertEqual(
            self.States,
            self.groups,
            "States does not match expected groups"
        )

        #Group comparison
        self.assertEqual(
            self.States['attempting'],
            EnumGroup(['attempting', 'attempt','attempted']),
            "group comparison"
        )
    def test_string_comparison(self):
        #For Enum collection
        self.assertEqual(
            self.States,
            self.expected,
            "Enum() does not match expectation"
        )

        #For single groups
        compared = all(
            (exp == state)
            for exp, state in zip(self.expected, self.States)
        )

        self.assert_(compared, "Iterator failed.")

        self.assertEqual(
            list(elm for elm in self.States),
            self.expected,
            "Groups from iter do not match expectations."
        )

    #def test_group_containment(self):
    #   States['attempting'] in States
    #def test_string_containment(self):
    #   'attempting' in States

#     def test_corner_case(self):
#         Problems = Enum([
#             (2,),
#             (1,),
#             ('c',)
#         ])
#         Problems['2']
#         print(Problems[1])
#         import pdb
#         pdb.set_trace()
#         print(Problems[1])

if __name__ == "__main__":
    unittest.main()


text:
/*!
 * monk.ui.js
 * version: 0.3.5
 * author: 百小僧(QQ:8020292)
 * site:http://www.baisoft.org
 * QQ群:123049073
 * https://github.com/MonkSoul/Monk.UI/
 */
; !function (factory) {
    "use strict";
    if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
        var target = module['exports'] || exports;
        factory(target);
    } else if (typeof define === 'function' && define['amd']) {
        define(['exports'], factory);
    } else {
        factory(window['monk'] = {});
    }
}(function (HExports) {
    var exports = typeof HExports !== 'undefined' ? HExports : {};
    exports.v = "0.3.5";
    exports.nextAll = function (el) {
        var eles = [];

        function nextCore(el) {
            var next = el.nextElementSibling;
            if (next) {
                eles.push(next);
                arguments.callee(next);
            }
        }
        nextCore(el);
        return eles;
    };
    // 初始化文本框
    // 设置必填图标位置
    exports.setRequireIconOffset = function (parent, init) {
        var that = this;
        var requireIcon = parent.querySelector(".monk-iconfont.icon-monk-required");
        var clearBtn = parent.querySelector(".monk-clear-input");
        if (requireIcon && clearBtn) {
            if (init) {
                var nexts = that.nextAll(requireIcon);
                var totalWidth = 0;
                Array.prototype.forEach.call(nexts, function (next, i) {
                    if (next) {
                        totalWidth += next.offsetWidth;
                    }
                });
                requireIcon.style.right = -totalWidth + "px";
            } else {
                requireIcon.style.right = "0px";
            }
        }
    }
    ;
    exports.inputInit = function () {
        var inputs = document.querySelectorAll(".monk-form-input,.monk-form-textarea");
        // 初始化文本框并绑定事件
        Array.prototype.forEach.call(inputs, function (input, i) {
            // 初始化关闭按钮和必填位置问题
            var parent = input.parentNode;
            exports.setRequireIconOffset(parent, true);
            // 绑定focus事件
            input.addEventListener("focus", function () {
                var parent = this.parentNode;
                parent.classList.add("focus");
            });
            ;// 绑定blur事件
            input.addEventListener("blur", function () {
                var parent = this.parentNode;
                if (!parent.classList.contains("monk-form-time-wrap")) {
                    parent.classList.remove("focus");
                }
            });
            ;// 绑定keyup事件
            input.addEventListener("keyup", function () {
                var parent = this.parentNode;
                var value = this.value.trim();
                var clearBtn = parent.querySelector(".monk-clear-input");
                if (clearBtn) {
                    if (value != "") {
                        clearBtn.style.cssText = "visibility:visible;";
                        exports.setRequireIconOffset(parent);
                    } else {
                        clearBtn.style.cssText = "visibility:hidden;";
                        exports.setRequireIconOffset(parent, true);
                    }
                }
            });
            // 绑定change事件
            input.addEventListener("change", function () {
                var parent = this.parentNode;
                var value = this.value.trim();
                var clearBtn = parent.querySelector(".monk-clear-input");
                if (clearBtn) {
                    if (value == "") {
                        clearBtn.style.cssText = "visibility:hidden;";
                        exports.setRequireIconOffset(parent, true);
                    }
                }
            });
            input.parentElement.addEventListener("click", function () {
                this.querySelector(".monk-form-input,.monk-form-textarea").focus();
            });
            ; var clearBtn = input.parentNode.querySelector(".monk-clear-input");
            if (clearBtn) {
                var value = input.value;
                if (value != "") {
                    clearBtn.style.cssText = "visibility:visible;";
                    exports.setRequireIconOffset(parent);
                } else {
                    clearBtn.style.cssText = "visibility:hidden;";
                }
                // 绑定关闭按钮
                clearBtn.addEventListener("click", function () {
                    var parent = this.parentNode;
                    var input = parent.querySelector(".monk-form-input,.monk-form-textarea");
                    input.value = "";
                    exports.setRequireIconOffset(parent, true);
                    this.style.cssText = "visibility:hidden;";
                });
                ;
            }
            // 自适应
            input.style.width = "";
            var areaWidth = input.parentNode.parentNode.offsetWidth;
            var parentWidth = input.parentNode.offsetWidth;
            if (parentWidth >= areaWidth) {
                var width = 0;
                Array.prototype.filter.call(input.parentNode.children, function (child) {
                    if (child !== input) {
                        width += child.offsetWidth;
                    }
                });
                input.style.width = areaWidth - width - 2 + "px";
            }
        });
    }();
    // 生成checkbox,radio,switch
    exports.createCheckboxRadio = function (arr) {
        if (arr.length > 0) {
            // 获取类型
            var type = arr[0];
            // 移除
            arr.splice(0, 1);
            var all = document.querySelectorAll(".monk-form-" + type + "-list");
            // 初始化HTML并绑定事件
            Array.prototype.forEach.call(all, function (list, i) {
                var html = "";
                // 获取所有的选项
                var items = list.querySelectorAll(".monk-" + type);
                Array.prototype.forEach.call(items, function (item, i) {
                    var name = item.getAttribute("name");
                    var value = item.value;
                    var text = item.getAttribute("text");
                    var checked = item.getAttribute("checked");
                    var readonly = item.getAttribute("readonly");
                    var disabled = item.getAttribute("disabled");
                    var valueHtml = value ? 'data-value="' + value + '"' : 'data-value=""';
                    var nameHtml = name ? 'data-name="' + name + '" ' : '';
                    var textHtml = text ? text : "value";
                    var checkedHtml = checked ? 'checked="checked"' : '';
                    var readonlyHtml = readonly ? 'readonly="readonly"' : '';
                    var disabledHtml = disabled ? 'disabled="disabled"' : '';
                    html += '
';
                    if (type == "checkbox" || type == "switch") {
                        html += '' + textHtml + '';
                        html += '';
                    } else if (type == "radio") {
                        html += '';
                        html += '' + textHtml + '';
                    }
                    html += '
\r\n';
                    // 设置只读
                    item.addEventListener("click", function () {
                        var readonly = this.getAttribute("readonly");
                        if (readonly) {
                            return false;
                        }
                    });
                    ;// 绑定改变事件
                    item.addEventListener("change", function () {
                        var name = this.getAttribute("name");
                        var value = this.value;
                        var parent = this.parentNode;
                        var wrap = parent.querySelector(".monk-form-" + type + "-wrap[data-name='" + name + "'][data-value='" + value + "']");
                        if (this.checked == true) {
                            if (type == "radio") {
                                var lastWrap = parent.querySelector(".monk-form-radio-wrap[checked='checked']");
                                if (lastWrap !== wrap) {
                                    lastWrap.removeAttribute("checked");
                                    wrap.setAttribute("checked", "checked");
                                }
                            } else {
                                wrap.setAttribute("checked", "checked");
                            }
                        } else {
                            if (type != "radio") {
                                wrap.removeAttribute("checked");
                            }
                        }
                    });
                    ;
                });
                // 生成HTML代码
                list.insertAdjacentHTML("afterbegin", html);
                // 获取所有的wrap
                var wraps = list.querySelectorAll(".monk-form-" + type + "-wrap");
                Array.prototype.forEach.call(wraps, function (wrap, i) {
                    // 绑定点击事件
                    wrap.addEventListener("click", function () {
                        var checked = this.getAttribute("checked");
                        var readonly = this.getAttribute("readonly");
                        var disabled = this.getAttribute("disabled");
                        var name = this.getAttribute("data-name");
                        var value = this.getAttribute("data-value");
                        if (readonly != "readonly" && disabled != "disabled") {
                            var parent = this.parentNode;
                            var box = parent.querySelector(".monk-" + type + "[name='" + name + "'][value='" + value + "']");
                            if (type == "radio") {
                                var lastWrap = parent.querySelector(".monk-form-" + type + "-wrap[checked='checked']");
                                if (lastWrap !== this) {
                                    lastWrap.removeAttribute("checked");
                                }
                                this.setAttribute("checked", "checked");
                                box.checked = true;
                            } else {
                                if (checked == "checked") {
                                    this.removeAttribute("checked");
                                    box.checked = false;
                                } else {
                                    this.setAttribute("checked", "checked");
                                    box.checked = true;
                                }
                            }
                        }
                    });
                    ;
                });
            });
            arguments.callee(arr);
        }
    }(["checkbox", "switch", "radio"]);
    // 初始化下拉
    exports.selectInit = function () {
        var all = document.querySelectorAll(".monk-form-select");
        // 初始化HTML并绑定事件
        Array.prototype.forEach.call(all, function (list, i) {
            // 设置宽度
            var selectWrap = list.parentNode.querySelector(".monk-form-select-wrap");
            list.style.width = selectWrap.offsetWidth + "px";
            var html = "";
            // 获取所有的选项
            var items = list.querySelectorAll(".monk-select *");
            Array.prototype.forEach.call(items, function (item, i) {
                if (item.tagName.toLowerCase() == "option") {
                    var text = item.textContent;
                    var value = item.getAttribute("value");
                    html += '
' + text + '
';
                } else if (item.tagName.toLowerCase() == "optgroup") {
                    var label = item.getAttribute("label");
                    html += '
' + label + '
';
                }
            });
            // 生成HTML代码
            list.insertAdjacentHTML("afterbegin", html);
            // 设置默认选中
            var select = list.querySelector(".monk-select");
            var option = select.querySelectorAll("option")[select.selectedIndex];
            var selectValue = option.value;
            var selectText = option.textContent;
            list.querySelector(".monk-form-option[data-value='" + selectValue + "']").setAttribute("selected", "selected");
            list.parentNode.querySelector(".monk-form-select-wrap .monk-form-input").setAttribute("value", selectText);
            // 绑定事件
            var options = list.querySelectorAll(".monk-form-option");
            Array.prototype.forEach.call(options, function (option, i) {
                option.addEventListener("mousedown", function () {
                    var value = this.getAttribute("data-value");
                    var text = this.textContent;
                    var parent = this.parentNode;
                    var scrollTop = this.offsetTop;
                    var select = parent.querySelector(".monk-select");
                    var input = parent.parentNode.querySelector(".monk-form-input");
                    var readonly = input.getAttribute("readonly");
                    if (!readonly) {
                        if (value != "") {
                            var lastWrap = this.parentNode.querySelector(".monk-form-option[selected='selected']");
                            if (lastWrap !== this && lastWrap) {
                                lastWrap.removeAttribute("selected");
                            }
                            this.setAttribute("selected", "selected");
                            input.value = text;
                            parent.scrollTop = scrollTop;
                            select.value = value;
                        }
                    }
                });
                ;
            });
        });
        function searchText(that) {
            var value = that.value;
            var parent = that.parentNode;
            var select = parent.parentNode.querySelector(".monk-form-select");
            var option = select.querySelector(".monk-form-option[data-text*='" + value + "']");
            if (option) {
                select.scrollTop = option.offsetTop;
            }
        }
        // 输入框绑定事件
        var inputs = document.querySelectorAll(".monk-form-select-wrap .monk-form-input");
        Array.prototype.forEach.call(inputs, function (input, i) {
            // 绑定焦点事件
            input.addEventListener("focus", function () {
                var parent = this.parentNode;
                var selectbox = parent.parentNode.querySelector(".monk-form-select");
                selectbox.classList.remove("monk-none");
                searchText(this);
            });
            ;// 失去焦点
            input.addEventListener("blur", function () {
                var parent = this.parentNode;
                var selectbox = parent.parentNode.querySelector(".monk-form-select");
                selectbox.classList.add("monk-none");
            });
            ;// 搜索
            input.addEventListener("keyup", function () {
                searchText(this);
            });
            ;
        });
        // 下拉图标绑定事件
        var selectIcons = document.querySelectorAll(".monk-select-arrow");
        Array.prototype.forEach.call(selectIcons, function (icon, i) {
            icon.addEventListener("mousedown", function () {
                var input = this.parentNode.querySelector(".monk-form-select-wrap .monk-form-input");
                var disabled = input.getAttribute("disabled");
                var select = input.parentNode.parentNode.querySelector(".monk-form-select");
                if (disabled != "disabled") {
                    if (select.classList.contains("monk-none")) {
                        setTimeout(function () {
                            input.focus();
                        }, 100);
                    } else {
                        input.blur();
                    }
                }
            });
            ;
        });
        // 下拉绑定事件
        var selects = document.querySelectorAll(".monk-select");
        Array.prototype.forEach.call(selects, function (select, i) {
            select.addEventListener("change", function () {
                var option = this.querySelectorAll("option")[select.selectedIndex];
                var selectValue = option.value;
                var selectText = option.textContent;
                var option = this.parentNode.querySelector(".monk-form-option[data-value='" + selectValue + "']");
                var input = this.parentNode.parentNode.querySelector(".monk-form-select-wrap .monk-form-input")
                var lastWrap = this.parentNode.querySelector(".monk-form-option[selected='selected']");
                if (lastWrap !== this && lastWrap) {
                    lastWrap.removeAttribute("selected");
                }
                option.setAttribute("selected", "selected");
                input.value = selectText;
                this.parentNode.scrollTop = option.offsetTop;
            });
            ;
        });
    }();
    // 初始化时间
    exports.timeInit = function () {
        function createTimeTags() {
            var html = '
';
            html += '
';
            html += '小时分钟秒钟';
            html += '
';
            html += '
';
            html += '
';
            // 生成小时
            for (var i = 0; i < 24; i++) {
                if (i < 10) {
                    html += '0' + i + '';
                } else {
                    html += '' + i + '';
                }
            }
            html += '
';
            html += '
';
            // 生成分钟
            for (var i = 0; i < 60; i++) {
                if (i < 10) {
                    html += '0' + i + '';
                } else {
                    html += '' + i + '';
                }
            }
            html += '
';
            html += '
';
            // 生成秒
            for (var i = 0; i < 60; i++) {
                if (i < 10) {
                    html += '0' + i + '';
                } else {
                    html += '' + i + '';
                }
            }
            html += '
';
            html += '
';
            html += '
当前时间关闭
';
            html += '
';
            return html;
        }
        var wraps = document.querySelectorAll(".monk-form-time-wrap");
        Array.prototype.forEach.call(wraps, function (wrap, i) {
            var input = wrap.querySelector(".monk-form-input");
            var value = input.value;
            if (!(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/.test(value))) {
                input.value = "00:00:00";
            }
            // 生成HTML代码
            wrap.insertAdjacentHTML("afterend", createTimeTags());
            // 设置宽度
            var timeWrap = wrap.parentNode.querySelector(".monk-form-time");
            timeWrap.style.width = wrap.offsetWidth + "px";
        });
        // 输入框绑定事件
        var inputs = document.querySelectorAll(".monk-form-time-wrap .monk-form-input");
        Array.prototype.forEach.call(inputs, function (input, i) {
            // 绑定焦点事件
            input.addEventListener("focus", function () {
                var parent = this.parentNode;
                var timebox = parent.parentNode.querySelector(".monk-form-time");
                timebox.classList.remove("monk-none");
                // 设置滚动
                var value = this.value;
                var timeArr = value.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
                var time = timeArr[0];
                var hour = timeArr[1];
                var minute = timeArr[3];
                var second = timeArr[4];
                var hourItem = this.parentNode.parentNode.querySelector(".monk-form-time-item:nth-child(1)");
                var minuteItem = this.parentNode.parentNode.querySelector(".monk-form-time-item:nth-child(2)");
                var secondItem = this.parentNode.parentNode.querySelector(".monk-form-time-item:nth-child(3)");
                var hourOption = hourItem.querySelector(".monk-form-time-hour[data-value='" + hour + "']");
                var minuteOption = minuteItem.querySelector(".monk-form-time-minute[data-value='" + minute + "']");
                var secondOption = secondItem.querySelector(".monk-form-time-second[data-value='" + second + "']");
                var hourSelect = hourItem.querySelector(".monk-form-time-hour.selected");
                var minuteSelect = minuteItem.querySelector(".monk-form-time-minute.selected");
                var secondSelect = secondItem.querySelector(".monk-form-time-second.selected");
                hourSelect ? hourSelect.classList.remove("selected") : "";
                minuteSelect ? minuteSelect.classList.remove("selected") : "";
                secondSelect ? secondSelect.classList.remove("selected") : "";
                hourItem.scrollTop = hourOption.offsetTop;
                minuteItem.scrollTop = minuteOption.offsetTop;
                secondItem.scrollTop = secondOption.offsetTop;
                hourOption.classList.add("selected");
                minuteOption.classList.add("selected");
                secondOption.classList.add("selected");
            });
            ; input.addEventListener("blur", function () {
                var inputValue = this.value;
                if (!(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/.test(inputValue))) {
                    var hourOpiton = this.parentNode.parentNode.querySelector(".monk-form-time-item:nth-child(1) .monk-form-time-hour.selected");
                    var minuteOpiton = this.parentNode.parentNode.querySelector(".monk-form-time-item:nth-child(2) .monk-form-time-minute.selected");
                    var secondOpiton = this.parentNode.parentNode.querySelector(".monk-form-time-item:nth-child(3) .monk-form-time-second.selected");
                    var timeArr = [];
                    timeArr[0] = hourOpiton ? hourOpiton.getAttribute("data-value") : "00";
                    timeArr[1] = minuteOpiton ? minuteOpiton.getAttribute("data-value") : "00";
                    timeArr[2] = secondOpiton ? secondOpiton.getAttribute("data-value") : "00";
                    this.value = timeArr.join(":");
                }
            });
        });
        function setTime(timeArr, that, typeIndex) {
            var time = that.textContent.trim();
            var lastWrap = that.parentNode.querySelector(".monk-form-time-" + typeIndex[1] + ".selected");
            if (lastWrap !== that && lastWrap) {
                lastWrap.classList.remove("selected");
            }
            timeArr[typeIndex[0]] = time;
        }
        // 小时选择
        var times = document.querySelectorAll(".monk-form-time-hour,.monk-form-time-minute ,.monk-form-time-second");
        Array.prototype.forEach.call(times, function (time, i) {
            time.addEventListener("click", function () {
                var input = this.parentNode.parentNode.parentNode.parentNode.querySelector(".monk-form-time-wrap .monk-form-input");
                var readonly = input.getAttribute("readonly");
                if (!readonly) {
                    var inputValue = input.value;
                    if (!(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/.test(inputValue))) {
                        input.value = "00:00:00";
                    }
                    var timeArr = inputValue.split(":");
                    if (timeArr.length == 0) {
                        timeArr = ["00", "00", "00"];
                    } else if (timeArr.length == 1) {
                        timeArr.push("00");
                        timeArr.push("00");
                    } else if (timeArr.length == 2) {
                        timeArr.push("00");
                    }
                    if (this.classList.contains("monk-form-time-hour")) {
                        setTime(timeArr, this, [0, "hour"]);
                    } else if (this.classList.contains("monk-form-time-minute")) {
                        setTime(timeArr, this, [1, "minute"]);
                    } else if (this.classList.contains("monk-form-time-second")) {
                        setTime(timeArr, this, [2, "second"]);
                    }
                    input.value = timeArr.join(":");
                    this.classList.add("selected");
                }
            });
        });
        // 点击按钮
        var timeBtns = document.querySelectorAll(".monk-form-time-btn span");
        Array.prototype.forEach.call(timeBtns, function (btn, i) {
            btn.addEventListener("click", function () {
                var input = this.parentNode.parentNode.parentNode.querySelector(".monk-form-time-wrap .monk-form-input");
                if (this.classList.contains("monk-time-current")) {
                    var readonly = input.getAttribute("readonly");
                    if (!readonly) {
                        var date = new Date();
                        var hours = date.getHours();
                        if (hours < 10) {
                            hours = "0" + hours;
                        }
                        var minute = date.getMinutes();
                        if (minute < 10) {
                            minute = "0" + minute;
                        }
                        var second = date.getSeconds();
                        if (second < 10) {
                            second = "0" + second;
                        }
                        var value = hours + ":" + minute + ":" + second;
                        input.value = value;
                        this.parentNode.querySelector(".monk-time-close").click();
                    }
                } else if (this.classList.contains("monk-time-close")) {
                    this.parentNode.parentNode.classList.add("monk-none");
                    input.blur();
                    input.parentNode.classList.remove("focus");
                }
            });
        });
        // 时间图标绑定事件
        var timeIcons = document.querySelectorAll(".icon-monk-time");
        Array.prototype.forEach.call(timeIcons, function (icon, i) {
            icon.addEventListener("mousedown", function () {
                var input = this.parentNode.querySelector(".monk-form-time-wrap .monk-form-input");
                var disabled = input.getAttribute("disabled");
                var timebox = input.parentNode.parentNode.querySelector(".monk-form-time");
                if (disabled != "disabled") {
                    if (timebox.classList.contains("monk-none")) {
                        setTimeout(function () {
                            input.focus();
                        }, 100);
                    } else {
                        timebox.classList.add("monk-none");
                        input.blur();
                        input.parentNode.classList.remove("focus");
                    }
                }
            });
            ;
        });
    }();
    // 初始化文件选择
    exports.fileInit = function () {
        var files = document.querySelectorAll(".monk-file");
        Array.prototype.forEach.call(files, function (file, i) {
            file.addEventListener("change", function () {
                var value = this.value;
                this.parentNode.parentNode.querySelector(".monk-form-input").value = value;
            });
        });
    }();
    // 初始化代码显示
    exports.codeInit = function () {
        var codes = document.querySelectorAll(".monk-code");
        Array.prototype.forEach.call(codes, function (code, i) {
            var language = code.getAttribute("data-language");
            var html = code.innerHTML;
            if (language.toLowerCase() == "html" || language.toLowerCase() == "xml") {
                html = html.replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/"/g, '"')
            }
            code.innerHTML = '

' + html.replace(/[\r\t\n]+/g, '

') + '

' + language + '';
        });
    }();
    // 模板引擎
    exports.tppl_flag = ["<%", "%>"];
    exports.tppl = function (tpl, data) {
        var that = this;
        var fn = function (d) {
            var i, k = [], v = [];
            for (i in d) {
                k.push(i);
                v.push(d[i]);
            }
            ; return (new Function(k, fn.$)).apply(d, v);
        }
        ;
        if (!fn.$) {
            var tpls = tpl.split(that.tppl_flag[0]);
            fn.$ = "var $=''";
            for (var t = 0; t < tpls.length; t++) {
                var p = tpls[t].split(that.tppl_flag[1]);
                if (t != 0) {
                    fn.$ += '=' == p[0].charAt(0) ? "+(" + p[0].substr(1) + ")" : ";" + p[0].replace(/\r\n/g, '') + "$=$"
                }
                fn.$ += "+'" + p[p.length - 1].replace(/\'/g, "\\'").replace(/\r\n/g, '\\n').replace(/\n/g, '\\n').replace(/\r/g, '\\n') + "'";
            }
            fn.$ += ";return $;";
        }
        return data ? fn(data) : fn;
    }
    ;
    // 重置表单
    exports.resetForm = function () {
        // 解决reset点击后,关闭按钮问题
        var reset = document.querySelector("input[type='reset']");
        function getParentsForm(el) {
            var form;
            function callee(el) {
                if (el) {
                    if (el.parentNode.tagName.toLowerCase() == "form") {
                        form = el.parentNode;
                        return;
                    } else {
                        arguments.callee(el.parentNode);
                    }
                }
            }
            callee(el);
            return form;
        }
        ;// 重置复选框,单选框,切换框
        function resetCheckboxRadio(form, type) {
            var checkboxs = form.querySelectorAll(".monk-" + type);
            Array.prototype.forEach.call(checkboxs, function (checkbox, i) {
                var name = checkbox.getAttribute("name");
                var value = checkbox.value;
                var parent = checkbox.parentNode;
                var wrap = parent.querySelector(".monk-form-" + type + "-wrap[data-name='" + name + "'][data-value='" + value + "']");
                if (checkbox.checked == true) {
                    wrap.setAttribute("checked", "checked");
                } else {
                    wrap.removeAttribute("checked");
                }
            });
        }
        ;
        if (reset) {
            reset.addEventListener("click", function () {
                var form = getParentsForm(this);
                if (form) {
                    form.reset();
                    // 重置输入框
                    var inputs = form.querySelectorAll(".monk-form-input,.monk-form-textarea");
                    Array.prototype.forEach.call(inputs, function (input, i) {
                        var parent = input.parentNode;
                        var value = input.value.trim();
                        var clearBtn = parent.querySelector(".monk-clear-input");
                        if (clearBtn) {
                            if (value != "") {
                                clearBtn.style.cssText = "visibility:visible;";
                                exports.setRequireIconOffset(parent);
                            } else {
                                clearBtn.style.cssText = "visibility:hidden;";
                                exports.setRequireIconOffset(parent, true);
                            }
                        }
                    });
                    // 重置radio,checkbox,switch
                    resetCheckboxRadio(form, "checkbox");
                    resetCheckboxRadio(form, "switch");
                    resetCheckboxRadio(form, "radio");
                    // 重置时间(无需重置)
                    // 重置下拉
                    var selects = form.querySelectorAll(".monk-select");
                    Array.prototype.forEach.call(selects, function (select, i) {
                        var option = select.querySelectorAll("option")[select.selectedIndex];
                        var selectValue = option.value;
                        var selectText = option.textContent;
                        var lastSelectOption = select.parentNode.querySelector(".monk-form-option[selected='selected']");
                        lastSelectOption ? lastSelectOption.removeAttribute("selected") : "";
                        select.parentNode.querySelector(".monk-form-option[data-value='" + selectValue + "']").setAttribute("selected", "selected");
                        select.parentNode.parentNode.querySelector(".monk-form-select-wrap .monk-form-input").setAttribute("value", selectText);
                    });
                }
            });
        }
    }();
    window.onresize = function () {
        var inputs = document.querySelectorAll(".monk-form-input,.monk-form-textarea");
        Array.prototype.forEach.call(inputs, function (input, i) {
            input.style.width = "";
            // 自适应
            var areaWidth = input.parentNode.parentNode.offsetWidth;
            var parentWidth = input.parentNode.offsetWidth;
            if (parentWidth >= areaWidth) {
                var width = 0;
                Array.prototype.filter.call(input.parentNode.children, function (child) {
                    if (child !== input) {
                        width += child.offsetWidth;
                    }
                });
                input.style.width = areaWidth - width - 2 + "px";
            }
        });
    };
});


text:
<?php

namespace Antares\UI\Navigation\Events;

use Antares\UI\Navigation\Menu;

class MenuCreated {

    /**
     * @var Menu
     */
    public $menu;

    /**
     * MenuCreated constructor.
     * @param Menu $menu
     */
    public function __construct(Menu $menu) {
        $this->menu = $menu;
    }

}


text:
<component name="libraryTable">
  <library name="Maven: net.openhft:zero-allocation-hashing:0.8">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/net/openhft/zero-allocation-hashing/0.8/zero-allocation-hashing-0.8.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/net/openhft/zero-allocation-hashing/0.8/zero-allocation-hashing-0.8-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/net/openhft/zero-allocation-hashing/0.8/zero-allocation-hashing-0.8-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
Categories

Admin

Meta

Category

Category Table

          <no-result text="No Category."></no-result>

        <loading ng-if="loading" text="Loading Categories"></loading>

                  {{theaditem.name}}
                  Actions

                      <input class="fileupload" type="file" name="file" file-upload="options"/>

                    <input class="form-control" ng-value="cate.name" type="text" placeholder="category name"/>

                    <input class="form-control" ng-value="cate.alias" type="text" placeholder="category name"/>

                          <input class="i-checks" type="checkbox" ng-model="cate.checked" icheck="icheck"/>

                      <input class="form-control txtLink" type="text" ng-model="cate.link" ng-disabled="!cate.checked"/>

                    <button class="remove btn btn-white" type="button" title="删除" ng-click="removeCate()"></button>

          <button class="btn btn-white" id="btnNew" ng-click="addCate()">New Category</button>
          <button class="btn btn-primary pull-right" id="btnSave" ng-click="saveCategories()">Save</button>


text:
using System;
using Newtonsoft.Json;

namespace Eventbrite.Entities
{
  public class HybridDate
  {
    [JsonProperty(PropertyName = "timezone")]
    public string Timezone { get; set; }

    [JsonProperty(PropertyName = "local")]
    public DateTime Local { get; set; }

    [JsonProperty(PropertyName = "utc")]
    public DateTime Utc { get; set; }
  }
}


text:
<!doctype html>
<html>
<head>
  <title>polymer home page</title>
  <style>
    html, body {
      font-family: Arial, sans-serif;
      white-space: nowrap;
      overflow: hidden;
    }
    polymer-home-page {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }
  </style>
  <script src="../platform/platform.js"></script>
  <link rel="import" href="polymer-home-page.html">
</head>
<body>
  <polymer-home-page></polymer-home-page>
</body>
</html>


text:
TIMBIR
######

TIMBIR is a method for 4D time-space reconstruction of data acquired using synchrotron X-ray computed tomography.
This software can be used to reconstruct any tomographic data in 3D or 4D.

-----------------
Project homepage:
-----------------
`http://timbir.readthedocs.org <http://timbir.readthedocs.org>`_

------------
Dependencies
------------
- MPI compiler
- Open MP
- Make utility

-------------
Demo/Examples
-------------
- Unix/Linux/Mac OS
	- 3D Reconstruction: Change directory to demo/recon_3d/shepp-logan-3D/ and run the script run_unix.sh
	- 4D Reconstruction: Change directory to demo/recon_4d/cahn-hilliard-4D/ and run the script run_unix.sh

- Supercomputing cluster (Rice cluster at Purdue)
	- 3D Reconstruction: Change directory to demo/recon_3d/shepp-logan-3D/ and run the script run_cluster.sh
	- 4D Reconstruction: Change directory to demo/recon_4d/cahn-hilliard-4D/ and run the script run_cluster.sh

---------
Citation
---------
- \K. A. Mohan, S. V. Venkatakrishnan, J. W. Gibbs, E. B. Gulsoy, X. Xiao, M. De Graef, P. W. Voorhees, and C. A. Bouman, "TIMBIR: A method for time-space reconstruction from interlaced views," IEEE Transactions on Computational Imaging, vol. 1, no. 2, pp. 96.111, June 2015.


text:
<?php

namespace AveEntityManager\Mapping\Sql\Field\Type;

/**
 * Class FloatType
 *
 * @package AveEntityManager\Mapping\Sql\Field\Type
 * @author Averor <averor.dev@gmail.com>
 * @created 20.06.17
 */
class FloatField extends AbstractScalarField
{
    const FIELD_TYPE = 'float';

    /**
     * {@inheritdoc}
     */
    public function entityValue($value)
    {
        return (float) $value;
    }

    /**
     * {@inheritdoc}
     */
    public function storageValue($value)
    {
        return (float) $value;
    }
}


text:
This example shows how to use ``Arena`` to submit a distributed pytorch job with tensorboard. The sample downloads the source code from git url.

1\. The first step is to check the available resources.
```
➜ arena top node
NAME                       IPADDRESS     ROLE    STATUS  GPU(Total)  GPU(Allocated)
cn-huhehaote.172.16.0.205  172.16.0.205  master  ready   0           0
cn-huhehaote.172.16.0.206  172.16.0.206  master  ready   0           0
cn-huhehaote.172.16.0.207  172.16.0.207  master  ready   0           0
cn-huhehaote.172.16.0.208  172.16.0.208  <none>  ready   4           0
cn-huhehaote.172.16.0.209  172.16.0.209  <none>  ready   4           0
cn-huhehaote.172.16.0.210  172.16.0.210  <none>  ready   4           0
-----------------------------------------------------------------------------------------
Allocated/Total GPUs In Cluster:
0/12 (0%)
```

As you see, there are 3 available nodes with GPU for running training jobs.

2\. Submit a distributed pytorch training job with 2 nodes and one gpu card, this example downloads the source code from  [Alibaba Cloud code]( https://code.aliyun.com/370272561/mnist-pytorch.git).
```
➜ arena --loglevel info submit pytorch \
    --name=pytorch-dist-tensorboard \
    --gpus=1 \
    --workers=2 \
    --image=registry.cn-beijing.aliyuncs.com/ai-samples/pytorch-with-tensorboard:1.5.1-cuda10.1-cudnn7-runtime \
    --sync-mode=git \
    --sync-source=https://code.aliyun.com/370272561/mnist-pytorch.git \
    --tensorboard \
    --logdir=/root/logs \
    "python /root/code/mnist-pytorch/mnist.py --epochs 50 --backend gloo --dir /root/logs"

configmap/pytorch-dist-tensorboard-pytorchjob created
configmap/pytorch-dist-tensorboard-pytorchjob labeled
service/pytorch-dist-tensorboard-tensorboard created
deployment.apps/pytorch-dist-tensorboard-tensorboard created
pytorchjob.kubeflow.org/pytorch-dist-tensorboard created
INFO[0000] The Job pytorch-dist-tensorboard has been submitted successfully
INFO[0000] You can run `arena get pytorch-dist-tensorboard --type pytorchjob` to check the job status
```

!!! note

    * the source code will be downloaded and extracted to the directory ``code/`` of the working directory. The default working directory is ``/root``, you can also specify by using ``--workingDir``.

    * ``workers`` is the total number of nodes participating in the training (must be a positive integer and greater than or equal to 1), including rank0 node used to establish communication (corresponding to the ``master`` node in the pytorch-operator). The default value of the parameter is 1, which can not be set, as a stand-alone job.

    * ``logdir`` indicates where the tensorboard reads the event logs of Pytorch.

3\. List all the jobs.
```
➜ arena list
NAME                          STATUS     TRAINER     AGE  NODE
pytorch-dist-tensorboard      SUCCEEDED  PYTORCHJOB  22h  N/A
```

4\. Get the details of the this job.
```
➜ arena get pytorch-dist-tensorboard
STATUS: SUCCEEDED
NAMESPACE: default
PRIORITY: N/A
TRAINING DURATION: 15m

NAME                      STATUS     TRAINER     AGE  INSTANCE                           NODE
pytorch-dist-tensorboard  SUCCEEDED  PYTORCHJOB  22h  pytorch-dist-tensorboard-master-0  172.16.0.210
pytorch-dist-tensorboard  SUCCEEDED  PYTORCHJOB  22h  pytorch-dist-tensorboard-worker-0  172.16.0.210

Your tensorboard will be available on:
http://172.16.0.205:30583
```

5\. You can access the tensorboard by using ``172.16.0.205:30583``. You can consider ``sshuttle`` if you can't access the tensorboard directly from your laptop. For example:
```
# you can install sshuttle==0.74 in your mac with python2.7
➜ pip install sshuttle==0.74

# 0/0 -> 0.0.0.0/0
➜ sshuttle -r root@39.104.17.205  0/0
```

![image](19-pytorchjob-tensorboard.png)


text:
package uk.co.thefishlive.maths.ui;

import com.google.common.base.Throwables;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javafx.animation.TranslateTransition;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.util.Duration;

import uk.co.thefishlive.maths.Main;
import uk.co.thefishlive.maths.resources.exception.ResourceException;
import uk.co.thefishlive.maths.tasks.TaskManager;
import uk.co.thefishlive.maths.ui.loader.UI;
import uk.co.thefishlive.maths.ui.loader.UILoader;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

public abstract class Controller implements Initializable, Displayable {

    private static final Logger logger = LogManager.getLogger();

    @FXML protected Pane pnlMenu;

    private UI parent;

    @FXML
    public void btnMenu_Click(MouseEvent event) {
        TranslateTransition transition = new TranslateTransition(Duration.millis(500), pnlMenu);
        transition.setByX(205);
        transition.play();
    }

    public void setParent(UI parent) {
        this.parent = parent;
    }

    public UI getParent() {
        return parent;
    }

    public void close() {
        Main.getInstance().setCurrentUI(parent);
    }

    @Override
    public void onDisplay() {}

    @Override
    public void onClose() {
        hideLoadingAnimation();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

    protected abstract Pane getContentPane();

    protected void showLoadingAnimation() {
        Runnable task = () -> {
            try {
                UI loading = UILoader.loadUI(Main.getInstance().getResourceManager().getResource("ui/loading.fxml"));
                getContentPane().getChildren().add(loading.getPane());
                logger.debug("Loaded loading panel");
            } catch (IOException | ResourceException e) {
                Throwables.propagate(e);
            }
        };

        if (!Thread.currentThread().getName().equals("JavaFX Application Thread")) {
            logger.debug("Loading loading panel from separate thread");
            TaskManager.runTaskSync(task);
        } else {
            logger.debug("Loading loading panel from main thread");
            task.run();
        }
    }

    protected void hideLoadingAnimation() {
        Runnable task = () -> {
            List<Node> children = new ArrayList<>(getContentPane().getChildren());
            children.stream().filter(node -> "pnlLoading".equals(node.getId())).forEach(node -> {
                getContentPane().getChildren().remove(node);
            });
            logger.debug("Removed loading panel");
        };

        if (!Thread.currentThread().getName().equals("JavaFX Application Thread")) {
            logger.debug("Removing loading panel from separate thread");
            TaskManager.runTaskSync(task);
        } else {
            logger.debug("Removing loading panel from main thread");
            task.run();
        }
    }
}


text:
<?php

namespace Test\Integration\Version6x0;

include_once(__DIR__. '/../Version4x0/LatencyCommandsTest.php');

class LatencyCommandsTest extends \Test\Integration\Version4x0\LatencyCommandsTest {}


text:
package clientcmd

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/emicklei/go-restful/swagger"
	"github.com/golang/glog"
	"github.com/spf13/pflag"

	"k8s.io/kubernetes/pkg/api"
	kerrors "k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/meta"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/apimachinery/registered"
	kclient "k8s.io/kubernetes/pkg/client/unversioned"
	kclientcmd "k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
	kclientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api"
	"k8s.io/kubernetes/pkg/kubectl"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
	"k8s.io/kubernetes/pkg/labels"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util/sets"

	"github.com/openshift/origin/pkg/api/latest"
	authorizationapi "github.com/openshift/origin/pkg/authorization/api"
	authorizationreaper "github.com/openshift/origin/pkg/authorization/reaper"
	buildapi "github.com/openshift/origin/pkg/build/api"
	buildreaper "github.com/openshift/origin/pkg/build/reaper"
	buildutil "github.com/openshift/origin/pkg/build/util"
	"github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/cmd/cli/describe"
	deployapi "github.com/openshift/origin/pkg/deploy/api"
	deploygen "github.com/openshift/origin/pkg/deploy/generator"
	deployreaper "github.com/openshift/origin/pkg/deploy/reaper"
	deployscaler "github.com/openshift/origin/pkg/deploy/scaler"
	deployutil "github.com/openshift/origin/pkg/deploy/util"
	routegen "github.com/openshift/origin/pkg/route/generator"
	userapi "github.com/openshift/origin/pkg/user/api"
	authenticationreaper "github.com/openshift/origin/pkg/user/reaper"
)

// New creates a default Factory for commands that should share identical server
// connection behavior. Most commands should use this method to get a factory.
func New(flags *pflag.FlagSet) *Factory {
	// TODO refactor this upstream:
	// DefaultCluster should not be a global
	// A call to ClientConfig() should always return the best clientCfg possible
	// even if an error was returned, and let the caller decide what to do
	kclientcmd.DefaultCluster.Server = ""

	// TODO: there should be two client configs, one for OpenShift, and one for Kubernetes
	clientConfig := DefaultClientConfig(flags)
	clientConfig = defaultingClientConfig{clientConfig}
	f := NewFactory(clientConfig)
	f.BindFlags(flags)

	return f
}

// defaultingClientConfig detects whether the provided config is the default, and if
// so returns an error that indicates the user should set up their config.
type defaultingClientConfig struct {
	nested kclientcmd.ClientConfig
}

// RawConfig calls the nested method
func (c defaultingClientConfig) RawConfig() (kclientcmdapi.Config, error) {
	return c.nested.RawConfig()
}

// Namespace calls the nested method, and if an empty config error is returned
// it checks for the same default as kubectl - the value of POD_NAMESPACE or
// "default".
func (c defaultingClientConfig) Namespace() (string, bool, error) {
	namespace, ok, err := c.nested.Namespace()
	if err == nil {
		return namespace, ok, nil
	}
	if !kclientcmd.IsEmptyConfig(err) {
		return "", false, err
	}

	// This way assumes you've set the POD_NAMESPACE environment variable using the downward API.
	// This check has to be done first for backwards compatibility with the way InClusterConfig was originally set up
	if ns := os.Getenv("POD_NAMESPACE"); ns != "" {
		return ns, true, nil
	}

	// Fall back to the namespace associated with the service account token, if available
	if data, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil {
		if ns := strings.TrimSpace(string(data)); len(ns) > 0 {
			return ns, true, nil
		}
	}

	return api.NamespaceDefault, false, nil
}

// ClientConfig returns a complete client config
func (c defaultingClientConfig) ClientConfig() (*kclient.Config, error) {
	cfg, err := c.nested.ClientConfig()
	if err == nil {
		return cfg, nil
	}

	if !kclientcmd.IsEmptyConfig(err) {
		return nil, err
	}

	// TODO: need to expose inClusterConfig upstream and use that
	if icc, err := kclient.InClusterConfig(); err == nil {
		glog.V(4).Infof("Using in-cluster configuration")
		return icc, nil
	}

	return nil, fmt.Errorf(`No configuration file found, please login or point to an existing file:

  1. Via the command-line flag --config
  2. Via the KUBECONFIG environment variable
  3. In your home directory as ~/.kube/config

To view or setup config directly use the 'config' command.`)
}

// Factory provides common options for OpenShift commands
type Factory struct {
	*cmdutil.Factory
	OpenShiftClientConfig kclientcmd.ClientConfig
	clients               *clientCache
}

func DefaultGenerators(cmdName string) map[string]kubectl.Generator {
	generators := map[string]map[string]kubectl.Generator{}
	generators["run"] = map[string]kubectl.Generator{
		"run/v1":            deploygen.BasicDeploymentConfigController{},
		"run-controller/v1": kubectl.BasicReplicationController{},
	}
	generators["expose"] = map[string]kubectl.Generator{
		"route/v1": routegen.RouteGenerator{},
	}

	return generators[cmdName]
}

// NewFactory creates an object that holds common methods across all OpenShift commands
func NewFactory(clientConfig kclientcmd.ClientConfig) *Factory {
	var restMapper meta.MultiRESTMapper
	seenGroups := sets.String{}
	for _, gv := range registered.EnabledVersions() {
		if seenGroups.Has(gv.Group) {
			continue
		}
		seenGroups.Insert(gv.Group)

		groupMeta, err := registered.Group(gv.Group)
		if err != nil {
			continue
		}
		restMapper = meta.MultiRESTMapper(append(restMapper, groupMeta.RESTMapper))
	}
	mapper := ShortcutExpander{RESTMapper: kubectl.ShortcutExpander{RESTMapper: restMapper}}

	clients := &clientCache{
		clients: make(map[string]*client.Client),
		configs: make(map[string]*kclient.Config),
		loader:  clientConfig,
	}

	w := &Factory{
		Factory:               cmdutil.NewFactory(clientConfig),
		OpenShiftClientConfig: clientConfig,
		clients:               clients,
	}

	w.Object = func() (meta.RESTMapper, runtime.ObjectTyper) {
		// Output using whatever version was negotiated in the client cache. The
		// version we decode with may not be the same as what the server requires.
		if cfg, err := clients.ClientConfigForVersion(nil); err == nil {
			cmdApiVersion := unversioned.GroupVersion{}
			if cfg.GroupVersion != nil {
				cmdApiVersion = *cfg.GroupVersion
			}
			return kubectl.OutputVersionMapper{RESTMapper: mapper, OutputVersions: []unversioned.GroupVersion{cmdApiVersion}}, api.Scheme
		}
		return mapper, api.Scheme
	}

	kClientForMapping := w.Factory.ClientForMapping
	w.ClientForMapping = func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
		if latest.OriginKind(mapping.GroupVersionKind) {
			mappingVersion := mapping.GroupVersionKind.GroupVersion()
			client, err := clients.ClientForVersion(&mappingVersion)
			if err != nil {
				return nil, err
			}
			return client.RESTClient, nil
		}
		return kClientForMapping(mapping)
	}

	// Save original Describer function
	kDescriberFunc := w.Factory.Describer
	w.Describer = func(mapping *meta.RESTMapping) (kubectl.Describer, error) {
		if latest.OriginKind(mapping.GroupVersionKind) {
			oClient, kClient, err := w.Clients()
			if err != nil {
				return nil, fmt.Errorf("unable to create client %s: %v", mapping.GroupVersionKind.Kind, err)
			}

			mappingVersion := mapping.GroupVersionKind.GroupVersion()
			cfg, err := clients.ClientConfigForVersion(&mappingVersion)
			if err != nil {
				return nil, fmt.Errorf("unable to load a client %s: %v", mapping.GroupVersionKind.Kind, err)
			}

			describer, ok := describe.DescriberFor(mapping.GroupVersionKind.GroupKind(), oClient, kClient, cfg.Host)
			if !ok {
				return nil, fmt.Errorf("no description has been implemented for %q", mapping.GroupVersionKind.Kind)
			}
			return describer, nil
		}
		return kDescriberFunc(mapping)
	}
	kScalerFunc := w.Factory.Scaler
	w.Scaler = func(mapping *meta.RESTMapping) (kubectl.Scaler, error) {
		oc, kc, err := w.Clients()
		if err != nil {
			return nil, err
		}

		if mapping.GroupVersionKind.GroupKind() == deployapi.Kind("DeploymentConfig") {
			return deployscaler.NewDeploymentConfigScaler(oc, kc), nil
		}
		return kScalerFunc(mapping)
	}
	kReaperFunc := w.Factory.Reaper
	w.Reaper = func(mapping *meta.RESTMapping) (kubectl.Reaper, error) {
		oc, kc, err := w.Clients()
		if err != nil {
			return nil, err
		}

		switch mapping.GroupVersionKind.GroupKind() {
		case deployapi.Kind("DeploymentConfig"):
			return deployreaper.NewDeploymentConfigReaper(oc, kc), nil
		case authorizationapi.Kind("Role"):
			return authorizationreaper.NewRoleReaper(oc, oc), nil
		case authorizationapi.Kind("ClusterRole"):
			return authorizationreaper.NewClusterRoleReaper(oc, oc, oc), nil
		case userapi.Kind("User"):
			return authenticationreaper.NewUserReaper(
				client.UsersInterface(oc),
				client.GroupsInterface(oc),
				client.ClusterRoleBindingsInterface(oc),
				client.RoleBindingsNamespacer(oc),
				kclient.SecurityContextConstraintsInterface(kc),
			), nil
		case userapi.Kind("Group"):
			return authenticationreaper.NewGroupReaper(
				client.GroupsInterface(oc),
				client.ClusterRoleBindingsInterface(oc),
				client.RoleBindingsNamespacer(oc),
				kclient.SecurityContextConstraintsInterface(kc),
			), nil
		case buildapi.Kind("BuildConfig"):
			return buildreaper.NewBuildConfigReaper(oc), nil
		}
		return kReaperFunc(mapping)
	}
	kGenerators := w.Factory.Generators
	w.Generators = func(cmdName string) map[string]kubectl.Generator {
		originGenerators := DefaultGenerators(cmdName)
		kubeGenerators := kGenerators(cmdName)

		ret := map[string]kubectl.Generator{}
		for k, v := range kubeGenerators {
			ret[k] = v
		}
		for k, v := range originGenerators {
			ret[k] = v
		}
		return ret
	}
	kPodSelectorForObjectFunc := w.Factory.PodSelectorForObject
	w.PodSelectorForObject = func(object runtime.Object) (string, error) {
		switch t := object.(type) {
		case *deployapi.DeploymentConfig:
			return kubectl.MakeLabels(t.Spec.Selector), nil
		default:
			return kPodSelectorForObjectFunc(object)
		}
	}

	kMapBasedSelectorForObjectFunc := w.Factory.MapBasedSelectorForObject
	w.MapBasedSelectorForObject = func(object runtime.Object) (string, error) {
		switch t := object.(type) {
		case *deployapi.DeploymentConfig:
			return kubectl.MakeLabels(t.Spec.Selector), nil
		default:
			return kMapBasedSelectorForObjectFunc(object)
		}

	}

	kPortsForObjectFunc := w.Factory.PortsForObject
	w.PortsForObject = func(object runtime.Object) ([]string, error) {
		switch t := object.(type) {
		case *deployapi.DeploymentConfig:
			return getPorts(t.Spec.Template.Spec), nil
		default:
			return kPortsForObjectFunc(object)
		}
	}
	kLogsForObjectFunc := w.Factory.LogsForObject
	w.LogsForObject = func(object, options runtime.Object) (*kclient.Request, error) {
		oc, _, err := w.Clients()
		if err != nil {
			return nil, err
		}

		switch t := object.(type) {
		case *deployapi.DeploymentConfig:
			dopts, ok := options.(*deployapi.DeploymentLogOptions)
			if !ok {
				return nil, errors.New("provided options object is not a DeploymentLogOptions")
			}
			return oc.DeploymentLogs(t.Namespace).Get(t.Name, *dopts), nil
		case *buildapi.Build:
			bopts, ok := options.(*buildapi.BuildLogOptions)
			if !ok {
				return nil, errors.New("provided options object is not a BuildLogOptions")
			}
			if bopts.Version != nil {
				return nil, errors.New("cannot specify a version and a build")
			}
			return oc.BuildLogs(t.Namespace).Get(t.Name, *bopts), nil
		case *buildapi.BuildConfig:
			bopts, ok := options.(*buildapi.BuildLogOptions)
			if !ok {
				return nil, errors.New("provided options object is not a BuildLogOptions")
			}
			builds, err := oc.Builds(t.Namespace).List(api.ListOptions{})
			if err != nil {
				return nil, err
			}
			builds.Items = buildapi.FilterBuilds(builds.Items, buildapi.ByBuildConfigLabelPredicate(t.Name))
			if len(builds.Items) == 0 {
				return nil, fmt.Errorf("no builds found for %q", t.Name)
			}
			if bopts.Version != nil {
				// If a version has been specified, try to get the logs from that build.
				desired := buildutil.BuildNameForConfigVersion(t.Name, int(*bopts.Version))
				return oc.BuildLogs(t.Namespace).Get(desired, *bopts), nil
			}
			sort.Sort(sort.Reverse(buildapi.BuildSliceByCreationTimestamp(builds.Items)))
			return oc.BuildLogs(t.Namespace).Get(builds.Items[0].Name, *bopts), nil
		default:
			return kLogsForObjectFunc(object, options)
		}
	}
	w.Printer = func(mapping *meta.RESTMapping, noHeaders, withNamespace, wide bool, showAll bool, showLabels, absoluteTimestamps bool, columnLabels []string) (kubectl.ResourcePrinter, error) {
		return describe.NewHumanReadablePrinter(noHeaders, withNamespace, wide, showAll, showLabels, absoluteTimestamps, columnLabels), nil
	}
	kCanBeExposed := w.Factory.CanBeExposed
	w.CanBeExposed = func(kind unversioned.GroupKind) error {
		if kind == deployapi.Kind("DeploymentConfig") {
			return nil
		}
		return kCanBeExposed(kind)
	}
	kCanBeAutoscaled := w.Factory.CanBeAutoscaled
	w.CanBeAutoscaled = func(kind unversioned.GroupKind) error {
		if kind == deployapi.Kind("DeploymentConfig") {
			return nil
		}
		return kCanBeAutoscaled(kind)
	}
	kAttachablePodForObjectFunc := w.Factory.AttachablePodForObject
	w.AttachablePodForObject = func(object runtime.Object) (*api.Pod, error) {
		oc, kc, err := w.Clients()
		if err != nil {
			return nil, err
		}
		switch t := object.(type) {
		case *deployapi.DeploymentConfig:
			var err error
			var pods *api.PodList
			for pods == nil || len(pods.Items) == 0 {
				if t.Status.LatestVersion == 0 {
					time.Sleep(2 * time.Second)
				}
				if t, err = oc.DeploymentConfigs(t.Namespace).Get(t.Name); err != nil {
					return nil, err
				}
				latestDeploymentName := deployutil.LatestDeploymentNameForConfig(t)
				deployment, err := kc.ReplicationControllers(t.Namespace).Get(latestDeploymentName)
				if err != nil {
					if kerrors.IsNotFound(err) {
						continue
					}
					return nil, err
				}
				pods, err = kc.Pods(deployment.Namespace).List(api.ListOptions{LabelSelector: labels.SelectorFromSet(deployment.Spec.Selector)})
				if err != nil {
					return nil, err
				}
				if len(pods.Items) == 0 {
					time.Sleep(2 * time.Second)
				}
			}
			var oldestPod *api.Pod
			for i := range pods.Items {
				pod := &pods.Items[i]
				if oldestPod == nil || pod.CreationTimestamp.Before(oldestPod.CreationTimestamp) {
					oldestPod = pod
				}
			}
			return oldestPod, nil
		default:
			return kAttachablePodForObjectFunc(object)
		}
	}
	kSwaggerSchemaFunc := w.Factory.SwaggerSchema
	w.Factory.SwaggerSchema = func(gvk unversioned.GroupVersionKind) (*swagger.ApiDeclaration, error) {
		if !latest.OriginKind(gvk) {
			return kSwaggerSchemaFunc(gvk)
		}
		// TODO: we need to register the OpenShift API under the Kube group, and start returning the OpenShift
		// group from the scheme.
		oc, _, err := w.Clients()
		if err != nil {
			return nil, err
		}
		return w.OriginSwaggerSchema(oc.RESTClient, gvk.GroupVersion())
	}

	w.EditorEnvs = func() []string {
		return []string{"OC_EDITOR", "EDITOR"}
	}

	return w
}

func getPorts(spec api.PodSpec) []string {
	result := []string{}
	for _, container := range spec.Containers {
		for _, port := range container.Ports {
			result = append(result, strconv.Itoa(port.ContainerPort))
		}
	}
	return result
}

// UpdatePodSpecForObject update the pod specification for the provided object
// TODO: move to upstream
func (f *Factory) UpdatePodSpecForObject(obj runtime.Object, fn func(*api.PodSpec) error) (bool, error) {
	// TODO: replace with a swagger schema based approach (identify pod template via schema introspection)
	switch t := obj.(type) {
	case *api.Pod:
		return true, fn(&t.Spec)
	case *api.PodTemplate:
		return true, fn(&t.Template.Spec)
	case *api.ReplicationController:
		if t.Spec.Template == nil {
			t.Spec.Template = &api.PodTemplateSpec{}
		}
		return true, fn(&t.Spec.Template.Spec)
	case *deployapi.DeploymentConfig:
		template := t.Spec.Template
		if template == nil {
			template = &api.PodTemplateSpec{}
		}
		return true, fn(&template.Spec)
	default:
		return false, fmt.Errorf("the object is not a pod or does not have a pod template")
	}
}

// ApproximatePodTemplateForObject returns a pod template object for the provided source.
// It may return both an error and a object. It attempt to return the best possible template
// avaliable at the current time.
func (w *Factory) ApproximatePodTemplateForObject(object runtime.Object) (*api.PodTemplateSpec, error) {
	switch t := object.(type) {
	case *deployapi.DeploymentConfig:
		fallback := t.Spec.Template

		_, kc, err := w.Clients()
		if err != nil {
			return fallback, err
		}

		latestDeploymentName := deployutil.LatestDeploymentNameForConfig(t)
		deployment, err := kc.ReplicationControllers(t.Namespace).Get(latestDeploymentName)
		if err != nil {
			return fallback, err
		}

		fallback = deployment.Spec.Template

		pods, err := kc.Pods(deployment.Namespace).List(api.ListOptions{LabelSelector: labels.SelectorFromSet(deployment.Spec.Selector)})
		if err != nil {
			return fallback, err
		}

		for i := range pods.Items {
			pod := &pods.Items[i]
			if fallback == nil || pod.CreationTimestamp.Before(fallback.CreationTimestamp) {
				fallback = &api.PodTemplateSpec{
					ObjectMeta: pod.ObjectMeta,
					Spec:       pod.Spec,
				}
			}
		}
		return fallback, nil

	default:
		pod, err := w.AttachablePodForObject(object)
		if pod != nil {
			return &api.PodTemplateSpec{
				ObjectMeta: pod.ObjectMeta,
				Spec:       pod.Spec,
			}, err
		}
		return nil, err
	}
}

// Clients returns an OpenShift and Kubernetes client.
func (f *Factory) Clients() (*client.Client, *kclient.Client, error) {
	kClient, err := f.Client()
	if err != nil {
		return nil, nil, err
	}
	osClient, err := f.clients.ClientForVersion(nil)
	if err != nil {
		return nil, nil, err
	}
	return osClient, kClient, nil
}

// OriginSwaggerSchema returns a swagger API doc for an Origin schema under the /oapi prefix.
func (f *Factory) OriginSwaggerSchema(client *kclient.RESTClient, version unversioned.GroupVersion) (*swagger.ApiDeclaration, error) {
	if version.IsEmpty() {
		return nil, fmt.Errorf("groupVersion cannot be empty")
	}
	body, err := client.Get().AbsPath("/").Suffix("swaggerapi", "oapi", version.Version).Do().Raw()
	if err != nil {
		return nil, err
	}
	var schema swagger.ApiDeclaration
	err = json.Unmarshal(body, &schema)
	if err != nil {
		return nil, fmt.Errorf("got '%s': %v", string(body), err)
	}
	return &schema, nil
}

// ShortcutExpander is a RESTMapper that can be used for OpenShift resources.   It expands the resource first, then invokes the wrapped
type ShortcutExpander struct {
	RESTMapper meta.RESTMapper
}

var _ meta.RESTMapper = &ShortcutExpander{}

func (e ShortcutExpander) KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) {
	return e.RESTMapper.KindFor(expandResourceShortcut(resource))
}

func (e ShortcutExpander) KindsFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionKind, error) {
	return e.RESTMapper.KindsFor(expandResourceShortcut(resource))
}

func (e ShortcutExpander) ResourcesFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) {
	return e.RESTMapper.ResourcesFor(expandResourceShortcut(resource))
}

func (e ShortcutExpander) ResourceFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) {
	return e.RESTMapper.ResourceFor(expandResourceShortcut(resource))
}

func (e ShortcutExpander) ResourceIsValid(resource unversioned.GroupVersionResource) bool {
	return e.RESTMapper.ResourceIsValid(expandResourceShortcut(resource))
}

func (e ShortcutExpander) ResourceSingularizer(resource string) (string, error) {
	return e.RESTMapper.ResourceSingularizer(expandResourceShortcut(unversioned.GroupVersionResource{Resource: resource}).Resource)
}

func (e ShortcutExpander) RESTMapping(gk unversioned.GroupKind, versions ...string) (*meta.RESTMapping, error) {
	return e.RESTMapper.RESTMapping(gk, versions...)
}

// AliasesForResource returns whether a resource has an alias or not
func (e ShortcutExpander) AliasesForResource(resource string) ([]string, bool) {
	aliases := map[string][]string{
		"all": latest.UserResources,
	}

	if res, ok := aliases[resource]; ok {
		return res, true
	}
	return e.RESTMapper.AliasesForResource(expandResourceShortcut(unversioned.GroupVersionResource{Resource: resource}).Resource)
}

// shortForms is the list of short names to their expanded names
var shortForms = map[string]string{
	"dc":      "deploymentconfigs",
	"bc":      "buildconfigs",
	"is":      "imagestreams",
	"istag":   "imagestreamtags",
	"isimage": "imagestreamimages",
	"sa":      "serviceaccounts",
	"pv":      "persistentvolumes",
	"pvc":     "persistentvolumeclaims",
}

// expandResourceShortcut will return the expanded version of resource
// (something that a pkg/api/meta.RESTMapper can understand), if it is
// indeed a shortcut. Otherwise, will return resource unmodified.
func expandResourceShortcut(resource unversioned.GroupVersionResource) unversioned.GroupVersionResource {
	if expanded, ok := shortForms[resource.Resource]; ok {
		resource.Resource = expanded
		return resource
	}
	return resource
}

// clientCache caches previously loaded clients for reuse. This is largely
// copied from upstream (because of typing) but reuses the negotiation logic.
// TODO: Consolidate this entire concept with upstream's ClientCache.
type clientCache struct {
	loader        kclientcmd.ClientConfig
	clients       map[string]*client.Client
	configs       map[string]*kclient.Config
	defaultConfig *kclient.Config
	// negotiatingClient is used only for negotiating versions with the server.
	negotiatingClient *kclient.Client
}

// ClientConfigForVersion returns the correct config for a server
func (c *clientCache) ClientConfigForVersion(version *unversioned.GroupVersion) (*kclient.Config, error) {
	if c.defaultConfig == nil {
		config, err := c.loader.ClientConfig()
		if err != nil {
			return nil, err
		}
		c.defaultConfig = config
	}
	// TODO: have a better config copy method
	cacheKey := ""
	if version != nil {
		cacheKey = version.String()
	}
	if config, ok := c.configs[cacheKey]; ok {
		return config, nil
	}
	if c.negotiatingClient == nil {
		// TODO: We want to reuse the upstream negotiation logic, which is coupled
		// to a concrete kube Client. The negotiation will ultimately try and
		// build an unversioned URL using the config prefix to ask for supported
		// server versions. If we use the default kube client config, the prefix
		// will be /api, while we need to use the OpenShift prefix to ask for the
		// OpenShift server versions. For now, set OpenShift defaults on the
		// config to ensure the right prefix gets used. The client cache and
		// negotiation logic should be refactored upstream to support downstream
		// reuse so that we don't need to do any of this cache or negotiation
		// duplication.
		negotiatingConfig := *c.defaultConfig
		client.SetOpenShiftDefaults(&negotiatingConfig)
		negotiatingClient, err := kclient.New(&negotiatingConfig)
		if err != nil {
			return nil, err
		}
		c.negotiatingClient = negotiatingClient
	}
	config := *c.defaultConfig
	negotiatedVersion, err := negotiateVersion(c.negotiatingClient, &config, version, latest.Versions)
	if err != nil {
		return nil, err
	}
	config.GroupVersion = negotiatedVersion
	client.SetOpenShiftDefaults(&config)
	c.configs[cacheKey] = &config

	// `version` does not necessarily equal `config.Version`.  However, we know that we call this method again with
	// `config.Version`, we should get the the config we've just built.
	configCopy := config
	c.configs[config.GroupVersion.String()] = &configCopy

	return &config, nil
}

// ClientForVersion initializes or reuses a client for the specified version, or returns an
// error if that is not possible
func (c *clientCache) ClientForVersion(version *unversioned.GroupVersion) (*client.Client, error) {
	cacheKey := ""
	if version != nil {
		cacheKey = version.String()
	}
	if client, ok := c.clients[cacheKey]; ok {
		return client, nil
	}
	config, err := c.ClientConfigForVersion(version)
	if err != nil {
		return nil, err
	}
	client, err := client.New(config)
	if err != nil {
		return nil, err
	}

	c.clients[config.GroupVersion.String()] = client
	return client, nil
}


text:
<link href="/common_components/footer/footer.css" rel="stylesheet" type="text/css">

SUPERmarket by Peter Orsos

opeter94@gmail.com

Copyright © 2016