text:
import pyglet
from pyglet import gl

from widgets import Widget, Control, Label
from button import Button
from frame import Wrapper, Frame
from layout import GetRelativePoint, ANCHOR_CENTER
from layout import VerticalLayout, HorizontalLayout

class DialogEventManager(Control):
    def __init__(self):
        """
        Creates a new event manager for a dialog.

        @param content The Widget which we wrap
        """
        Control.__init__(self)
        self.controls = []
        self.control_areas = {}
        self.control_map = {}
        self.hover = None
        self.focus = None
        self.wheel_hint = None
        self.wheel_target = None

    def get_value(self, id):
        widget = self.get_widget(id)
        if widget is not None:
            return widget.get_value()

    def get_values(self):
        retval = {}
        for widget in self.controls:
            if widget.is_input() and widget.id is not None:
                retval[widget.id] = widget.get_value()
        return retval

    def get_widget(self, id):
        return self.control_map.get(id)

    def hit_control(self, x, y, control):
        left, right, top, bottom = self.control_areas[control]
        if x >= left and x < right and y >= bottom and y < top:
            return control.hit_test(x, y)
        else:
            return False

    def on_key_press(self, symbol, modifiers):
        """
        TAB and ENTER will move us between fields, holding shift will
        reverse the direction of our iteration.  We don't handle ESCAPE.
        Otherwise, we pass keys to our child elements.

        @param symbol Key pressed
        @param modifiers Modifiers for key press
        """
        if symbol in [pyglet.window.key.TAB, pyglet.window.key.ENTER]:
            focusable = [x for x in self.controls
                         if x.is_focusable() and not x.is_disabled()]
            if not focusable:
                return

            if modifiers & pyglet.window.key.MOD_SHIFT:
                dir = -1
            else:
                dir = 1

            if self.focus is not None and self.focus in focusable:
                index = focusable.index(self.focus)
            else:
                index = 0 - dir

            new_focus = focusable[(index + dir) % len(focusable)]
            self.set_focus(new_focus)
            new_focus.ensure_visible()

            # If we hit ENTER, and wrapped back to the first focusable,
            # pass the ENTER back so the Dialog can call its on_enter callback
            if symbol != pyglet.window.key.ENTER or \
               new_focus != focusable[0]:
                return pyglet.event.EVENT_HANDLED

        elif symbol != pyglet.window.key.ESCAPE:
            if self.focus is not None and hasattr(self.focus, 'on_key_press'):
                return self.focus.on_key_press(symbol, modifiers)

    def on_key_release(self, symbol, modifiers):
        """Pass key release events to the focus

        @param symbol Key released
        @param modifiers Modifiers for key released
        """
        if self.focus is not None and hasattr(self.focus, 'on_key_release'):
            return self.focus.on_key_release(symbol, modifiers)

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        """
        Handles mouse dragging.  If we have a focus, pass it in.

        @param x X coordinate of mouse
        @param y Y coordinate of mouse
        @param dx Delta X
        @param dy Delta Y
        @param buttons Buttons held while moving
        @param modifiers Modifiers to apply to buttons
        """
        if self.focus is not None:
            self.focus.dispatch_event('on_mouse_drag',
                                      x, y, dx, dy, buttons, modifiers)
            return pyglet.event.EVENT_HANDLED

    def on_mouse_motion(self, x, y, dx, dy):
        """
        Handles mouse motion.  We highlight controls that we are hovering
        over.

        @param x X coordinate of mouse
        @param y Y coordinate of mouse
        @param dx Delta X
        @param dy Delta Y
        """
        if self.hover is not None and not self.hit_control(x, y, self.hover):
            self.hover.dispatch_event('on_mouse_motion', x, y, dx, dy)
        new_hover = None
        for control in self.controls:
            if self.hit_control(x, y, control):
                new_hover = control
                break
        self.set_hover(new_hover)
        if self.hover is not None:
            self.hover.dispatch_event('on_mouse_motion', x, y, dx, dy)

    def on_mouse_press(self, x, y, button, modifiers):
        """
        If the focus is set, and the target lies within the focus, pass the
        message down.  Otherwise, check if we need to assign a new focus.
        If the mouse was pressed within our frame but no control was targeted,
        we may be setting up to drag the Dialog around.

        @param x X coordinate of mouse
        @param y Y coordinate of mouse
        @param button Button pressed
        @param modifiers Modifiers to apply to button
        """
        if self.focus is not None and self.hit_control(x, y, self.focus):
            self.focus.dispatch_event('on_mouse_press',
                                      x, y, button, modifiers)
            return pyglet.event.EVENT_HANDLED
        else:
            if self.hit_test(x, y):
                self.set_focus(self.hover)
                if self.focus is not None:
                    self.focus.dispatch_event('on_mouse_press',
                                              x, y, button, modifiers)
                    return pyglet.event.EVENT_HANDLED
            else:
                self.set_focus(None)

    def on_mouse_release(self, x, y, button, modifiers):
        """
        Button was released.  We pass this along to the focus, then we
        generate an on_mouse_motion to handle changing the highlighted
        Control if necessary.

        @param x X coordinate of mouse
        @param y Y coordinate of mouse
        @param button Button released
        @param modifiers Modifiers to apply to button
        """
        self.is_dragging = False
        if self.focus is not None:
            self.focus.dispatch_event('on_mouse_release',
                                      x, y, button, modifiers)
            return pyglet.event.EVENT_HANDLED # this eats input
        DialogEventManager.on_mouse_motion(self, x, y, 0, 0)

    def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
        """
        Mousewheel was scrolled.  See if we have a wheel target, or
        failing that, a wheel hint.

        @param x X coordinate of mouse
        @param y Y coordinate of mouse
        @param scroll_x Number of clicks horizontally mouse was moved
        @param scroll_y Number of clicks vertically mouse was moved
        """
        if self.wheel_target is not None and \
           self.wheel_target in self.controls:
            self.wheel_target.dispatch_event('on_mouse_scroll',
                                             x, y, scroll_x, scroll_y)
            return pyglet.event.EVENT_HANDLED
        elif self.wheel_hint is not None and \
             self.wheel_hint in self.controls:
            self.wheel_hint.dispatch_event('on_mouse_scroll',
                                           x, y, scroll_x, scroll_y)
            return pyglet.event.EVENT_HANDLED

    def on_text(self, text):
        if self.focus and text != u'\r':
            try:
                return getattr(self.focus, 'on_text')(text)
            except KeyError:
                return pyglet.event.EVENT_UNHANDLED

    def on_text_motion(self, motion):
        if self.focus:
            try:
                return getattr(self.focus, 'on_text_motion')(motion)
            except KeyError:
                return pyglet.event.EVENT_UNHANDLED

    def on_text_motion_select(self, motion):
        if self.focus:
            try:
                return getattr(self.focus, 'on_text_motion_select')(motion)
            except KeyError:
                return pyglet.event.EVENT_UNHANDLED

    def on_update(self, dt):
        """
        We update our layout only when it's time to construct another frame.
        Since we may receive several resize events within this time, this
        ensures we don't resize too often.

        @param dialog The Dialog containing the controls
        @param dt Time passed since last update event (in seconds)
        """
        for control in self.controls:
            control.dispatch_event('on_update', dt)

    def set_focus(self, focus):
        """
        Sets a new focus, dispatching lose and gain focus events appropriately

        @param focus The new focus, or None if no focus
        """
        if self.focus == focus:
            return
        if self.focus is not None:
            self.focus.dispatch_event('on_lose_focus')
        self.focus = focus
        if focus is not None:
            focus.dispatch_event('on_gain_focus')

    def set_hover(self, hover):
        """
        Sets a new highlight, dispatching lose and gain highlight events
        appropriately

        @param hover The new highlight, or None if no highlight
        """
        if self.hover == hover:
            return
        if self.hover is not None:
            self.hover.dispatch_event('on_lose_highlight')
        self.hover = hover
        if hover is not None:
            hover.dispatch_event('on_gain_highlight')

    def set_wheel_hint(self, control):
        self.wheel_hint = control

    def set_wheel_target(self, control):
        self.wheel_target = control

    def teardown(self):
        self.controls = []
        self.control_map = {}
        self.focus = None
        self.hover = None
        self.wheel_hint = None
        self.wheel_target = None

    def update_controls(self):
        """Update our list of controls which may respond to user input."""
        controls = self._get_controls()
        self.controls = []
        self.control_areas = {}
        self.control_map = {}
        for control, left, right, top, bottom in controls:
            self.controls.append(control)
            self.control_areas[control] = (left, right, top, bottom)
            if control.id is not None:
                self.control_map[control.id] = control

        if self.hover is not None and self.hover not in self.controls:
            self.set_hover(None)
        if self.focus is not None and self.focus not in self.controls:
            self.set_focus(None)

kytten_next_dialog_order_id = 0
def GetNextDialogOrderId():
    global kytten_next_dialog_order_id
    kytten_next_dialog_order_id += 1
    return kytten_next_dialog_order_id

class DialogGroup(pyglet.graphics.OrderedGroup):
    """
    Ensure that all Widgets within a Dialog can be drawn with
    blending enabled, and that our Dialog will be drawn in a particular
    order relative to other Dialogs.
    """
    def __init__(self, parent=None):
        """
        Creates a new DialogGroup.  By default we'll be on top.

        @param parent Parent group
        """
        pyglet.graphics.OrderedGroup.__init__(
            self, GetNextDialogOrderId(), parent)
        self.real_order = self.order

    def __cmp__(self, other):
        """
        When compared with other DialogGroups, we'll return our real order
        compared against theirs; otherwise use the OrderedGroup comparison.
        """
        if isinstance(other, DialogGroup):
            return cmp(self.real_order, other.real_order)
        else:
            return OrderedGroup.__cmp__(self, other)

    def is_on_top(self):
        """
        Are we the top dialog group?
        """
        global kytten_next_dialog_order_id
        return self.real_order == kytten_next_dialog_order_id

    def pop_to_top(self):
        """
        Put us on top of other dialog groups.
        """
        self.real_order = GetNextDialogOrderId()

    def set_state(self):
        """
        Ensure that blending is set.
        """
        gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT)
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

    def unset_state(self):
        """
        Restore previous blending state.
        """
        gl.glPopAttrib()

class Dialog(Wrapper, DialogEventManager):
    """
    Defines a new GUI.  By default it can contain only one element, but that
    element can be a Layout of some kind which can contain multiple elements.
    Pass a Theme in to set the graphic appearance of the Dialog.

    The Dialog is always repositioned in relationship to the window, and
    handles resize events accordingly.
    """
    def __init__(self, content=None, window=None, batch=None, group=None,
                 anchor=ANCHOR_CENTER, offset=(0, 0), parent=None,
                 theme=None, movable=True, on_enter=None, on_escape=None):
        """
        Creates a new dialog.

        @param content The Widget which we wrap
        @param window The window to which we belong; used to set the
                      mouse cursor when appropriate.  If set, we will
                      add ourself to the window as a handler.
        @param batch Batch in which we are to place our graphic elements;
                     may be None if we are to create our own Batch
        @param group Group in which we are to place our graphic elements;
                     may be None
        @param anchor Anchor point of the window, relative to which we
                      are positioned.  If ANCHOR_TOP_LEFT is specified,
                      our top left corner will be aligned to the window's
                      top left corner; if ANCHOR_CENTER is specified,
                      our center will be aligned to the window's center,
                      and so forth.
        @param offset Offset from the anchor point.  A positive X is always
                      to the right, a positive Y to the upward direction.
        @param theme The Theme which we are to use to generate our graphical
                     appearance.
        @param movable True if the dialog is able to be moved
        @param on_enter Callback for when user presses enter on the last
                        input within this dialog, i.e. form submit
        @param on_escape Callback for when user presses escape
        """
        assert isinstance(theme, dict)
        Wrapper.__init__(self, content=content)
        DialogEventManager.__init__(self)

        self.window = window
        self.anchor = anchor
        self.offset = offset
        self.theme = theme
        self.is_movable = movable
        self.on_enter = on_enter
        self.on_escape = on_escape
        if batch is None:
            self.batch = pyglet.graphics.Batch()
            self.own_batch = True
        else:
            self.batch = batch
            self.own_batch = False
        self.root_group = DialogGroup(parent=group)
        self.panel_group = pyglet.graphics.OrderedGroup(0, self.root_group)
        self.bg_group = pyglet.graphics.OrderedGroup(1, self.root_group)
        self.fg_group = pyglet.graphics.OrderedGroup(2, self.root_group)
        self.highlight_group = pyglet.graphics.OrderedGroup(3, self.root_group)
        self.needs_layout = True
        self.is_dragging = False

        if window is None:
            self.screen = Widget()
        else:
            width, height = window.get_size()
            self.screen = Widget(width=width, height=height)
            window.push_handlers(self)

    def do_layout(self):
        """
        We lay out the Dialog by first determining the size of all its
        chlid Widgets, then laying ourself out relative to the parent window.
        """
        # Determine size of all components
        self.size(self)

        # Calculate our position relative to our containing window,
        # making sure that we fit completely on the window.  If our offset
        # would send us off the screen, constrain it.
        x, y = GetRelativePoint(self.screen, self.anchor,
                                self, None, (0, 0))
        max_offset_x = self.screen.width - self.width - x
        max_offset_y = self.screen.height - self.height - y
        offset_x, offset_y = self.offset
        offset_x = max(min(offset_x, max_offset_x), -x)
        offset_y = max(min(offset_y, max_offset_y), -y)
        self.offset = (offset_x, offset_y)
        x += offset_x
        y += offset_y

        # Perform the actual layout now!
        self.layout(x, y)
        self.update_controls()

        self.needs_layout = False

    def draw(self):
        assert self.own_batch
        self.batch.draw()

    def ensure_visible(self, control):
        """
        Ensure a control is visible.  For Dialog, this doesn't matter
        since we don't scroll.
        """
        pass

    def get_root(self):
        return self

    def on_key_press(self, symbol, modifiers):
        """
        We intercept TAB, ENTER, and ESCAPE events.  TAB and ENTER will
        move us between fields, holding shift will reverse the direction
        of our iteration.  ESCAPE may cause us to send an on_escape
        callback.

        Otherwise, we pass key presses to our child elements.

        @param symbol Key pressed
        @param modifiers Modifiers for key press
        """
        retval = DialogEventManager.on_key_press(self, symbol, modifiers)
        if not retval:
            if symbol in [pyglet.window.key.TAB, pyglet.window.key.ENTER]:
                if self.on_enter is not None:
                    self.on_enter(self)
                    return pyglet.event.EVENT_HANDLED
            elif symbol == pyglet.window.key.ESCAPE:
                if self.on_escape is not None:
                    self.on_escape(self)
                    return pyglet.event.EVENT_HANDLED
        return retval

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        """
        Handles mouse dragging.  If we have a focus, pass it in.  Otherwise
        if we are movable, and we were being dragged, move the window.

        @param x X coordinate of mouse
        @param y Y coordinate of mouse
        @param dx Delta X
        @param dy Delta Y
        @param buttons Buttons held while moving
        @param modifiers Modifiers to apply to buttons
        """
        if not DialogEventManager.on_mouse_drag(self, x, y, dx, dy,
                                                buttons, modifiers):
            if self.is_movable and self.is_dragging:
                x, y = self.offset
                self.offset = (int(x + dx), int(y + dy))
                self.set_needs_layout()
                return pyglet.event.EVENT_HANDLED

    def on_mouse_press(self, x, y, button, modifiers):
        """
        If the focus is set, and the target lies within the focus, pass the
        message down.  Otherwise, check if we need to assign a new focus.
        If the mouse was pressed within our frame but no control was targeted,
        we may be setting up to drag the Dialog around.

        @param x X coordinate of mouse
        @param y Y coordinate of mouse
        @param button Button pressed
        @param modifiers Modifiers to apply to button
        """
        retval = DialogEventManager.on_mouse_press(self, x, y,
                                             button, modifiers)
        if self.hit_test(x, y):
            if not self.root_group.is_on_top():
                self.pop_to_top()
            if not retval:
                self.is_dragging = True
                retval = pyglet.event.EVENT_HANDLED
        return retval

    def on_mouse_release(self, x, y, button, modifiers):
        """
        Button was released.  We pass this along to the focus, then we
        generate an on_mouse_motion to handle changing the highlighted
        Control if necessary.

        @param x X coordinate of mouse
        @param y Y coordinate of mouse
        @param button Button released
        @param modifiers Modifiers to apply to button
        """
        self.is_dragging = False
        return DialogEventManager.on_mouse_release(self, x, y,
                                                   button, modifiers)

    def on_resize(self, width, height):
        """
        Update our knowledge of the window's width and height.

        @param width Width of the window
        @param height Height of the window
        """
        if self.screen.width != width or self.screen.height != height:
            self.screen.width, self.screen.height = width, height
            self.needs_layout = True

    def on_update(self, dt):
        """
        We update our layout only when it's time to construct another frame.
        Since we may receive several resize events within this time, this
        ensures we don't resize too often.

        @param dt Time passed since last update event (in seconds)
        """
        if self.needs_layout:
            self.do_layout()
        DialogEventManager.on_update(self, dt)

    def pop_to_top(self):
        """
        Pop our dialog group to the top, and force our batch to re-sort
        the groups.  Also, puts our event handler on top of the window's
        event handler stack.
        """
        self.root_group.pop_to_top()
        self.batch._draw_list_dirty = True  # forces resorting groups
        if self.window is not None:
            self.window.remove_handlers(self)
            self.window.push_handlers(self)

    def set_needs_layout(self):
        """
        True if we should redo the Dialog layout on our next update.
        """
        self.needs_layout = True

    def teardown(self):
        DialogEventManager.teardown(self)
        if self.content is not None:
            self.content.teardown()
            self.content = None
        if self.window is not None:
            self.window.remove_handlers(self)
            self.window = None
        self.batch._draw_list_dirty = True  # forces resorting groups

class PopupMessage(Dialog):
    """A simple fire-and-forget dialog."""

    def __init__(self, text="", window=None, batch=None, group=None,
                 theme=None, on_escape=None):
        def on_ok(dialog=None):
            if on_escape is not None:
                on_escape(self)
            self.teardown()

        return Dialog.__init__(self, content=Frame(
            VerticalLayout([
                Label(text),
                Button("Ok", on_click=on_ok),
            ])),
            window=window, batch=batch, group=group,
            theme=theme, movable=True,
            on_enter=on_ok, on_escape=on_ok)

class PopupConfirm(Dialog):
    """An ok/cancel-style dialog.  Escape defaults to cancel."""

    def __init__(self, text="", ok="Ok", cancel="Cancel",
                 window=None, batch=None, group=None, theme=None,
                 on_ok=None, on_cancel=None):
        def on_ok_click(dialog=None):
            if on_ok is not None:
                on_ok(self)
            self.teardown()

        def on_cancel_click(dialog=None):
            if on_cancel is not None:
                on_cancel(self)
            self.teardown()

        return Dialog.__init__(self, content=Frame(
            VerticalLayout([
                Label(text),
                HorizontalLayout([
                    Button(ok, on_click=on_ok_click),
                    None,
                    Button(cancel, on_click=on_cancel_click)
                ]),
            ])),
            window=window, batch=batch, group=group,
            theme=theme, movable=True,
            on_enter=on_ok_click, on_escape=on_cancel_click)


text:
package com.helger.photon.uicore.serverlog;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

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

import com.helger.commons.error.level.EErrorLevel;
import com.helger.commons.error.level.IErrorLevel;
import com.helger.commons.log.LogHelper;
import com.helger.commons.string.StringHelper;
import com.helger.photon.ajax.executor.IAjaxExecutor;
import com.helger.photon.app.PhotonUnifiedResponse;
import com.helger.web.scope.IRequestWebScopeWithoutResponse;

public class AjaxExecutorServerLog implements IAjaxExecutor
{
  private static final Logger LOGGER = LoggerFactory.getLogger (AjaxExecutorServerLog.class);
  private static final IErrorLevel DEFAULT_SEVERITY = EErrorLevel.INFO;
  private static final String PARAM_SEVERITY = "severity";
  private static final String PARAM_MESSAGE = "message";
  private static final String PARAM_KEY = "key";

  @Nonnull
  public static IErrorLevel getErrorLevelFromString (@Nullable final String sSeverity)
  {
    if (StringHelper.hasText (sSeverity))
    {
      if ("fatal".equalsIgnoreCase (sSeverity))
        return EErrorLevel.FATAL_ERROR;
      if ("error".equalsIgnoreCase (sSeverity))
        return EErrorLevel.ERROR;
      if ("warn".equalsIgnoreCase (sSeverity) || "warning".equalsIgnoreCase (sSeverity))
        return EErrorLevel.WARN;
      if ("info".equalsIgnoreCase (sSeverity))
        return EErrorLevel.INFO;
      if ("success".equalsIgnoreCase (sSeverity) || "debug".equalsIgnoreCase (sSeverity) || "trace".equalsIgnoreCase (sSeverity))
        return EErrorLevel.SUCCESS;
    }
    return DEFAULT_SEVERITY;
  }

  public void handleRequest (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope,
                             @Nonnull final PhotonUnifiedResponse aAjaxResponse) throws Exception
  {
    final String sSeverity = aRequestScope.params ().getAsString (PARAM_SEVERITY);
    final String sMessage = aRequestScope.params ().getAsString (PARAM_MESSAGE);
    final String sKey = aRequestScope.params ().getAsString (PARAM_KEY);
    final String sExpectedKey = ServerLogSessionKey.getGeneratedSessionKey ();
    if (StringHelper.hasNoText (sMessage) || sExpectedKey == null || !sExpectedKey.equals (sKey))
    {
      LOGGER.error ("Missing required parameter");
      aAjaxResponse.createBadRequest ();
      return;
    }

    // Main logging
    final IErrorLevel aSeverity = getErrorLevelFromString (sSeverity);
    LogHelper.log (AjaxExecutorServerLog.class, aSeverity, sMessage);
    aAjaxResponse.jsonEmpty ();
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite verbose="0" name="Failed suite [Command line suite]">
  <test name="Command line test(failed)">
    <classes>
      <class name="cmc.ps.test.service.TransitiveClosureServiceTest">
        <methods>
          <include name="springTestContextAfterTestClass"/>
          <include name="springTestContextBeforeTestClass"/>
          <include name="springTestContextBeforeTestMethod"/>
          <include name="transitiveClosureTest"/>
          <include name="beforeTest"/>
          <include name="springTestContextPrepareTestInstance"/>
          <include name="springTestContextAfterTestMethod"/>
        </methods>
      </class> <!-- cmc.ps.test.service.TransitiveClosureServiceTest -->
      <class name="cmc.ps.test.service.OwnerServiceTest">
        <methods>
          <include name="springTestContextAfterTestClass"/>
          <include name="springTestContextBeforeTestClass"/>
          <include name="setUp"/>
          <include name="springTestContextBeforeTestMethod"/>
          <include name="springTestContextPrepareTestInstance"/>
          <include name="springTestContextAfterTestMethod"/>
        </methods>
      </class> <!-- cmc.ps.test.service.OwnerServiceTest -->
      <class name="cmc.ps.test.service.HistoryServiceTest">
        <methods>
          <include name="springTestContextAfterTestClass"/>
          <include name="springTestContextBeforeTestClass"/>
          <include name="springTestContextBeforeTestMethod"/>
          <include name="springTestContextPrepareTestInstance"/>
          <include name="springTestContextAfterTestMethod"/>
          <include name="setUp"/>
        </methods>
      </class> <!-- cmc.ps.test.service.HistoryServiceTest -->
      <class name="cmc.ps.test.service.BusinessServiceTest">
        <methods>
          <include name="springTestContextAfterTestClass"/>
          <include name="setUp"/>
          <include name="springTestContextBeforeTestClass"/>
          <include name="springTestContextBeforeTestMethod"/>
          <include name="springTestContextPrepareTestInstance"/>
          <include name="springTestContextAfterTestMethod"/>
        </methods>
      </class> <!-- cmc.ps.test.service.BusinessServiceTest -->
      <class name="cmc.ps.test.service.LegalEntityServiceTest">
        <methods>
          <include name="springTestContextAfterTestClass"/>
          <include name="springTestContextBeforeTestClass"/>
          <include name="setUp"/>
          <include name="springTestContextBeforeTestMethod"/>
          <include name="springTestContextPrepareTestInstance"/>
          <include name="springTestContextAfterTestMethod"/>
        </methods>
      </class> <!-- cmc.ps.test.service.LegalEntityServiceTest -->
      <class name="cmc.ps.test.service.PhysicalPersonServiceTest">
        <methods>
          <include name="springTestContextAfterTestClass"/>
          <include name="springTestContextBeforeTestClass"/>
          <include name="springTestContextBeforeTestMethod"/>
          <include name="springTestContextPrepareTestInstance"/>
          <include name="springTestContextAfterTestMethod"/>
          <include name="setUp"/>
        </methods>
      </class> <!-- cmc.ps.test.service.PhysicalPersonServiceTest -->
    </classes>
  </test> <!-- Command line test(failed) -->
</suite> <!-- Failed suite [Command line suite] -->


text:
ActiveRecord::Schema.define(:version => 20140611153231) do

  create_table "admin_users", :force => true do |t|
    t.string   "email",                  :default => "", :null => false
    t.string   "encrypted_password",     :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          :default => 0,  :null => false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
  end

  add_index "admin_users", ["email"], :name => "index_admin_users_on_email", :unique => true
  add_index "admin_users", ["reset_password_token"], :name => "index_admin_users_on_reset_password_token", :unique => true

  create_table "article_translations", :force => true do |t|
    t.integer  "article_id"
    t.string   "locale",     :null => false
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.string   "title"
    t.text     "body"
  end

  add_index "article_translations", ["article_id"], :name => "index_article_translations_on_article_id"
  add_index "article_translations", ["locale"], :name => "index_article_translations_on_locale"

  create_table "articles", :force => true do |t|
    t.string   "title"
    t.text     "body"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

end


text:
package net.ssehub.easy.instantiation.core.model.defaultInstantiators;

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

import net.ssehub.easy.instantiation.core.model.artifactModel.FileArtifact;
import net.ssehub.easy.instantiation.core.model.artifactModel.Path;
import net.ssehub.easy.instantiation.core.model.common.VilException;
import net.ssehub.easy.instantiation.core.model.vilTypes.IVilType;
import net.ssehub.easy.instantiation.core.model.vilTypes.Instantiator;
import net.ssehub.easy.instantiation.core.model.vilTypes.Invisible;
import net.ssehub.easy.instantiation.core.model.vilTypes.OperationMeta;
import net.ssehub.easy.instantiation.core.model.vilTypes.Set;

/**
 * Unpacks ZIP files.
 *
 * @author Holger Eichelberger
 * @author kroeher
 */
@Instantiator("unzip")
public class Unzip implements IVilType {

    /**
     * Unpacks files in zip into target.
     *
     * @param zip the ZIP file to be unpacked
     * @param target the target path to unpack to
     * @return the created artifacts
     * @throws VilException in case of unpacking problems
     */
    @OperationMeta(returnGenerics = FileArtifact.class)
    public static Set<FileArtifact> unzip(Path zip, Path target) throws VilException {
        return unpack(zip, target, new ZipHandler());
    }

    /**
     * Unpacks files in zip into target.
     *
     * @param zip the ZIP file to be unpacked
     * @param target the target path to unpack to
     * @param handler the ZIP/JAR handler
     * @return the created artifacts
     * @throws VilException in case of unpacking problems
     */
    @Invisible
    public static Set<FileArtifact> unpack(Path zip, Path target, ZipHandler handler) throws VilException {
        List<File> files = new ArrayList<File>();
        try {
            handler.unpack(zip.getAbsolutePath(), target.getAbsolutePath(), null, files);
        } catch (IOException e) {
            throw new VilException(e, VilException.ID_IO);
        }
        return Zip.toFileArtifactSet(files, target.getArtifactModel());
    }

    /**
     * Unpacks files in zip that matches the given
     * filter into target.
     *
     * @param zip the ZIP file to be unpacked
     * @param target the target path to unpack to
     * @param pattern an optional ANT pattern used as a filter expression, typically a specific folder or package.
     *   May be null if no filter is required.
     * @param handler the ZIP/JAR handler
     * @return the created artifacts
     * @throws VilException in case of unpacking problems
     */
    @Invisible
    public static Set<FileArtifact> unpack(Path zip, Path target, String pattern, ZipHandler handler)
        throws VilException {
        List<File> files = new ArrayList<File>();
        try {
            handler.unpack(zip.getAbsolutePath(), target.getAbsolutePath(), pattern, files);
        } catch (IOException e) {
            throw new VilException(e, VilException.ID_IO);
        }
        return Zip.toFileArtifactSet(files, target.getArtifactModel());
    }

}


text:
"""
Akshay Tambe
Pachter and Doudna groups
UC Berkeley

Dropseq_utils.py
A few useful objects for working with single-cell barcode
data as de Bruijn graphs
"""
import sys
import numpy as np

class Edge:
	"""
	An edge in a de Bruijn graph
	Attributes
		node (string)
		neighbor (string)
		weight (float)
	To be a valid edge, all the nucleotides in node and neighbor must
		be the same, except for the first nt of the node /
		last nt of the edge
	"""
	def __init__(self, _node, _neighbor, _weight):
		self.node = _node
		self.neighbor = _neighbor
		self.weight = _weight
		assert (self.is_valid_edge()), \
			print('Not a valid edge: %s\t%s' % (self.node, self.neighbor))

	def get_name(self):
		"""
		Returns a tuple (node, neighbor) for this edge
		"""
		return(self.node, self.neighbor)

	def get_weight(self):
		return self.weight

	def get_sequence(self):
		return(self.node[0] + self.neighbor)

	def is_valid_edge(self):
		return(
			(self.node[1:] == self.neighbor[0:-1]) and \
			(self.weight >= 0.0))

	def is_self_edge(self):
		""""
		Returns true if node and neigobor are the same
		"""
		return(self.node == self.neighbor)

class Path:
	"""
	A path through a de Bruijn graph
	Attributes
		edges (list): a list of Edge objects

	To be a valid path, edges[i].node must be equal to edges[i-1].neighbor
		for all entries in self.edges
	"""
	def __init__(self, _edges):
		self.edges = _edges
		assert (self.is_valid_path()), \
			print('Not a valid path\n%s' % self.get_nodes_ordered())

	def get_weight(self):
		"""
		Returns float
			the weight of the lowest-weight edge
		"""
		return(self.get_lowest_weight_edge().get_weight())

	def get_cycle_weight(self):
		"""
		Returns float
			0 if the path is not a cycle
			the path weight otherwise
		"""
		if(not self.is_cycle()):
			return 0.0
		else:
			return self.get_weight()

	def get_lowest_weight_edge(self):
		return(
			min(self.edges,
			key = lambda edge: edge.get_weight()))

	def get_sequence(self):
		edges = self.edges
		seq = ''
		seq = (edges[0]).node
		for edge in edges[1:]:
			seq += (edge.node)[-1]
		return seq

	def get_sequence_circular(self):
		"""
		Gets the sequence for a cycle by starting at a node beginning with '$'
		"""
		seq = self.get_sequence()
		if(not self.is_cycle()):
			return seq

		start_ind = 0
		if('$' in seq):
			start_ind = seq.index('$') + 1
		seq_len = self.get_length() - 1
		seq = seq[start_ind:] + seq[0:start_ind]
		return(seq[0:seq_len])

	def get_start_node(self):
		return self.edges[0].node

	def get_end_node(self):
		return self.edges[-1].neighbor

	def get_nodes_ordered(self):
		nodes = [edge.node for edge in self.edges]
		if(not self.is_cycle()):
			nodes.append(self.edges[-1].neighbor)
		return sorted(nodes)

	def get_length(self):
		return len(self.edges)

	def is_cycle(self):
		return (self.get_start_node() == self.get_end_node())

	def is_valid_path(self):
		if(len(self.edges) == 1):
			return True
		for i in range(0, len(self.edges) - 1):
			neighbor = self.edges[i].neighbor
			next_node = self.edges[i+1].node
			if(neighbor != next_node):
				print(neighbor, next_node)
				return False
		return True

	def is_possible_cycle(self, cycle_length):
		"""
		Returns whether this path might be part of a cycle of fixed length
			If path_length > (cycle_length - kmer_size) there is some substring
			that is shared between the last position(s) of the path's end node and
			the first position(s) of its start node
		"""
		kmer_size = len(self.get_start_node())
		if(self.get_length() < (cycle_length - kmer_size)):
			return True
		if(self.is_cycle()):
			return True

		overlap = self.get_length() - (cycle_length - kmer_size)
		if((self.get_start_node()[0:overlap]) ==
				(self.get_end_node()[kmer_size - overlap:])):
			return True
		return False

class Graph:
	def __init__(self, _edges_lst):
		#create dict of edge objects
		self.edges = {}
		self.self_edges = {}
		for edge in _edges_lst:
			if(edge.is_self_edge()):
				key = edge.node
				self.self_edges[key] = edge
			else:
				key = edge.get_name()
				self.edges[key] = edge

	def get_num_edges(self):
		return(
			len(self.edges.values()) + \
			len(self.self_edges.values()))

	def get_total_weight(self):
		total_weight = sum( \
				[edge.get_weight() for edge in self.edges.values()]) + \
			sum( \
				[edge.get_weight() for edge in self.self_edges.values()])
		return total_weight

	def get_edges_sorted(self):
		edges_list = sorted(
			self.edges.values(),
			key = lambda edge: edge.get_weight(),
			reverse=True)
		return edges_list

	def get_outgoing_edges(self, node):
		alphabet = ['A', 'C', 'G', 'T', '$']
		outgoing_edges = []
		for a in alphabet:
			neighbor = ''.join([node[1:] + a])
			key = (node, neighbor)
			if(key in self.edges):
				outgoing_edges.append(self.edges[key])
		return outgoing_edges

	def get_outgoing_edges_sorted(self, node):
		return sorted(
			self.get_outgoing_edges(node),
			key = lambda edge: edge.get_weight(),
			reverse = True)#sorted by edge weight (descending)]

	def find_cyclic_path(self, current_path, expected_path_length):
		"""
		Args
			current_path (Path):
				a Path (of variable length)
			expected_path_length (int):
				length of cycles to look for (# edges in cyclic path)
		Returns
			Cycle (boolean): whether or not a cycle was found
			Path (Path): a path object representing the best path

		Recursively finds high-weight cyclic paths of fixed length
			Initialize by passing a path of length 1 (a single edge)
			Recursion terminates if:
				If current path length is larger than expected path length
				If current path cannot be a cycle of expected length
				If current path is a cycle of expected length
			Otherwise recursively:
				Return highest weight cyclic path from each outgoing node

		This recursion has a fixed upper bound for branching. For any starting edge,
			The total number of possible paths is given by:
				4**(expected_path_length - kmer_size)
		"""
		#check if path is too long (fail condition)
		if(current_path.get_length() > expected_path_length + 1):
			return(False, current_path)
		#check that this path is possibly part of a cycle (fail condition)
		if(not current_path.is_possible_cycle(expected_path_length)):
			return(False, current_path)
		#check if path is a cycle of expected length (success condition)
		if(current_path.is_cycle() and
			np.fabs(current_path.get_length() - expected_path_length) <= 1):
			return(True, current_path)
		#check if path is a smaller cycle, and if so check for self edges
		if(current_path.is_cycle() and
			current_path.get_length() < expected_path_length):

			(possible_self_edges,
				updated_path) = self.check_possible_self_edges(
				current_path,
				expected_path_length)
			if(not possible_self_edges):
				return(False, current_path)
			else:
				return(True, updated_path)

		#else return best cycle of all outgoing edges (continue recursion)
		current_node = current_path.get_end_node()
		outgoing_edges = self.get_outgoing_edges_sorted(current_node)
		#outgoing_edges is sorted in descending order by weight
		if(len(outgoing_edges) == 0):
			return (False, current_path)
		best_path = current_path
		for (i, outgoing_edge) in enumerate(outgoing_edges):
			downstream_path = Path(current_path.edges + [outgoing_edge])
			is_cycle, path = self.find_cyclic_path(
				downstream_path,
				expected_path_length)
			if(path.get_cycle_weight() > best_path.get_cycle_weight()):
				best_path = path
			if(i < len(outgoing_edges) - 1 and \
				best_path.is_cycle() and \
				best_path.get_cycle_weight() > outgoing_edges[i+1].get_weight()):
				break
		return(best_path.is_cycle(), best_path)

	def check_possible_self_edges(self, current_path, expected_path_length):
		possible_self_edges = []
		for edge in current_path.edges:
			node = edge.node
			if(node in self.self_edges.keys()):
				self_edge = self.self_edges[node]
				possible_self_edges.append(self_edge)
		if(len(possible_self_edges) == 0):
			return (False, current_path)
		#else
		best_self_edge = max(
			possible_self_edges,
			key = lambda edge: edge.get_weight())
		num_self_edges_needed = expected_path_length - current_path.get_length()

		new_edges = []
		min_edge_weight = current_path.get_cycle_weight()
		for i in range(current_path.get_length()):
			this_edge = current_path.edges[i]
			if(this_edge.node == best_self_edge.node):
				for j in range(num_self_edges_needed):
					new_edge = Edge(this_edge.node, this_edge.node, min_edge_weight)
					new_edges.append(new_edge)
			new_edges.append(this_edge)
		return (True, Path(new_edges))

	def find_all_cyclic_paths(self, start_node, start_neighbor, expected_path_length):
		key = (start_node, start_neighbor)
		if(key not in self.edges):
			raise StopIteration

		start_edge = self.edges[key]
		initial_path = Path([start_edge])
		while(True):
			cycle, path = self.find_cyclic_path(initial_path, expected_path_length)
			if(path.get_length() != expected_path_length):
				raise StopIteration
			elif(cycle):
				yield path
			#decrement edges in graph by cycle weight
			cycle_weight = path.get_cycle_weight()
			for edge in path.edges:
				key = edge.get_name()
				if(key in self.edges.keys()):
					self.edges[key].weight -= cycle_weight


text:
package cc.redpen.parser.latex;

import org.junit.Test;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.ArrayDeque;

import java.util.regex.Pattern;

import static org.junit.Assert.*;
import static cc.redpen.parser.latex.Tools.*;
import static cc.redpen.parser.latex.Assert.*;

import org.pegdown.ast.*;

public class ToolsTest {
    @Test
    public void testSummary() {
        final Node node = new RootNode();
        node.getChildren().add(new HeaderNode(1, new TextNode("First section")));

        assertEquals(
            "(RootNode (HeaderNode#1 (TextNode 'First section')))",
            summary(node));
    }

    /* <1>part,<2>chapter,<3>section,<4>subsection,<5>subsubsection */
    @Test
    public void testSummary2() {
        final Node node = new RootNode();
        node.getChildren().add(new HeaderNode(5));

        assertEquals(
            "(RootNode (HeaderNode#5 ()))",
            summary(node));
    }

    @Test
    public void testSummary3() {
        final Node node = new RootNode();
        node.getChildren().add(new SimpleNode(SimpleNode.Type.Linebreak));

        assertEquals(
            "(RootNode (SimpleNode#Linebreak))",
            summary(node));
    }
}


text:
name: closure-warnings/analyzer-checks
---

## Summary


text:
SYNONYM

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

#### Published in
Grevillea 21(no. 98): 37 (1892)

#### Original name
Bolbitius candidus Cooke & Massee, 1892

### Remarks
null


text:
Este é um exemplo de algoritmo para Smart Contracts utilizando a linguagem Solidity na plataforma Ethereum. Este exemplo faz parte da palestra "Desenvolvimento de Smart Contract - Um novo universo que surge";

Para executar:

- abra a IDE na WEB no endereço [1]
- faça o upload do arquivo `smart_contract`.
- Clique em `Publish` e `Create`
- Preencha o parâmetro da função `startShares` com o valor da cotação
- Clique em `startShares`

This is an example of an algorithm for Smart Contracts using the Solidity language on the Ethereum platform. This example is part of the talk "Development of Smart Contract - A new universe that arises"

To execute:

- open the WEB-IDE on address [1]
- upload the file `smart_contract`
- Click on `Publish` and `Create`
- Fill the function atribute `startShare` with quotation value
- Click on `startShares`

[1] http://ethereum.github.io/browser-solidity/


text:
MoonSharp Tutorials
===================

These are sources for the tutorials contained at http://www.moonsharp.org/getting_started.html and following pages.


text:
package com.alibaba.com.caucho.hessian.io;

import java.io.IOException;
import java.lang.reflect.Constructor;

/**
 * Deserializing a string valued object
 */
public class SqlDateDeserializer extends AbstractDeserializer {
  private Class _cl;
  private Constructor _constructor;

  public SqlDateDeserializer(Class cl)
    throws NoSuchMethodException
  {
    _cl = cl;
    _constructor = cl.getConstructor(new Class[] { long.class });
  }

  public Class getType()
  {
    return _cl;
  }

  public Object readMap(AbstractHessianInput in)
    throws IOException
  {
    int ref = in.addRef(null);

    long initValue = Long.MIN_VALUE;

    while (! in.isEnd()) {
      String key = in.readString();

      if (key.equals("value"))
	initValue = in.readUTCDate();
      else
	in.readString();
    }

    in.readMapEnd();

    Object value = create(initValue);

    in.setRef(ref, value);

    return value;
  }

  public Object readObject(AbstractHessianInput in, String []fieldNames)
    throws IOException
  {
    int ref = in.addRef(null);

    long initValue = Long.MIN_VALUE;

    for (int i = 0; i < fieldNames.length; i++) {
      String key = fieldNames[i];

      if (key.equals("value"))
	initValue = in.readUTCDate();
      else
	in.readObject();
    }

    Object value = create(initValue);

    in.setRef(ref, value);

    return value;
  }

  private Object create(long initValue)
    throws IOException
  {
    if (initValue == Long.MIN_VALUE)
      throw new IOException(_cl.getName() + " expects name.");

    try {
      return _constructor.newInstance(new Object[] { new Long(initValue) });
    } catch (Exception e) {
      throw new IOExceptionWrapper(e);
    }
  }
}


text:
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_bma220 as sensorObj

def main():
    # Instantiate an BMA220 using default parameters (bus 0, addr 0x0a)
    sensor = sensorObj.BMA220()

    ## Exit handlers ##
    # This function stops python from printing a stacktrace when you hit control-C
    def SIGINTHandler(signum, frame):
        raise SystemExit

    # This function lets you run code on exit
    def exitHandler():
        print("Exiting")
        sys.exit(0)

    # Register exit handlers
    atexit.register(exitHandler)
    signal.signal(signal.SIGINT, SIGINTHandler)

    x = sensorObj.new_floatp()
    y = sensorObj.new_floatp()
    z = sensorObj.new_floatp()

    while (1):
        sensor.update()
        sensor.getAccelerometer(x, y, z)
        print("Accelerometer: AX:", sensorObj.floatp_value(x), end=' ')
        print(" AY:", sensorObj.floatp_value(y), end=' ')
        print(" AZ:", sensorObj.floatp_value(z))

        time.sleep(.5)

if __name__ == '__main__':
    main()


text:
<?php

class main extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('mod_kecamatan');
    }

    public function index() {
        $this->ShowKecamatan();
    }

    public function ShowKecamatan() {
        $this->load->view('extjs');
        $this->load->view("kecamatan_entry");
    }

    public function DataListKecamatan() {
        $q = $this->input->get('query');
        $sort = $this->input->get('sort');
        $dir = $this->input->get('dir');
        $start = $this->input->get('start');
        $limit = $this->input->get('limit');

        $data = $this->mod_kecamatan->MasterKecamatan($q, $start, $limit);

        foreach ($data[1] as $r)
            $record_count = $r->recordcount;
        echo "{'totalCount':'$record_count', 'nama_data':[";

        foreach ($data[0] as $row) {
            echo "{
                    'id':'$row->id',
                    'nama':'$row->nama'
                 },";
        }
        echo "]}";
    }

    public function HapusKecamatan() {
        $id = $this->input->post('id');
        $this->mod_kecamatan->HapusKecamatan($id);
    }

    public function InsertKecamatan() {
        $id = $this->input->post('id');
        $nama = $this->input->post('nama');

        $this->mod_kecamatan->HapusKecamatan($id);
		$this->mod_kecamatan->InsertKecamatan($nama);

    }

	public function UpdateKecamatan() {
        $id = $this->input->post('id');
        $nama = $this->input->post('nama');

		$this->mod_kecamatan->UpdateKecamatan($id, $nama);
	}

}

?>


text: SLURM patterns for timberchop


text:
package lab.chabingba.eventorganizer.Visual;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import android.widget.Scroller;

import lab.chabingba.eventorganizer.Helpers.Constants.GlobalConstants;

/**
 * Created by Tsvetan on 2015-05-27.
 */
public class FlyInMenuContainer extends LinearLayout {
    private View menu;
    private View content;
    private int menuMargin = 80;
    private int magicPaddingRemove = 40;

    private int sdkVersion = Build.VERSION.SDK_INT;

    private int currentContentOffset = 0;
    private GlobalConstants.MenuState menuState = GlobalConstants.MenuState.CLOSED;

    private Scroller scroller = new Scroller(this.getContext(), new SmoothInterpolator());
    private Runnable runnable = new AnimationRunnable();
    private Handler handler = new Handler();

    private int menuAnimationDuration = 1000;
    private int menuAnimationInterval = 16;

    public FlyInMenuContainer(Context context) {
        super(context);
    }

    public FlyInMenuContainer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        this.setPadding(0, 0, 0, 0);

        //get the linear layout for the menu
        this.menu = this.getChildAt(0);

        //get the linear layout for the content
        this.content = this.getChildAt(1);

        this.menu.setVisibility(View.GONE);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        if (this.sdkVersion > 12) {
            magicPaddingRemove = 0;
        }

        if (changed) {
            this.calculateChildDimension();
        }

        this.menu.layout(l, t - magicPaddingRemove, r - this.menuMargin, b);

        this.content.layout(l + this.currentContentOffset, t - magicPaddingRemove, r + this.currentContentOffset, b);
    }

    private void calculateChildDimension() {
        this.content.getLayoutParams().height = this.getHeight();
        this.content.getLayoutParams().width = this.getWidth();

        this.menu.getLayoutParams().height = this.getHeight();
        this.menu.getLayoutParams().width = this.getWidth() - this.menuMargin;
    }

    public void toggleMenu() {
        switch (this.menuState) {
            case CLOSED:
                this.menuState = GlobalConstants.MenuState.OPENING;
                this.menu.setVisibility(View.VISIBLE);
                this.scroller.startScroll(0, 0, this.getMenuWidth(), 0, menuAnimationDuration);
                break;
            case OPEN:
                this.menuState = GlobalConstants.MenuState.CLOSING;
                this.scroller.startScroll(this.currentContentOffset, 0, -this.currentContentOffset, 0, menuAnimationDuration);
                break;
            default:
                return;
        }

        this.handler.postDelayed(this.runnable, menuAnimationInterval);
    }

    private int getMenuWidth() {
        return this.menu.getLayoutParams().width;
    }

    private void adjustContentPosition(boolean isAnimationOngoing) {
        int scrollerOffset = this.scroller.getCurrX();
        this.content.offsetLeftAndRight(scrollerOffset - this.currentContentOffset);
        this.currentContentOffset = scrollerOffset;

        this.invalidate();

        if (isAnimationOngoing) {
            this.handler.postDelayed(this.runnable, menuAnimationInterval);
        } else {
            this.onMenuTransitionComplete();
        }
    }

    private void onMenuTransitionComplete() {
        switch (this.menuState) {
            case OPENING:
                this.menuState = GlobalConstants.MenuState.OPEN;
                break;
            case CLOSING:
                this.menuState = GlobalConstants.MenuState.CLOSED;
                this.menu.setVisibility(View.GONE);
                break;
            default:
                return;
        }
    }

    public GlobalConstants.MenuState getMenuState() {
        return this.menuState;
    }

    private class SmoothInterpolator implements Interpolator {

        @Override
        public float getInterpolation(float input) {
            return (float) Math.pow(input - 1, 5) + 1;
        }
    }

    private class AnimationRunnable implements Runnable {

        @Override
        public void run() {
            boolean isAnimationOngoing = FlyInMenuContainer.this.scroller.computeScrollOffset();

            FlyInMenuContainer.this.adjustContentPosition(isAnimationOngoing);
        }
    }
}


text:
class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :drop, counter_cache: true
  validates :user, :drop, :text, presence: true
end


text:
export const back = `<ComposerHeader backButtonValue="Back to Social Posts"/>`;

export const main = `<ComposerHeader>
<ComposerHeader.MainActions>
  <Button skin="inverted">Preview</Button>
  <Button>Next</Button>
</ComposerHeader.MainActions>
</ComposerHeader>`;

export const actions = `
<ComposerHeader backButtonValue="Back to Social Posts">
<ComposerHeader.Actions justifyContent="flex-start">
  <TextButton skin="premium">
    Upgrade
  </TextButton>
</ComposerHeader.Actions>
<ComposerHeader.MainActions>
  <Button skin="inverted">Preview</Button>
  <Button>Next</Button>
</ComposerHeader.MainActions>
</ComposerHeader>
`;

export const dividers = `
<ComposerHeader backButtonValue="Back to Social Posts">
<ComposerHeader.Actions justifyContent="flex-start">
  <TextButton skin="premium">
    Upgrade
  </TextButton>
</ComposerHeader.Actions>
<ComposerHeader.Actions justifyContent="flex-end">
  <ToggleButton labelValue="Undo">
    <Icons.Undo />
  </ToggleButton>
  <ToggleButton labelValue="Redo">
    <Icons.Redo />
  </ToggleButton>
</ComposerHeader.Actions>
<ComposerHeader.MainActions>
  <Button skin="inverted">Preview</Button>
  <Button>Next</Button>
</ComposerHeader.MainActions>
</ComposerHeader>
`;

export const save = `
<Layout cols={1}>
<ComposerHeader backButtonValue="Back to Social Posts">
<ComposerHeader.Actions  >
  <TextButton skin="premium">
    Upgrade
  </TextButton>
</ComposerHeader.Actions>
<ComposerHeader.Actions justifyContent="flex-end" >
<ComposerHeader.SaveStatus saveStatusValue="Saving..."/>
<ToggleButton labelValue="Undo">
  <Icons.Undo />
</ToggleButton>
<ToggleButton labelValue="Redo">
  <Icons.Redo />
</ToggleButton>
</ComposerHeader.Actions>
<ComposerHeader.MainActions>
  <Button skin="inverted">Preview</Button>
  <Button>Next</Button>
</ComposerHeader.MainActions>
</ComposerHeader>
<ComposerHeader backButtonValue="Back to Social Posts" >
<ComposerHeader.Actions  >
  <TextButton skin="premium">
    Upgrade
  </TextButton>
</ComposerHeader.Actions>
<ComposerHeader.Actions width="auto" >
<ComposerHeader.SaveStatus saveStatusValue="Saving..." />
</ComposerHeader.Actions>
<ComposerHeader.MainActions>
  <Button skin="inverted">Preview</Button>
  <Button>Next</Button>
</ComposerHeader.MainActions>
</ComposerHeader>
</Layout>
`;

export const size = `
<Layout cols={1}>
<ComposerHeader backButtonValue="Back to Social Posts">
<ComposerHeader.Actions  >
  <TextButton skin="premium">
    Upgrade
  </TextButton>
</ComposerHeader.Actions>
<ComposerHeader.Actions justifyContent="flex-end">
<ComposerHeader.SaveStatus saveStatusValue="Saving..." />
<ToggleButton labelValue="Undo">
  <Icons.Undo />
</ToggleButton>
<ToggleButton labelValue="Redo">
  <Icons.Redo />
</ToggleButton>
</ComposerHeader.Actions>
<ComposerHeader.MainActions>
  <Button skin="inverted">Preview</Button>
  <Button>Next</Button>
</ComposerHeader.MainActions>
</ComposerHeader>

<ComposerHeader backButtonValue="Back to Social Posts" size="small">
<ComposerHeader.Actions  >
  <TextButton skin="premium" size="small">
    Upgrade
  </TextButton>
</ComposerHeader.Actions>
<ComposerHeader.Actions justifyContent="flex-end">
<ComposerHeader.SaveStatus saveStatusValue="Saving..." size="small" />
<ToggleButton labelValue="Undo">
  <Icons.Undo />
</ToggleButton>
<ToggleButton labelValue="Redo">
  <Icons.Redo />
</ToggleButton>
</ComposerHeader.Actions>
<ComposerHeader.MainActions>
  <Button size="small" skin="inverted">Preview</Button>
  <Button size="small"> Next</Button>
</ComposerHeader.MainActions>
</ComposerHeader>
</Layout>
`;

export const shadow = `
<ComposerHeader backButtonValue="Back to Social Posts" dropShadow>
<ComposerHeader.Actions  >
  <TextButton skin="premium">
    Upgrade
  </TextButton>
</ComposerHeader.Actions>
<ComposerHeader.Actions justifyContent="flex-end">
<ComposerHeader.SaveStatus saveStatusValue="Saving..." />
<ToggleButton labelValue="Undo">
  <Icons.Undo />
</ToggleButton>
<ToggleButton labelValue="Redo">
  <Icons.Redo />
</ToggleButton>
</ComposerHeader.Actions>
<ComposerHeader.MainActions>
  <Button skin="inverted">Preview</Button>
  <Button>Next</Button>
</ComposerHeader.MainActions>
</ComposerHeader>
`;


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="8dp"
    android:paddingRight="8dp">

    <EditText
        android:id="@+id/device_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/buttonBarPadding"
        android:layout_marginRight="@dimen/buttonBarPadding"
        android:layout_marginLeft="@dimen/buttonBarPadding"
        android:ems="10"
        android:hint="@string/device_name" >

        <requestFocus />
    </EditText>

</LinearLayout>


text:
using std::make_pair;
using std::pair;
using std::set;
using std::string;
using std::vector;

namespace chromeos_update_engine {

namespace {
void SetOpForNodes(Graph* graph) {
  for (Graph::iterator it = graph->begin(), e = graph->end(); it != e; ++it) {
    it->op.set_type(InstallOperation_Type_MOVE);
  }
}
}  // namespace {}

class CycleBreakerTest : public ::testing::Test {};

TEST(CycleBreakerTest, SimpleTest) {
  int counter = 0;
  const Vertex::Index n_a = counter++;
  const Vertex::Index n_b = counter++;
  const Vertex::Index n_c = counter++;
  const Vertex::Index n_d = counter++;
  const Vertex::Index n_e = counter++;
  const Vertex::Index n_f = counter++;
  const Vertex::Index n_g = counter++;
  const Vertex::Index n_h = counter++;
  const Graph::size_type kNodeCount = counter++;

  Graph graph(kNodeCount);
  SetOpForNodes(&graph);

  graph[n_a].out_edges.insert(make_pair(n_e, EdgeProperties()));
  graph[n_a].out_edges.insert(make_pair(n_f, EdgeProperties()));
  graph[n_b].out_edges.insert(make_pair(n_a, EdgeProperties()));
  graph[n_c].out_edges.insert(make_pair(n_d, EdgeProperties()));
  graph[n_d].out_edges.insert(make_pair(n_e, EdgeProperties()));
  graph[n_d].out_edges.insert(make_pair(n_f, EdgeProperties()));
  graph[n_e].out_edges.insert(make_pair(n_b, EdgeProperties()));
  graph[n_e].out_edges.insert(make_pair(n_c, EdgeProperties()));
  graph[n_e].out_edges.insert(make_pair(n_f, EdgeProperties()));
  graph[n_f].out_edges.insert(make_pair(n_g, EdgeProperties()));
  graph[n_g].out_edges.insert(make_pair(n_h, EdgeProperties()));
  graph[n_h].out_edges.insert(make_pair(n_g, EdgeProperties()));

  CycleBreaker breaker;

  set<Edge> broken_edges;
  breaker.BreakCycles(graph, &broken_edges);

  // The following cycles must be cut:
  // A->E->B
  // C->D->E
  // G->H

  EXPECT_TRUE(broken_edges.count(make_pair(n_a, n_e)) ||
              broken_edges.count(make_pair(n_e, n_b)) ||
              broken_edges.count(make_pair(n_b, n_a)));
  EXPECT_TRUE(broken_edges.count(make_pair(n_c, n_d)) ||
              broken_edges.count(make_pair(n_d, n_e)) ||
              broken_edges.count(make_pair(n_e, n_c)));
  EXPECT_TRUE(broken_edges.count(make_pair(n_g, n_h)) ||
              broken_edges.count(make_pair(n_h, n_g)));
  EXPECT_EQ(3, broken_edges.size());
}

namespace {
pair<Vertex::Index, EdgeProperties> EdgeWithWeight(Vertex::Index dest,
uint64_t weight) {
  EdgeProperties props;
  props.extents.resize(1);
  props.extents[0].set_num_blocks(weight);
  return make_pair(dest, props);
}
}  // namespace {}

// This creates a bunch of cycles like this:
//
//               root <------.
//    (t)->     / | \        |
//             V  V  V       |
//             N  N  N       |
//              \ | /        |
//               VVV         |
//                N          |
//              / | \        |
//             V  V  V       |
//             N  N  N       |
//               ...         |
//     (s)->    \ | /        |
//               VVV         |
//                N          |
//                 \_________/
//
// such that the original cutting algo would cut edges (s). We changed
// the algorithm to cut cycles (t) instead, since they are closer to the
// root, and that can massively speed up cycle cutting.
TEST(CycleBreakerTest, AggressiveCutTest) {
  int counter = 0;

  const int kNodesPerGroup = 4;
  const int kGroups = 33;

  Graph graph(kGroups * kNodesPerGroup + 1);  // + 1 for the root node
  SetOpForNodes(&graph);

  const Vertex::Index n_root = counter++;

  Vertex::Index last_hub = n_root;
  for (int i = 0; i < kGroups; i++) {
    uint64_t weight = 5;
    if (i == 0)
      weight = 2;
    else if (i == (kGroups - 1))
      weight = 1;

    const Vertex::Index next_hub = counter++;

    for (int j = 0; j < (kNodesPerGroup - 1); j++) {
      const Vertex::Index node = counter++;
      graph[last_hub].out_edges.insert(EdgeWithWeight(node, weight));
      graph[node].out_edges.insert(EdgeWithWeight(next_hub, weight));
    }
    last_hub = next_hub;
  }

  graph[last_hub].out_edges.insert(EdgeWithWeight(n_root, 5));

  EXPECT_EQ(counter, graph.size());

  CycleBreaker breaker;

  set<Edge> broken_edges;
  LOG(INFO) << "If this hangs for more than 1 second, the test has failed.";
  breaker.BreakCycles(graph, &broken_edges);

  set<Edge> expected_cuts;

  for (Vertex::EdgeMap::const_iterator it = graph[n_root].out_edges.begin(),
       e = graph[n_root].out_edges.end(); it != e; ++it) {
    expected_cuts.insert(make_pair(n_root, it->first));
  }

  EXPECT_TRUE(broken_edges == expected_cuts);
}

TEST(CycleBreakerTest, WeightTest) {
  int counter = 0;
  const Vertex::Index n_a = counter++;
  const Vertex::Index n_b = counter++;
  const Vertex::Index n_c = counter++;
  const Vertex::Index n_d = counter++;
  const Vertex::Index n_e = counter++;
  const Vertex::Index n_f = counter++;
  const Vertex::Index n_g = counter++;
  const Vertex::Index n_h = counter++;
  const Vertex::Index n_i = counter++;
  const Vertex::Index n_j = counter++;
  const Graph::size_type kNodeCount = counter++;

  Graph graph(kNodeCount);
  SetOpForNodes(&graph);

  graph[n_a].out_edges.insert(EdgeWithWeight(n_b, 4));
  graph[n_a].out_edges.insert(EdgeWithWeight(n_f, 3));
  graph[n_a].out_edges.insert(EdgeWithWeight(n_h, 2));
  graph[n_b].out_edges.insert(EdgeWithWeight(n_a, 3));
  graph[n_b].out_edges.insert(EdgeWithWeight(n_c, 4));
  graph[n_c].out_edges.insert(EdgeWithWeight(n_b, 5));
  graph[n_c].out_edges.insert(EdgeWithWeight(n_d, 3));
  graph[n_d].out_edges.insert(EdgeWithWeight(n_a, 6));
  graph[n_d].out_edges.insert(EdgeWithWeight(n_e, 3));
  graph[n_e].out_edges.insert(EdgeWithWeight(n_d, 4));
  graph[n_e].out_edges.insert(EdgeWithWeight(n_g, 5));
  graph[n_f].out_edges.insert(EdgeWithWeight(n_g, 2));
  graph[n_g].out_edges.insert(EdgeWithWeight(n_f, 3));
  graph[n_g].out_edges.insert(EdgeWithWeight(n_d, 5));
  graph[n_h].out_edges.insert(EdgeWithWeight(n_i, 8));
  graph[n_i].out_edges.insert(EdgeWithWeight(n_e, 4));
  graph[n_i].out_edges.insert(EdgeWithWeight(n_h, 9));
  graph[n_i].out_edges.insert(EdgeWithWeight(n_j, 6));

  CycleBreaker breaker;

  set<Edge> broken_edges;
  breaker.BreakCycles(graph, &broken_edges);

  // These are required to be broken:
  EXPECT_TRUE(broken_edges.count(make_pair(n_b, n_a)));
  EXPECT_TRUE(broken_edges.count(make_pair(n_b, n_c)));
  EXPECT_TRUE(broken_edges.count(make_pair(n_d, n_e)));
  EXPECT_TRUE(broken_edges.count(make_pair(n_f, n_g)));
  EXPECT_TRUE(broken_edges.count(make_pair(n_h, n_i)));
}

TEST(CycleBreakerTest, UnblockGraphTest) {
  int counter = 0;
  const Vertex::Index n_a = counter++;
  const Vertex::Index n_b = counter++;
  const Vertex::Index n_c = counter++;
  const Vertex::Index n_d = counter++;
  const Graph::size_type kNodeCount = counter++;

  Graph graph(kNodeCount);
  SetOpForNodes(&graph);

  graph[n_a].out_edges.insert(EdgeWithWeight(n_b, 1));
  graph[n_a].out_edges.insert(EdgeWithWeight(n_c, 1));
  graph[n_b].out_edges.insert(EdgeWithWeight(n_c, 2));
  graph[n_c].out_edges.insert(EdgeWithWeight(n_b, 2));
  graph[n_b].out_edges.insert(EdgeWithWeight(n_d, 2));
  graph[n_d].out_edges.insert(EdgeWithWeight(n_a, 2));

  CycleBreaker breaker;

  set<Edge> broken_edges;
  breaker.BreakCycles(graph, &broken_edges);

  // These are required to be broken:
  EXPECT_TRUE(broken_edges.count(make_pair(n_a, n_b)));
  EXPECT_TRUE(broken_edges.count(make_pair(n_a, n_c)));
}

TEST(CycleBreakerTest, SkipOpsTest) {
  int counter = 0;
  const Vertex::Index n_a = counter++;
  const Vertex::Index n_b = counter++;
  const Vertex::Index n_c = counter++;
  const Graph::size_type kNodeCount = counter++;

  Graph graph(kNodeCount);
  SetOpForNodes(&graph);
  graph[n_a].op.set_type(InstallOperation_Type_REPLACE_BZ);
  graph[n_c].op.set_type(InstallOperation_Type_REPLACE);

  graph[n_a].out_edges.insert(EdgeWithWeight(n_b, 1));
  graph[n_c].out_edges.insert(EdgeWithWeight(n_b, 1));

  CycleBreaker breaker;

  set<Edge> broken_edges;
  breaker.BreakCycles(graph, &broken_edges);

  EXPECT_EQ(2, breaker.skipped_ops());
}

}  // namespace chromeos_update_engine


text:
package org.zstack.test.configuration;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.configuration.DiskOfferingInventory;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.BeanConstructor;
import org.zstack.test.DBUtil;
import org.zstack.utils.Utils;
import org.zstack.utils.data.SizeUnit;
import org.zstack.utils.logging.CLogger;

public class TestUpdateDiskOffering {
	CLogger logger = Utils.getLogger(TestUpdateDiskOffering.class);
    Api api;
    ComponentLoader loader;
    DatabaseFacade dbf;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        BeanConstructor con = new BeanConstructor();
        /* This loads spring application context */
        loader = con.addXml("ZoneManager.xml").addXml("PortalForUnitTest.xml").addXml("ConfigurationManager.xml").addXml("Simulator.xml").addXml("PrimaryStorageManager.xml").addXml("AccountManager.xml").build();
        dbf = loader.getComponent(DatabaseFacade.class);
        api = new Api();
        api.startServer();
    }

	@Test
	public void test() throws InterruptedException, ApiSenderException {
	    DiskOfferingInventory inv = new DiskOfferingInventory();
	    inv.setDiskSize(SizeUnit.GIGABYTE.toByte(10));
	    inv.setName("Test");
	    inv.setDescription("Test");
	    inv = api.addDiskOffering(inv);
        inv.setName("1");
        inv.setDescription("xxx");
        inv = api.updateDiskOffering(inv);
        Assert.assertEquals("1", inv.getName());
        Assert.assertEquals("xxx", inv.getDescription());
	}
}


text:
"""
Package contains interfaces for using existing functionality in other packages

Requires Packages to be installed
"""
__docformat__ = 'restructuredtext'

from io import DataGrabber, DataSink, SelectFiles
from utility import IdentityInterface, Rename, Function, Select, Merge


text:
/**
 * @flow
 */

import type {ExtendedModule} from '../types/Stats';

export type FilterProps = {
  moduleName: string,
  cumulativeSizeMin: string,
  cumulativeSizeMax: string,
  requiredByCountMin: string,
  requiredByCountMax: string,
  requirementsCountMin: string,
  requirementsCountMax: string,
};

export type FilterableFields = $Keys<FilterProps>;

type FilterMethod = (eModule: ExtendedModule) => boolean;

function makeRecordLikeRegExpFilter(field: string, re: RegExp | ''): FilterMethod {
  return function(eModule: ExtendedModule): boolean {
    if (re && !re.test(eModule[field])) {
      return false;
    }
    return true;
  };
}

function toNumber(value: string): number | '' {
  return value === '' ? '' : Number(value);
}

function makeRecordRangeFilter(
  field: string,
  min: number | '',
  max: number | '',
): FilterMethod {
  return function(eModule: ExtendedModule): boolean {
    if (min !== '' && max !== '') {
      return eModule[field] >= min && eModule[field] <= max;
    }
    if (min !== '') {
      return eModule[field] >= min;
    }
    if (max !== '') {
      return eModule[field] <= max;
    }
    return true;
  };
}

export default function filterModules(
  extendedModules: Array<ExtendedModule>,
  filters: FilterProps,
): Array<ExtendedModule> {
  return extendedModules
    .filter(makeRecordLikeRegExpFilter(
      'name',
      new RegExp(filters.moduleName),
    ))
    .filter(makeRecordRangeFilter(
      'cumulativeSize',
      toNumber(filters.cumulativeSizeMin),
      toNumber(filters.cumulativeSizeMax),
    ))
    .filter(makeRecordRangeFilter(
      'requiredByCount',
      toNumber(filters.requiredByCountMin),
      toNumber(filters.requiredByCountMax),
    ))
    .filter(makeRecordRangeFilter(
      'requirementsCount',
      toNumber(filters.requirementsCountMin),
      toNumber(filters.requirementsCountMax),
    ));
}


text:
In this guide, we'll walk through how you can integrate your new HSDS: React updates with local projects.

## Creating a beta build

The simplest way to do this is to create a new beta build for HSDS: React.

To do this, run this command:

```
npm run release:beta
```

You'll be prompted to select a version to upgrade to.

Note: The version numbers (below) may be different when you run this.

```
? Select semver increment or specify new version (Use arrow keys)
❯ patch         2.6.8
  minor         2.7.0
  major         3.0.0
  prepatch      2.6.8-0
  preminor      2.7.0-0
  premajor      3.0.0-0
  prerelease    2.6.8-0
  ──────────────
  Other (specify)
```

### Other (specify)

It is recommended that you select the `Other (specify)` option. This allows you to create a (unique) namespaced release.

From the above example, you'll be asked to specify your own version after selecting `Other (specify)`:

```
? Select semver increment or specify new version Other (specify)
? Version
```

For this guide, we'll enter in `2.6.8-hello-0`:

```
? Select semver increment or specify new version Other (specify)
? Version 2.6.8-hello-0
```

Next, you'll be asked to specify the tag for your release.

Note: This list (below) may be different when you run this.

```
? How should this pre-release version be tagged in npm? (Use arrow keys)
❯ next
  new-blue
  ──────────────
  Other (specify)
```

You can either select `next` (if you're confident this release will be 👍). If not, or if you want to release under a custom tag, select `Other (specify)`.

For this example, we'll release under a custom tag of `hello`:

```
? Select semver increment or specify new version Other (specify)
? Version 2.6.8-hello-0
? How should this pre-release version be tagged in npm? Other (specify)
? Tag hello
```

Congrats! You just created a custom beta release!

### Prepatching

To easiest thing to do would be to select `prepatch`. From the above example, you'll be asked to confirm after selecting `prepatch`:

```
Will bump from 2.6.7 to 2.6.8-0 and tag this release in npm as beta. Continue? (Y/n)
```

Press `Enter`, or type `Y` + `Enter`.

Congrats! You just created a prepatch beta release!

### Integration with local development

Awesome! We just released a custom beta build with the version `@helpscout/hsds-react@v2.6-8-hello-0.

To test it out in your local development project, simply version bump the `@helpscout/hsds-react` version in your project's `package.json`.

```
"@helpscout/hsds-react": "2.6.7" -> "2.6-8-hello-0"
```

And that's it 🙏! You've successfully integrated your newly custom beta build with your local project.

### (Beta) Build and repeat

Feel free to create new beta builds as needed! Repeat the steps above until you're confident the update is ready for prime time!

### What about `npm link`?

Unfortunately, setting up `npm link` with this project is (very) tedious and slow. We've explored various ways to automate the linking process. The results were inconsistent and very slow.

As of this moment, it's actually much more efficient to create and release beta builds.


text:
<template>

basic

			<ssv-checkbox label="Tick me!" checked.bind="isTicked">
			</ssv-checkbox>

				State ${isTicked ? "Ticked" : "Unticked"}

<ssv-checkbox label="Tick me!" checked.bind="isTicked"></ssv-checkbox>
State <strong> $ {isTicked ? "Ticked" : "Unticked"}</strong>

type

			<ssv-checkbox label="Filled style" type="filled">
			</ssv-checkbox>

<ssv-checkbox label="Filled style" type="filled">
</ssv-checkbox>

disabled states

				<ssv-checkbox label="Disabled Ticked" checked disabled>
				</ssv-checkbox>
				<ssv-checkbox label="Disabled Unticked" disabled>
				</ssv-checkbox>

<ssv-checkbox label="Disabled Ticked" checked disabled>
</ssv-checkbox>
<ssv-checkbox label="Disabled Unticked" disabled>
</ssv-checkbox>

disabled bind

				<ssv-checkbox label="I can be disabled" disabled.bind="isDisabled">
				</ssv-checkbox>
				<ssv-checkbox label="Disable the other" checked.bind="isDisabled">
				</ssv-checkbox>

<ssv-checkbox label="I can be disabled" disabled.bind="isDisabled">
</ssv-checkbox>
<ssv-checkbox label="Disable the other" checked.bind="isDisabled">
</ssv-checkbox>

label position

				<ssv-checkbox label="label before" label-position="before" type="minimal">
				</ssv-checkbox>
				<ssv-checkbox label="label before disabled" label-position="before" disabled type="minimal">
				</ssv-checkbox>
				<ssv-checkbox label="label after" label-position="after" type="minimal">
				</ssv-checkbox>

<ssv-checkbox label="label before" label-position="before">
</ssv-checkbox>
<ssv-checkbox label="label before disabled" label-position="before" disabled>
</ssv-checkbox>
<ssv-checkbox label="label after" label-position="after">
</ssv-checkbox>

indeterminate

				<ssv-checkbox label="Indeterminate" indeterminate checked.bind="indeterminateChecked" type="minimal">
				</ssv-checkbox>
				<ssv-checkbox label="Indeterminate" indeterminate checked.bind="indeterminateChecked" type="filled">
				</ssv-checkbox>
				<button ssv-button click.trigger="resetIndeterminate()">Reset</button>

<ssv-checkbox label="Indeterminate" indeterminate checked.bind="indeterminateChecked" type="minimal">
</ssv-checkbox>
<ssv-checkbox label="Indeterminate" indeterminate checked.bind="indeterminateChecked" type="filled">
</ssv-checkbox>
<button ssv-button click.trigger="indeterminateChecked = null">Reset</button>

variations

type ${type}

${color ? color : "default"}

							<ssv-checkbox color.bind="color" type.bind="type" label="Unticked">
							</ssv-checkbox>

							<ssv-checkbox color.bind="color" type.bind="type" label="Ticked" checked>
							</ssv-checkbox>

							<ssv-checkbox color.bind="color" type.bind="type" label="Indeterminate" indeterminate>
							</ssv-checkbox>

							<ssv-checkbox color.bind="color" type.bind="type" label="Unticked Disabled" disabled>
							</ssv-checkbox>

							<ssv-checkbox color.bind="color" type.bind="type" label="Ticked Disabled" checked disabled>
							</ssv-checkbox>

							<ssv-checkbox color.bind="color" type.bind="type" label="Indeterminate Disabled" disabled indeterminate>
							</ssv-checkbox>

</template>


text:
using System;
using Subtext.Framework.Configuration;

namespace Subtext.Web.Install
{
    /// <summary>
    /// Summary description for InstallationComplete.
    /// </summary>
    public partial class InstallationComplete : InstallationBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            InstallationManager.ResetInstallationStatusCache();

            if(paraBlogLink != null)
            {
                paraBlogLink.Visible = false;
            }
            if(paraBlogAdminLink != null)
            {
                paraBlogAdminLink.Visible = false;
            }
            if(paraBlogmlImport != null)
            {
                paraBlogmlImport.Visible = false;
            }

            if(Config.CurrentBlog != null)
            {
                if(lnkBlog != null && paraBlogLink != null)
                {
                    paraBlogLink.Visible = true;
                    lnkBlog.HRef = Url.BlogUrl();
                }

                if(lnkBlogAdmin != null && paraBlogAdminLink != null)
                {
                    paraBlogAdminLink.Visible = true;
                    lnkBlogAdmin.HRef = AdminUrl.Home();
                }

                if(lnkBlogMl != null && paraBlogmlImport != null)
                {
                    paraBlogmlImport.Visible = true;
                    lnkBlogMl.HRef = AdminUrl.ImportExport();
                }
            }
        }
    }
}


text:
package com.composum.sling.nodes.update;

import org.apache.sling.api.resource.ResourceResolver;
import org.jetbrains.annotations.NotNull;

import javax.jcr.RepositoryException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.InputStream;

public interface SourceUpdateService {

    /**
     * Reads a ZIP from the input stream and updates the resources at the path of the entries of the zip file so that
     * they are identical to the stream, ignoring / updating metadata.
     *
     * @param resolver       the resolver we write to
     * @param zipInputStream contains a zip with the data to import. It needs to contain the actual content to import below jcr_root.
     *                       E.g. if nodePath is /content/whatever, the zip contains the relevant content below jcr_root/content/whatever/somepath
     * @param nodePath       the path of the node we want to update
     * @throws IllegalArgumentException if something about the parameters is too fishy to go on
     */
    void updateFromZip(@NotNull ResourceResolver resolver, @NotNull InputStream zipInputStream, @NotNull String nodePath)
            throws IOException, RepositoryException, TransformerException, IllegalArgumentException;

}


text:
package org.hl7.v3;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for CodingRationale.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="CodingRationale">
 *   <restriction base="{urn:hl7-org:v3}cs">
 *     <enumeration value="SH"/>
 *     <enumeration value="HL7"/>
 *     <enumeration value="SRC"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "CodingRationale")
@XmlEnum
public enum CodingRationale {

    SH("SH"),
    @XmlEnumValue("HL7")
    HL_7("HL7"),
    SRC("SRC");
    private final String value;

    CodingRationale(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static CodingRationale fromValue(String v) {
        for (CodingRationale c: CodingRationale.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
COMPONENT=TestTemp
include ../Makerules


text:
/// <reference path="Mouse/MouseHandler.ts" />
/// <reference path="Keyboard/KeyboardHandler.ts" />

module EndGate.Input {

    /**
    * Defines an all around Input handler which manages mouse and keyboard events.
    */
    export class InputManager {
        /**
        * Used to bind functions to mouse related events.
        */
        public Mouse: MouseHandler;
        /**
        * Used to bind functions to keyboard related events.
        */
        public Keyboard: KeyboardHandler;

        /**
        * Creates a new instance of the InputManager object.
        * @param target The object through which mouse events will be monitored on.
        */
        constructor(target: HTMLElement) {
            this.Mouse = new MouseHandler(target);
            this.Keyboard = new KeyboardHandler();
        }
    }

}


text:
package auth

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"encoding/json"
	"errors"

	"github.com/issue9/wechat/common"
)

// 几个错误信息
var (
	ErrInvalidSessionKey = errors.New("无效的 sessionkey")
	ErrInvalidInitVector = errors.New("无效的 Initization vector")
)

// 加密数据解密之后的部分内容
type encyData struct {
	Watermark *Watermark `json:"watermark"`
}

// Watermark 水印部分的内容
type Watermark struct {
	Appid     string `json:"appid"`
	Timestamp int64  `json:"timestamp"`
}

// Decode 解析加密数据
//
// 返回的 Watermark 可用以验证数据是否正确
func Decode(appid, sessionkey, data, iv string) ([]byte, *Watermark, error) {
	if len(sessionkey) != 24 {
		return nil, nil, ErrInvalidSessionKey
	}
	aeskey, err := base64.StdEncoding.DecodeString(sessionkey)
	if err != nil {
		return nil, nil, err
	}

	if len(iv) != 24 {
		return nil, nil, ErrInvalidInitVector
	}
	aesiv, err := base64.StdEncoding.DecodeString(iv)
	if err != nil {
		return nil, nil, err
	}

	cipherText, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return nil, nil, err
	}

	block, err := aes.NewCipher(aeskey)
	if err != nil {
		return nil, nil, err
	}

	mode := cipher.NewCBCDecrypter(block, aesiv)
	mode.CryptBlocks(cipherText, cipherText)

	cipherText = common.PKCS7UnPadding(cipherText)
	obj := &encyData{}
	if err = json.Unmarshal(cipherText, obj); err != nil {
		return nil, nil, err
	}

	return cipherText, obj.Watermark, nil
}


text:
var webpack = require("webpack");
var WebpackDevServer = require("webpack-dev-server");
var gutil = require("gulp-util");

module.exports = function(gulp, plugins) {
    return function() {
// Start a webpack-dev-server
 var config = Object.create(require('../webpack.config.js'));
    config = require('../webpack.config.js');
console.log(config.module);
    config.devtool = "eval";
    config.debug = true;

    new WebpackDevServer(webpack(config), {
        publicPath: config.output.publicPath,
        stats: {
            colors: true
        }
    }).listen(8080, "localhost", function(err) {
        if(err) throw new gutil.PluginError("webpack-dev-server", err);
        // Server listening
        gutil.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html");
        // keep the server alive or continue?
        // callback();
    });

    };
};


text:
package org.apache.flink.yarn;

import org.apache.flink.util.FlinkException;

import org.apache.hadoop.yarn.api.records.NodeState;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.exceptions.YarnException;

import java.io.IOException;

/**
 * {@link YarnClusterInformationRetriever} implementation which queries the Yarn cluster using
 * a {@link YarnClient} instance.
 */
public final class YarnClientYarnClusterInformationRetriever implements YarnClusterInformationRetriever {
	private final YarnClient yarnClient;

	private YarnClientYarnClusterInformationRetriever(YarnClient yarnClient) {
		this.yarnClient = yarnClient;
	}

	@Override
	public int getMaxVcores() throws FlinkException {
		try {
			return yarnClient.getNodeReports(NodeState.RUNNING)
				.stream()
				.mapToInt(report -> report.getCapability().getVirtualCores())
				.max()
				.orElse(0);
		} catch (YarnException | IOException e) {
			throw new FlinkException("Couldn't get cluster description, please check on the YarnConfiguration", e);
		}
	}

	public static YarnClientYarnClusterInformationRetriever create(YarnClient yarnClient) {
		return new YarnClientYarnClusterInformationRetriever(yarnClient);
	}
}


text:
package org.postgresql.pljava.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;

/**
 *
 * @author Thomas Hallgren
 */
public class SPIDriver implements Driver {
    private static final Connection           s_defaultConn   = new SPIConnection();
    private static final String               s_defaultURL    = "jdbc:default:connection";

    private static final int                  s_defaultURLLen = s_defaultURL.length();
    private static final DriverPropertyInfo[] s_noInfo        = new DriverPropertyInfo[0];

    static {
        try {
            DriverManager.registerDriver(new SPIDriver());
        } catch (SQLException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    static Connection getDefault() {
        return s_defaultConn;
    }

    public boolean acceptsURL(String url) throws SQLException {
        if (url.startsWith(s_defaultURL)) {
            // Accept extra info at end provided the defaultURL is
            // delimited by a ':'
            //
            if (url.length() == s_defaultURLLen
                || url.charAt(s_defaultURLLen) == ':') {
                return true;
            }
        }
        return false;
    }

    public Connection connect(String url, Properties info) throws SQLException {
        return acceptsURL(url) ? s_defaultConn : null;
    }

    public int getMajorVersion() {
        return 1;
    }

    public int getMinorVersion() {
        return 0;
    }

    /* (non-Javadoc)
     * @see java.sql.Driver#getParentLogger()
     */
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        // TODO Auto-generated method stub
        return null;
    }

    public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
                                                                            throws SQLException {
        return s_noInfo;
    }

    public boolean jdbcCompliant() {
        return false; // Not all functionality is supported at present.
    }
}


text:
<?php

namespace Google\AdsApi\Dfp\v201611;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class PlacementErrorReason
{
    const INVALID_ENTITY_TYPE = 'INVALID_ENTITY_TYPE';
    const SHARED_INVENTORY_ASSIGNED = 'SHARED_INVENTORY_ASSIGNED';
    const PLACEMENTS_CANNOT_INCLUDE_INVENTORY_FROM_MULTIPLE_DISTRIBUTOR_NETWORKS = 'PLACEMENTS_CANNOT_INCLUDE_INVENTORY_FROM_MULTIPLE_DISTRIBUTOR_NETWORKS';
    const PLACEMENTS_CANNOT_INCLUDE_BOTH_LOCAL_AND_SHARED_INVENTORY = 'PLACEMENTS_CANNOT_INCLUDE_BOTH_LOCAL_AND_SHARED_INVENTORY';
    const UNKNOWN = 'UNKNOWN';

}


text:
/*****************************************************************************/
/* Csv.cpp                                Copyright (c) Ladislav Zezula 2019 */
/*---------------------------------------------------------------------------*/
/* Implementation for the CSV handler class                                  */
/*---------------------------------------------------------------------------*/
/*   Date    Ver   Who  Comment                                              */
/* --------  ----  ---  -------                                              */
/* 24.05.19  1.00  Lad  Created                                              */
/*****************************************************************************/

#define __CASCLIB_SELF__
#include "../CascLib.h"
#include "../CascCommon.h"

//-----------------------------------------------------------------------------
// Local variables

static const CASC_CSV_LINE NullLine;
#define NullColumn NullLine.Columns[0];

//-----------------------------------------------------------------------------
// Local functions

static char * NextLine(char * szLine)
{
    // Find the end of the line
    while(szLine[0] != 0 && szLine[0] != 0x0A && szLine[0] != 0x0D)
        szLine++;

    // Terminate the line
    while(szLine[0] == 0x0A || szLine[0] == 0x0D)
        *szLine++ = 0;

    // If there's an end-of-string, it's over
    return (szLine[0] != 0) ? szLine : NULL;
}

static char * NextColumn(char * szColumn)
{
    // Find the end of the column
    while(szColumn[0] != 0 && szColumn[0] != '|')
        szColumn++;

    // Terminate the column
    if (szColumn[0] == '|')
    {
        *szColumn++ = 0;
        return szColumn;
    }

    // If there's an end-of-string, it's over
    return NULL;
}

static size_t CalcHashValue(const char * szString)
{
    size_t dwHash = 0x7EEE7EEE;

    // Hash the string itself
    while(szString[0] != 0)
    {
        dwHash = (dwHash >> 24) ^ (dwHash << 5) ^ dwHash ^ szString[0];
        szString++;
    }

    // Return the hash limited by the table size
    return dwHash;
}

static BYTE HashToIndex(size_t dwHashValue)
{
    return (BYTE)(dwHashValue & (CSV_HASH_TABLE_SIZE - 1));
}

//-----------------------------------------------------------------------------
// Class for CSV line

CASC_CSV_LINE::CASC_CSV_LINE()
{
    m_pParent = NULL;
    m_nColumns = 0;
}

CASC_CSV_LINE::~CASC_CSV_LINE()
{}

bool CASC_CSV_LINE::SetLine(CASC_CSV * pParent, char * szCsvLine)
{
    char * szCsvColumn;
    size_t nHdrColumns = 0;
    size_t nColumns = 0;

    // Reset the number of column to zero
    m_pParent = pParent;
    m_nColumns = 0;

    // Parse each column
    while(szCsvLine != NULL && nColumns < CSV_MAX_COLUMNS)
    {
        // Get current line and the next one
        szCsvColumn = szCsvLine;
        szCsvLine = NextColumn(szCsvLine);

        // Save the current line
        Columns[nColumns].szValue = szCsvColumn;
        Columns[nColumns].nLength = strlen(szCsvColumn);
        nColumns++;
    }

    // Columns overflow
    if(nColumns >= CSV_MAX_COLUMNS)
    {
        assert(false);
        return false;
    }

    // If the parent has header lines, then the number of columns must match
    // In the case of mismatched column count, ignore the line
    nHdrColumns = pParent->GetHeaderColumns();
    if(nHdrColumns != 0 && nColumns != nHdrColumns)
        return false;

    // All OK
    m_nColumns = nColumns;
    return true;
}

const CASC_CSV_COLUMN & CASC_CSV_LINE::operator[](const char * szColumnName) const
{
    size_t nIndex;

    // The column must have a hash table
    if(m_pParent != NULL)
    {
        nIndex = m_pParent->GetColumnIndex(szColumnName);
        if(nIndex != CSV_INVALID_INDEX && nIndex < m_nColumns)
        {
            return Columns[nIndex];
        }
    }

    return NullColumn;
}

const CASC_CSV_COLUMN & CASC_CSV_LINE::operator[](size_t nIndex) const
{
    return (nIndex < m_nColumns) ? Columns[nIndex] : NullColumn;
}

//-----------------------------------------------------------------------------
// Class for CSV object

CASC_CSV::CASC_CSV(size_t nLinesMax, bool bHasHeader)
{
    // Initialize the class variables
    memset(HashTable, 0xFF, sizeof(HashTable));
    m_szCsvFile = NULL;
    m_szCsvPtr = NULL;
    m_nCsvFile = 0;
    m_nLines = 0;
    m_bHasHeader = bHasHeader;

    // Nonzero number of lines means a finite CSV handler. The CSV will be loaded at once.
    // Zero means that the user needs to call LoadNextLine() and then the line data
    if(nLinesMax != 0)
    {
        m_pLines = new CASC_CSV_LINE[nLinesMax];
        m_nLinesMax = nLinesMax;
        m_bHasAllLines = true;
    }
    else
    {
        m_pLines = new CASC_CSV_LINE[1];
        m_nLinesMax = 1;
        m_bHasAllLines = false;
    }
}

CASC_CSV::~CASC_CSV()
{
    if(m_pLines != NULL)
        delete[] m_pLines;
    if(m_szCsvFile != NULL)
        delete [] m_szCsvFile;
    m_szCsvFile = NULL;
}

DWORD CASC_CSV::Load(LPCTSTR szFileName)
{
    DWORD cbFileData = 0;
    DWORD dwErrCode = ERROR_SUCCESS;

    m_szCsvFile = (char *)LoadFileToMemory(szFileName, &cbFileData);
    if (m_szCsvFile != NULL)
    {
        // There is one extra byte reserved by LoadFileToMemory, so we can put zero there
        m_szCsvFile[cbFileData] = 0;
        m_szCsvPtr = m_szCsvFile;
        m_nCsvFile = cbFileData;

        // Parse the data
        dwErrCode = ParseCsvData() ? ERROR_SUCCESS : ERROR_BAD_FORMAT;
    }
    else
    {
        dwErrCode = GetLastError();
    }

    return dwErrCode;
}

DWORD CASC_CSV::Load(LPBYTE pbData, size_t cbData)
{
    DWORD dwErrCode = ERROR_NOT_ENOUGH_MEMORY;

    m_szCsvFile = new char[cbData + 1];
    if (m_szCsvFile != NULL)
    {
        // Copy the entire data and terminate them with zero
        memcpy(m_szCsvFile, pbData, cbData);
        m_szCsvFile[cbData] = 0;
        m_szCsvPtr = m_szCsvFile;
        m_nCsvFile = cbData;

        // Parse the data
        dwErrCode = ParseCsvData() ? ERROR_SUCCESS : ERROR_BAD_FORMAT;
    }

    return dwErrCode;
}

bool CASC_CSV::LoadNextLine()
{
    bool bResult = false;

    // Only endless CSV handler can do this
    if(m_bHasAllLines == false)
    {
        // A few checks
        assert(m_pLines != NULL);
        assert(m_nLinesMax == 1);

        // Reset the current line and load it
        bResult = LoadNextLine(m_pLines[0]);
        m_nLines = (bResult) ? 1 : 0;
    }

    return bResult;
}

bool CASC_CSV::InitializeHashTable()
{
    // Create the hash table of HeaderText -> ColumnIndex
    for(size_t i = 0; i < Header.GetColumnCount(); i++)
    {
        // Calculate the start slot and the current slot
        size_t nStartIndex = HashToIndex(CalcHashValue(Header[i].szValue));
        size_t nHashIndex = nStartIndex;

        // Go as long as there is not a free space
        while(HashTable[nHashIndex] != 0xFF)
        {
            nHashIndex = HashToIndex(nHashIndex + 1);
        }

        // Set the slot
        HashTable[nHashIndex] = (BYTE)i;
    }

    return true;
}

bool CASC_CSV::LoadNextLine(CASC_CSV_LINE & Line)
{
    // Overwatch ROOT's header begins with "#"
    if(m_szCsvPtr == m_szCsvFile && m_szCsvPtr[0] == '#')
        m_szCsvPtr++;

    // Parse the entire line
    while(m_szCsvPtr != NULL && m_szCsvPtr[0] != 0)
    {
        char * szCsvLine = m_szCsvPtr;

        // Get the next line
        m_szCsvPtr = NextLine(m_szCsvPtr);

        // Initialize the line
        if (Line.SetLine(this, szCsvLine))
            return true;
    }

    // End-of-file found
    return false;
}

bool CASC_CSV::ParseCsvData()
{
    // Sanity checks
    assert(m_nLines == 0);

    // If we have header, then parse it and set the pointer to the next line
    if(m_bHasHeader)
    {
        // Load the current line to the header
        if (!LoadNextLine(Header))
            return false;

        // Initialize the hash table
        if(!InitializeHashTable())
            return false;
    }

    // Are we supposed to load all lines?
    if(m_bHasAllLines)
    {
        // Parse each line
        for(size_t i = 0; i < m_nLinesMax; i++)
        {
            if(!LoadNextLine(m_pLines[i]))
                break;
            m_nLines++;
        }
    }

    return true;
}

const CASC_CSV_COLUMN & CASC_CSV::operator[](const char * szColumnName) const
{
    if (m_pLines == NULL || m_nLines == 0)
        return NullColumn;
    return m_pLines[0][GetColumnIndex(szColumnName)];
}

const CASC_CSV_LINE & CASC_CSV::operator[](size_t nIndex) const
{
    if (m_pLines == NULL || nIndex >= m_nLines)
        return NullLine;
    return m_pLines[nIndex];
}

size_t CASC_CSV::GetHeaderColumns() const
{
    return (m_bHasHeader) ? Header.GetColumnCount() : 0;
}

size_t CASC_CSV::GetColumnIndex(const char * szColumnName) const
{
    if(m_bHasHeader)
    {
        // Calculate the start slot and the current slot
        size_t nStartIndex = HashToIndex(CalcHashValue(szColumnName));
        size_t nHashIndex = nStartIndex;
        size_t nIndex;

        // Go as long as there is not a free space
        while((nIndex = HashTable[nHashIndex]) != 0xFF)
        {
            // Compare the string
            if(!strcmp(Header[nIndex].szValue, szColumnName))
                return nIndex;

            // Move to the next column
            nHashIndex = HashToIndex(nHashIndex + 1);
        }
    }

    return CSV_INVALID_INDEX;
}