text:
require 'stringio'

require 'puma/thread_pool'
require 'puma/const'
require 'puma/events'
require 'puma/null_io'
require 'puma/compat'
require 'puma/reactor'
require 'puma/client'
require 'puma/binder'
require 'puma/delegation'
require 'puma/accept_nonblock'
require 'puma/util'

require 'puma/puma_http11'

unless Puma.const_defined? "IOBuffer"
  require 'puma/io_buffer'
end

require 'socket'

module Puma

  # The HTTP Server itself. Serves out a single Rack app.
  class Server

    include Puma::Const
    extend  Puma::Delegation

    attr_reader :thread
    attr_reader :events
    attr_accessor :app

    attr_accessor :min_threads
    attr_accessor :max_threads
    attr_accessor :persistent_timeout
    attr_accessor :auto_trim_time
    attr_accessor :reaping_time
    attr_accessor :first_data_timeout

    # Create a server for the rack app +app+.
    #
    # +events+ is an object which will be called when certain error events occur
    # to be handled. See Puma::Events for the list of current methods to implement.
    #
    # Server#run returns a thread that you can join on to wait for the server
    # to do its work.
    #
    def initialize(app, events=Events.stdio, options={})
      @app = app
      @events = events

      @check, @notify = Puma::Util.pipe

      @status = :stop

      @min_threads = 0
      @max_threads = 16
      @auto_trim_time = 1
      @reaping_time = 1

      @thread = nil
      @thread_pool = nil

      @persistent_timeout = PERSISTENT_TIMEOUT

      @binder = Binder.new(events)
      @own_binder = true

      @first_data_timeout = FIRST_DATA_TIMEOUT

      @leak_stack_on_error = true

      @options = options
      @queue_requests = options[:queue_requests].nil? ? true : options[:queue_requests]

      ENV['RACK_ENV'] ||= "development"

      @mode = :http
    end

    attr_accessor :binder, :leak_stack_on_error

    forward :add_tcp_listener,  :@binder
    forward :add_ssl_listener,  :@binder
    forward :add_unix_listener, :@binder

    def inherit_binder(bind)
      @binder = bind
      @own_binder = false
    end

    def tcp_mode!
      @mode = :tcp
    end

    # On Linux, use TCP_CORK to better control how the TCP stack
    # packetizes our stream. This improves both latency and throughput.
    #
    if RUBY_PLATFORM =~ /linux/
      # 6 == Socket::IPPROTO_TCP
      # 3 == TCP_CORK
      # 1/0 == turn on/off
      def cork_socket(socket)
        begin
          socket.setsockopt(6, 3, 1) if socket.kind_of? TCPSocket
        rescue IOError, SystemCallError
        end
      end

      def uncork_socket(socket)
        begin
          socket.setsockopt(6, 3, 0) if socket.kind_of? TCPSocket
        rescue IOError, SystemCallError
        end
      end
    else
      def cork_socket(socket)
      end

      def uncork_socket(socket)
      end
    end

    def backlog
      @thread_pool and @thread_pool.backlog
    end

    def running
      @thread_pool and @thread_pool.spawned
    end

    # Lopez Mode == raw tcp apps

    def run_lopez_mode(background=true)
      @thread_pool = ThreadPool.new(@min_threads,
                                    @max_threads,
                                    Hash) do |client, tl|

        io = client.to_io
        addr = io.peeraddr.last

        if addr.empty?
          # Set unix socket addrs to localhost
          addr = "127.0.0.1:0"
        else
          addr = "#{addr}:#{io.peeraddr[1]}"
        end

        env = { 'thread' => tl, REMOTE_ADDR => addr }

        begin
          @app.call env, client.to_io
        rescue Object => e
          STDERR.puts "! Detected exception at toplevel: #{e.message} (#{e.class})"
          STDERR.puts e.backtrace
        end

        client.close unless env['detach']
      end

      @events.fire :state, :running

      if background
        @thread = Thread.new { handle_servers_lopez_mode }
        return @thread
      else
        handle_servers_lopez_mode
      end
    end

    def handle_servers_lopez_mode
      begin
        check = @check
        sockets = [check] + @binder.ios
        pool = @thread_pool

        while @status == :run
          begin
            ios = IO.select sockets
            ios.first.each do |sock|
              if sock == check
                break if handle_check
              else
                begin
                  if io = sock.accept_nonblock
                    client = Client.new io, nil
                    pool << client
                  end
                rescue SystemCallError
                  # nothing
                rescue Errno::ECONNABORTED
                  # client closed the socket even before accept
                  io.close rescue nil
                end
              end
            end
          rescue Object => e
            @events.unknown_error self, e, "Listen loop"
          end
        end

        @events.fire :state, @status

        graceful_shutdown if @status == :stop || @status == :restart

      rescue Exception => e
        STDERR.puts "Exception handling servers: #{e.message} (#{e.class})"
        STDERR.puts e.backtrace
      ensure
        @check.close
        @notify.close

        if @status != :restart and @own_binder
          @binder.close
        end
      end

      @events.fire :state, :done
    end
    # Runs the server.
    #
    # If +background+ is true (the default) then a thread is spun
    # up in the background to handle requests. Otherwise requests
    # are handled synchronously.
    #
    def run(background=true)
      BasicSocket.do_not_reverse_lookup = true

      @events.fire :state, :booting

      @status = :run

      if @mode == :tcp
        return run_lopez_mode(background)
      end

      queue_requests = @queue_requests

      @thread_pool = ThreadPool.new(@min_threads,
                                    @max_threads,
                                    IOBuffer) do |client, buffer|
        process_now = false

        begin
          if queue_requests
            process_now = client.eagerly_finish
          else
            client.finish
            process_now = true
          end
        rescue MiniSSL::SSLError => e
          ssl_socket = client.io
          addr = ssl_socket.peeraddr.last
          cert = ssl_socket.peercert

          client.close

          @events.ssl_error self, addr, cert, e
        rescue HttpParserError => e
          client.write_400
          client.close

          @events.parse_error self, client.env, e
        rescue ConnectionError
          client.close
        else
          if process_now
            process_client client, buffer
          else
            client.set_timeout @first_data_timeout
            @reactor.add client
          end
        end
      end

      @thread_pool.clean_thread_locals = @options[:clean_thread_locals]

      if queue_requests
        @reactor = Reactor.new self, @thread_pool
        @reactor.run_in_thread
      end

      if @reaping_time
        @thread_pool.auto_reap!(@reaping_time)
      end

      if @auto_trim_time
        @thread_pool.auto_trim!(@auto_trim_time)
      end

      @events.fire :state, :running

      if background
        @thread = Thread.new { handle_servers }
        return @thread
      else
        handle_servers
      end
    end

    def handle_servers
      begin
        check = @check
        sockets = [check] + @binder.ios
        pool = @thread_pool
        queue_requests = @queue_requests

        remote_addr_value = nil
        remote_addr_header = nil

        case @options[:remote_address]
        when :value
          remote_addr_value = @options[:remote_address_value]
        when :header
          remote_addr_header = @options[:remote_address_header]
        end

        while @status == :run
          begin
            ios = IO.select sockets
            ios.first.each do |sock|
              if sock == check
                break if handle_check
              else
                begin
                  if io = sock.accept_nonblock
                    client = Client.new io, @binder.env(sock)
                    if remote_addr_value
                      client.peerip = remote_addr_value
                    elsif remote_addr_header
                      client.remote_addr_header = remote_addr_header
                    end

                    pool << client
                    pool.wait_until_not_full unless queue_requests
                  end
                rescue SystemCallError
                  # nothing
                rescue Errno::ECONNABORTED
                  # client closed the socket even before accept
                  io.close rescue nil
                end
              end
            end
          rescue Object => e
            @events.unknown_error self, e, "Listen loop"
          end
        end

        @events.fire :state, @status

        graceful_shutdown if @status == :stop || @status == :restart
        if queue_requests
          @reactor.clear! if @status == :restart
          @reactor.shutdown
        end
      rescue Exception => e
        STDERR.puts "Exception handling servers: #{e.message} (#{e.class})"
        STDERR.puts e.backtrace
      ensure
        @check.close
        @notify.close

        if @status != :restart and @own_binder
          @binder.close
        end
      end

      @events.fire :state, :done
    end

    # :nodoc:
    def handle_check
      cmd = @check.read(1)

      case cmd
      when STOP_COMMAND
        @status = :stop
        return true
      when HALT_COMMAND
        @status = :halt
        return true
      when RESTART_COMMAND
        @status = :restart
        return true
      end

      return false
    end

    # Given a connection on +client+, handle the incoming requests.
    #
    # This method support HTTP Keep-Alive so it may, depending on if the client
    # indicates that it supports keep alive, wait for another request before
    # returning.
    #
    def process_client(client, buffer)
      begin
        close_socket = true

        while true
          case handle_request(client, buffer)
          when false
            return
          when :async
            close_socket = false
            return
          when true
            return unless @queue_requests
            buffer.reset

            unless client.reset(@status == :run)
              close_socket = false
              client.set_timeout @persistent_timeout
              @reactor.add client
              return
            end
          end
        end

      # The client disconnected while we were reading data
      rescue ConnectionError
        # Swallow them. The ensure tries to close +client+ down

      # SSL handshake error
      rescue MiniSSL::SSLError => e
        ssl_socket = client.io
        addr = ssl_socket.peeraddr.last
        cert = ssl_socket.peercert

        close_socket = true

        @events.ssl_error self, addr, cert, e

      # The client doesn't know HTTP well
      rescue HttpParserError => e
        client.write_400

        @events.parse_error self, client.env, e

      # Server error
      rescue StandardError => e
        client.write_500

        @events.unknown_error self, e, "Read"

      ensure
        buffer.reset

        begin
          client.close if close_socket
        rescue IOError, SystemCallError
          # Already closed
        rescue StandardError => e
          @events.unknown_error self, e, "Client"
        end
      end
    end

    # Given a Hash +env+ for the request read from +client+, add
    # and fixup keys to comply with Rack's env guidelines.
    #
    def normalize_env(env, client)
      if host = env[HTTP_HOST]
        if colon = host.index(":")
          env[SERVER_NAME] = host[0, colon]
          env[SERVER_PORT] = host[colon+1, host.bytesize]
        else
          env[SERVER_NAME] = host
          env[SERVER_PORT] = default_server_port(env)
        end
      else
        env[SERVER_NAME] = LOCALHOST
        env[SERVER_PORT] = default_server_port(env)
      end

      unless env[REQUEST_PATH]
        # it might be a dumbass full host request header
        uri = URI.parse(env[REQUEST_URI])
        env[REQUEST_PATH] = uri.path

        raise "No REQUEST PATH" unless env[REQUEST_PATH]
      end

      env[PATH_INFO] = env[REQUEST_PATH]

      # From http://www.ietf.org/rfc/rfc3875 :
      # "Script authors should be aware that the REMOTE_ADDR and
      # REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
      # may not identify the ultimate source of the request.
      # They identify the client for the immediate request to the
      # server; that client may be a proxy, gateway, or other
      # intermediary acting on behalf of the actual source client."
      #

      unless env.key?(REMOTE_ADDR)
        begin
          addr = client.peerip
        rescue Errno::ENOTCONN
          # Client disconnects can result in an inability to get the
          # peeraddr from the socket; default to localhost.
          addr = LOCALHOST_IP
        end

        # Set unix socket addrs to localhost
        addr = LOCALHOST_IP if addr.empty?

        env[REMOTE_ADDR] = addr
      end
    end

    def default_server_port(env)
      return PORT_443 if env[HTTPS_KEY] == 'on' || env[HTTPS_KEY] == 'https'
      env['HTTP_X_FORWARDED_PROTO'] == 'https' ? PORT_443 : PORT_80
    end

    # Given the request +env+ from +client+ and a partial request body
    # in +body+, finish reading the body if there is one and invoke
    # the rack app. Then construct the response and write it back to
    # +client+
    #
    # +cl+ is the previously fetched Content-Length header if there
    # was one. This is an optimization to keep from having to look
    # it up again.
    #
    def handle_request(req, lines)
      env = req.env
      client = req.io

      normalize_env env, req

      env[PUMA_SOCKET] = client

      if env[HTTPS_KEY] && client.peercert
        env[PUMA_PEERCERT] = client.peercert
      end

      env[HIJACK_P] = true
      env[HIJACK] = req

      body = req.body

      head = env[REQUEST_METHOD] == HEAD

      env[RACK_INPUT] = body
      env[RACK_URL_SCHEME] =  env[HTTPS_KEY] ? HTTPS : HTTP

      # A rack extension. If the app writes #call'ables to this
      # array, we will invoke them when the request is done.
      #
      after_reply = env[RACK_AFTER_REPLY] = []

      begin
        begin
          status, headers, res_body = @app.call(env)

          return :async if req.hijacked

          status = status.to_i

          if status == -1
            unless headers.empty? and res_body == []
              raise "async response must have empty headers and body"
            end

            return :async
          end
        rescue StandardError => e
          @events.unknown_error self, e, "Rack app"

          status, headers, res_body = lowlevel_error(e)
        end

        content_length = nil
        no_body = head

        if res_body.kind_of? Array and res_body.size == 1
          content_length = res_body[0].bytesize
        end

        cork_socket client

        line_ending = LINE_END
        colon = COLON

        http_11 = if env[HTTP_VERSION] == HTTP_11
          allow_chunked = true
          keep_alive = env.fetch(HTTP_CONNECTION, "").downcase != CLOSE
          include_keepalive_header = false

          # An optimization. The most common response is 200, so we can
          # reply with the proper 200 status without having to compute
          # the response header.
          #
          if status == 200
            lines << HTTP_11_200
          else
            lines.append "HTTP/1.1 ", status.to_s, " ",
                         fetch_status_code(status), line_ending

            no_body ||= status < 200 || STATUS_WITH_NO_ENTITY_BODY[status]
          end
          true
        else
          allow_chunked = false
          keep_alive = env.fetch(HTTP_CONNECTION, "").downcase == KEEP_ALIVE
          include_keepalive_header = keep_alive

          # Same optimization as above for HTTP/1.1
          #
          if status == 200
            lines << HTTP_10_200
          else
            lines.append "HTTP/1.0 ", status.to_s, " ",
                         fetch_status_code(status), line_ending

            no_body ||= status < 200 || STATUS_WITH_NO_ENTITY_BODY[status]
          end
          false
        end

        response_hijack = nil

        headers.each do |k, vs|
          case k.downcase
          when CONTENT_LENGTH2
            content_length = vs
            next
          when TRANSFER_ENCODING
            allow_chunked = false
            content_length = nil
          when HIJACK
            response_hijack = vs
            next
          end

          if vs.respond_to?(:to_s)
            vs.to_s.split(NEWLINE).each do |v|
              lines.append k, colon, v, line_ending
            end
          else
            lines.append k, colon, line_ending
          end
        end

        if include_keepalive_header
          lines << CONNECTION_KEEP_ALIVE
        elsif http_11 && !keep_alive
          lines << CONNECTION_CLOSE
        end

        if no_body
          if content_length and status != 204
            lines.append CONTENT_LENGTH_S, content_length.to_s, line_ending
          end

          lines << line_ending
          fast_write client, lines.to_s
          return keep_alive
        end

        if content_length
          lines.append CONTENT_LENGTH_S, content_length.to_s, line_ending
          chunked = false
        elsif !response_hijack and allow_chunked
          lines << TRANSFER_ENCODING_CHUNKED
          chunked = true
        end

        lines << line_ending

        fast_write client, lines.to_s

        if response_hijack
          response_hijack.call client
          return :async
        end

        begin
          res_body.each do |part|
            if chunked
              next if part.bytesize.zero?
              fast_write client, part.bytesize.to_s(16)
              fast_write client, line_ending
              fast_write client, part
              fast_write client, line_ending
            else
              fast_write client, part
            end

            client.flush
          end

          if chunked
            fast_write client, CLOSE_CHUNKED
            client.flush
          end
        rescue SystemCallError, IOError
          raise ConnectionError, "Connection error detected during write"
        end

      ensure
        uncork_socket client

        body.close
        req.tempfile.unlink if req.tempfile
        res_body.close if res_body.respond_to? :close

        after_reply.each { |o| o.call }
      end

      return keep_alive
    end

    def fetch_status_code(status)
      HTTP_STATUS_CODES.fetch(status) { 'CUSTOM' }
    end
    private :fetch_status_code

    # Given the requset +env+ from +client+ and the partial body +body+
    # plus a potential Content-Length value +cl+, finish reading
    # the body and return it.
    #
    # If the body is larger than MAX_BODY, a Tempfile object is used
    # for the body, otherwise a StringIO is used.
    #
    def read_body(env, client, body, cl)
      content_length = cl.to_i

      remain = content_length - body.bytesize

      return StringIO.new(body) if remain <= 0

      # Use a Tempfile if there is a lot of data left
      if remain > MAX_BODY
        stream = Tempfile.new(Const::PUMA_TMP_BASE)
        stream.binmode
      else
        # The body[0,0] trick is to get an empty string in the same
        # encoding as body.
        stream = StringIO.new body[0,0]
      end

      stream.write body

      # Read an odd sized chunk so we can read even sized ones
      # after this
      chunk = client.readpartial(remain % CHUNK_SIZE)

      # No chunk means a closed socket
      unless chunk
        stream.close
        return nil
      end

      remain -= stream.write(chunk)

      # Raed the rest of the chunks
      while remain > 0
        chunk = client.readpartial(CHUNK_SIZE)
        unless chunk
          stream.close
          return nil
        end

        remain -= stream.write(chunk)
      end

      stream.rewind

      return stream
    end

    # A fallback rack response if +@app+ raises as exception.
    #
    def lowlevel_error(e)
      if handler = @options[:lowlevel_error_handler]
        return handler.call(e)
      end

      if @leak_stack_on_error
        [500, {}, ["Puma caught this error: #{e.message} (#{e.class})\n#{e.backtrace.join("\n")}"]]
      else
        [500, {}, ["An unhandled lowlevel error occurred. The application logs may have details.\n"]]
      end
    end

    # Wait for all outstanding requests to finish.
    #
    def graceful_shutdown
      if @options[:shutdown_debug]
        threads = Thread.list
        total = threads.size

        pid = Process.pid

        $stdout.syswrite "#{pid}: === Begin thread backtrace dump ===\n"

        threads.each_with_index do |t,i|
          $stdout.syswrite "#{pid}: Thread #{i+1}/#{total}: #{t.inspect}\n"
          $stdout.syswrite "#{pid}: #{t.backtrace.join("\n#{pid}: ")}\n\n"
        end
        $stdout.syswrite "#{pid}: === End thread backtrace dump ===\n"
      end

      if @options[:drain_on_shutdown]
        count = 0

        while true
          ios = IO.select @binder.ios, nil, nil, 0
          break unless ios

          ios.first.each do |sock|
            begin
              if io = sock.accept_nonblock
                count += 1
                client = Client.new io, @binder.env(sock)
                @thread_pool << client
              end
            rescue SystemCallError
            end
          end
        end

        @events.debug "Drained #{count} additional connections."
      end

      @thread_pool.shutdown if @thread_pool
    end

    # Stops the acceptor thread and then causes the worker threads to finish
    # off the request queue before finally exiting.
    #
    def stop(sync=false)
      begin
        @notify << STOP_COMMAND
      rescue IOError
        # The server, in another thread, is shutting down
      end

      @thread.join if @thread && sync
    end

    def halt(sync=false)
      begin
        @notify << HALT_COMMAND
      rescue IOError
        # The server, in another thread, is shutting down
      end

      @thread.join if @thread && sync
    end

    def begin_restart
      begin
        @notify << RESTART_COMMAND
      rescue IOError
        # The server, in another thread, is shutting down
      end
    end

    def fast_write(io, str)
      n = 0
      while true
        begin
          n = io.syswrite str
        rescue Errno::EAGAIN, Errno::EWOULDBLOCK
          if !IO.select(nil, [io], nil, WRITE_TIMEOUT)
            raise ConnectionError, "Socket timeout writing data"
          end

          retry
        rescue  Errno::EPIPE, SystemCallError, IOError
          raise ConnectionError, "Socket timeout writing data"
        end

        return if n == str.bytesize
        str = str.byteslice(n..-1)
      end
    end
    private :fast_write
  end
end


text:
<form class="form-horizontal">

        Username

            <input type="text" class="form-control" id="inputName" ng-model="credentials.username" autocomplete="on" required/>

        Password

            <input type="password" class="form-control" id="inputPassword" ng-model="credentials.password" required/>

            <button type="submit" class="btn btn-default" ng-click="login()">Login</button>

</form>

redpajama_set_name: RedPajamaGithub


text:
import fnmatch
import re

from six import string_types

from . import levels

__re_type = type(re.compile('foo'))  # XXX is there a canonical place for this?

def msg_filter(x):
    """intelligently create a filter"""
    # XXX replace lambdas with nicely-named functions, for debugging
    if x is None:
        return lambda msg: True
    elif isinstance(x, bool):
        return lambda msg: x
    elif isinstance(x, string_types):
        return regex_wrapper(re.compile(x))
    elif isinstance(x, __re_type):
        return regex_wrapper(x)
    elif callable(x):  # XXX test w/ inspect.getargs here?
        return x
    elif isinstance(x, (list, tuple)):
        return list_wrapper(x)
    else:
        # XXX a dict could be used to filter on fields (w/ callables?)
        raise ValueError("Unknown filter: {0!r}".format(x))

def list_wrapper(lst):
    filts = [msg_filter(i) for i in lst]

    def wrapped(msg):
        return all(f(msg) for f in filts)
    return wrapped

def regex_wrapper(regexp):
    assert isinstance(regexp, __re_type)

    def wrapped(msg):
        return regexp.match(msg.text) is not None
    return wrapped

def names(*names):
    """
    Returns a filter which matches message names against exact strings

    :args names: Any number of arguments are accepted.  Each one should be a string which can
        exactly match a message's name.
    :returns: A filter function.  The function returns True if the msg name is the same as one of
        the names provided here.
    """
    names_set = set(names)

    def set_names_filter(msg):
        return msg.name in names_set
    set_names_filter.names = names
    return set_names_filter

def glob_names(*names):
    """
    Return a filter which matches message names based on a list of globs

    :args names: Any number of arguments are accepted.  Each one should be a glob pattern which can
        match a message's name.
    :returns: A filter function.  The function returns True if the msg name matches one of the glob
        patterns provided here.
    """
    # copied from fnmatch.fnmatchcase - for speed
    patterns = [re.compile(fnmatch.translate(pat)) for pat in names]

    def glob_names_filter(msg):
        return any(pat.match(msg.name) is not None for pat in patterns)
    glob_names_filter.names = names
    return glob_names_filter

class Emitter(object):
    """Hold and manage an Output and associated filter."""

    def __init__(self, min_level, filter, output):
        if not isinstance(min_level, levels.LogLevel):
            raise ValueError("Unknown min_level: {0}".format(min_level))

        self.min_level = min_level
        self.filter = filter
        self._output = output

    @property
    def filter(self):
        return self._filter

    @filter.setter
    def filter(self, f):
        self._filter = msg_filter(f)


text:
package com.xjeffrose.xio.core;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.Test;

import static org.junit.Assert.*;

public class BBtoHttpResponseTest {

  @Test
  public void testGetResponseOK() throws Exception {
    ByteBuf bb = Unpooled.wrappedBuffer("HTTP/1.1 200 OK\r\nServer: xio\r\n\r\n\r\n".getBytes());
    DefaultFullHttpResponse response = BBtoHttpResponse.getResponse(bb);

    assertEquals(HttpResponseStatus.OK, response.getStatus());
    assertEquals("xio", response.headers().get("Server"));

  }

  @Test
  public void testGetResponseServerError() throws Exception {
    ByteBuf bb = Unpooled.wrappedBuffer("HTTP/1.1 500 Internal Server Error\r\nServer: xio\r\n\r\n\r\n".getBytes());
    DefaultFullHttpResponse response = BBtoHttpResponse.getResponse(bb);

    assertEquals(HttpResponseStatus.INTERNAL_SERVER_ERROR, response.getStatus());
    assertEquals("xio", response.headers().get("Server"));
  }
}


text:
package com.weinyc.sa.app.engine.controller;

import net.sf.json.JSONObject;

import com.weinyc.sa.core.engine.AbstractController;
import com.weinyc.sa.core.engine.AbstractServicer;
import com.weinyc.sa.core.annotation.ServicerType;
import com.weinyc.sa.common.util.JSONUtils;
import com.weinyc.sa.app.engine.servicer.AccountServicer;
import com.weinyc.sa.app.engine.servicer.MerchantServicer;
import com.weinyc.sa.app.model.Account;
public class AccountController extends AbstractController{

    @ServicerType(value="com.weinyc.sa.app.engine.servicer.AccountServicer", spring="")
    private AccountServicer servicer;

    @ServicerType(value="com.weinyc.sa.app.engine.servicer.MerchantServicer", spring="")
    private MerchantServicer merchantServicer;

    @Override
    public String getFORM_NAME () {
        return "AccountForm";
    }

    @Override
    public String getJSP_TOGO_PERIX () {
        return "Account";
    }

    @Override
    public AbstractServicer getServicer () {
        return servicer;
    }

    public void setServicer (AccountServicer servicer) {
        this.servicer = servicer;
    }

    @Override
    public void submitAction(){

    }

    public Object getColumnsAction(){
        return this.getColumns();
    }

    public String getColumns(){
        return JSONUtils.toString(Account.COLUMNS, 36);
    }

    public MerchantServicer getMerchantServicer() {
        return merchantServicer;
    }

    public void setMerchantServicer(MerchantServicer merchantServicer) {
        this.merchantServicer = merchantServicer;
    }

    public Object listMerchantsAction(){
        return this.merchantServicer.getJSONArray(new JSONObject());
    }

}


text:
360recovery Luci configuration page.Made by 981213
]]--

module("luci.controller.360recovery", package.seeall)

function index()

	local page
	page = entry({"admin", "system", "360recovery"}, call("action_360recovery"), _("刷写360加密固件"), 45)
	page.dependent = true
end

function action_360recovery()
	local sys = require "luci.sys"
	local fs  = require "luci.fs"

	local upgrade_avail = nixio.fs.access("/lib/upgrade/platform.sh")
	local reset_avail   = os.execute([[grep '"rootfs_data"' /proc/mtd >/dev/null 2>&1]]) == 0

	local restore_cmd = "tar -xzC/ >/dev/null 2>&1"
	local backup_cmd  = "sysupgrade --create-backup - 2>/dev/null"
	local image_tmp   = "/tmp/firmware_encrypted.img"
	local image_tmp_dec   = "/tmp/firmware_decrypted.img"

	local function image_supported()
		-- XXX: yay...
		return ( 0 == os.execute(
			"rom_decrypt "..image_tmp.." "..image_tmp_dec.." 2>&1 > /dev/null"
		) )
	end

	local function image_checksum()
		return (luci.sys.exec("md5sum %q" % image_tmp):match("^([^%s]+)"))
	end

	local function storage_size()
		local size = 0
		if nixio.fs.access("/proc/mtd") then
			for l in io.lines("/proc/mtd") do
				local d, s, e, n = l:match('^([^%s]+)%s+([^%s]+)%s+([^%s]+)%s+"([^%s]+)"')
				if n == "linux" or n == "firmware" then
					size = tonumber(s, 16)
					break
				end
			end
		elseif nixio.fs.access("/proc/partitions") then
			for l in io.lines("/proc/partitions") do
				local x, y, b, n = l:match('^%s*(%d+)%s+(%d+)%s+([^%s]+)%s+([^%s]+)')
				if b and n and not n:match('[0-9]') then
					size = tonumber(b) * 1024
					break
				end
			end
		end
		return size
	end

	local fp
	luci.http.setfilehandler(
		function(meta, chunk, eof)
			if not fp then
				fp = io.open(image_tmp, "w")
			end
			if chunk then
				fp:write(chunk)
			end
			if eof then
				fp:close()
			end
		end
	)

	if luci.http.formvalue("image") or luci.http.formvalue("step") then
		--
		-- Initiate firmware flash
		--
		local step = tonumber(luci.http.formvalue("step") or 1)
		if step == 1 then
			if image_supported() then
				luci.template.render("360recovery_upgrade", {
					checksum = image_checksum(),
					storage  = storage_size(),
					size     = nixio.fs.stat(image_tmp).size,
				})
			else
				nixio.fs.unlink(image_tmp)
				luci.template.render("360recovery", {
					reset_avail   = reset_avail,
					upgrade_avail = upgrade_avail,
					image_invalid = true
				})
			end
		--
		-- Start sysupgrade flash
		--
		elseif step == 2 then
			luci.template.render("admin_system/applyreboot", {
				title = luci.i18n.translate("Flashing..."),
				msg   = luci.i18n.translate("The system is flashing now.
 DO NOT POWER OFF THE DEVICE!
 Wait a few minutes before you try to reconnect. It might be necessary to renew the address of your computer to reach the device again, depending on your settings."),
				addr  = "192.168.1.1"
			})
			os.execute("killall uhttpd dropbear && sleep 1 && mtd -r write "..image_tmp_dec.." firmware && reboot &")
		end
	else
		--
		-- Overview
		--
		luci.template.render("360recovery", {
			reset_avail   = reset_avail,
			upgrade_avail = upgrade_avail
		})
	end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:jms="http://www.mulesoft.org/schema/mule/jms"
   xmlns:pattern="http://www.mulesoft.org/schema/mule/pattern" xmlns:ws="http://www.mulesoft.org/schema/mule/ws"
   xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml" xmlns:cxf="http://www.mulesoft.org/schema/mule/cxf"
   xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:servlet="http://www.mulesoft.org/schema/mule/servlet"
   xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
   xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.mulesoft.org/schema/mule/jms http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd
http://www.mulesoft.org/schema/mule/pattern http://www.mulesoft.org/schema/mule/pattern/current/mule-pattern.xsd
http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/cxf http://www.mulesoft.org/schema/mule/cxf/current/mule-cxf.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/servlet http://www.mulesoft.org/schema/mule/servlet/current/mule-servlet.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ws http://www.mulesoft.org/schema/mule/ws/current/mule-ws.xsd">

   <flow name="Client-Consumer-Unsecure-HTTP-Listener">
      <http:listener config-ref="Listener-Application"
         path="${client.consumer.unsecure.path}" doc:name="HTTP Inbound Endpoint" />
      <flow-ref name="Read-HTTP-Variables" doc:name="Read HTPP variables" />
      <flow-ref name="Client-Consumer-Unsecure-Endpoint" doc:name="Send request" />
        <response>
            <flow-ref name="Transform-Response" doc:name="Transform to a valid response"/>
        </response>
   </flow>
   <sub-flow name="Client-Consumer-Unsecure-Endpoint">
      <logger message="Begins the unsecure consumer client flow"
         level="INFO" doc:name="Logger" />
      <flow-ref name="Transform-Consumer-Request-Vars" doc:name="Transform to a valid request" />
      <ws:consumer config-ref="Consumer-Unsecure-CodeFirst"
         operation="${wsdl.operation}" doc:name="Unsecure code-first endpoint consumer" />
      <logger message="Ends the unsecure consumer client flow" level="INFO"
         doc:name="Logger" />
   </sub-flow>

   <flow name="Client-Consumer-Password-HTTP-Listener">
      <http:listener config-ref="Listener-Application"
         path="${client.consumer.password.path}" doc:name="HTTP Inbound Endpoint" />
      <flow-ref name="Read-HTTP-Variables" doc:name="Read HTPP variables" />
      <flow-ref name="Client-Consumer-Password-Endpoint" doc:name="Send request" />
        <response>
            <flow-ref name="Transform-Response" doc:name="Transform to a valid response"/>
        </response>
   </flow>
   <sub-flow name="Client-Consumer-Password-Endpoint">
      <logger message="Begins the password protected consumer client flow"
         level="INFO" doc:name="Logger" />
      <flow-ref name="Transform-Consumer-Request-Vars" doc:name="Transform to a valid request" />
      <ws:consumer config-ref="Consumer-Password-CodeFirst"
         operation="${wsdl.operation}" doc:name="Password protected code-first endpoint consumer" />
      <logger message="Ends the password protected consumer client flow"
         level="INFO" doc:name="Logger" />
   </sub-flow>

   <flow name="Client-Consumer-Signature-HTTP-Listener">
      <http:listener config-ref="Listener-Application"
         path="${client.consumer.signature.path}" doc:name="HTTP Inbound Endpoint" />
      <flow-ref name="Read-HTTP-Variables" doc:name="Read HTPP variables" />
      <flow-ref name="Client-Consumer-Signature-Endpoint" doc:name="Send request" />
        <response>
            <flow-ref name="Transform-Response" doc:name="Transform to a valid response"/>
        </response>
   </flow>
   <sub-flow name="Client-Consumer-Signature-Endpoint">
      <logger message="Begins the signed consumer client flow" level="INFO"
         doc:name="Logger" />
      <flow-ref name="Transform-Consumer-Request-Vars" doc:name="Transform to a valid request" />
      <ws:consumer config-ref="Consumer-Signature-CodeFirst"
         operation="${wsdl.operation}" doc:name="Signed code-first endpoint consumer" />
      <logger message="Ends the signed consumer client flow" level="INFO"
         doc:name="Logger" />
   </sub-flow>

   <flow name="Client-Consumer-Encryption-HTTP-Listener">
      <http:listener config-ref="Listener-Application"
         path="${client.consumer.encryption.path}" doc:name="HTTP Inbound Endpoint" />
      <flow-ref name="Read-HTTP-Variables" doc:name="Read HTPP variables" />
      <flow-ref name="Client-Consumer-Encryption-Endpoint"
         doc:name="Send request" />
        <response>
            <flow-ref name="Transform-Response" doc:name="Transform to a valid response"/>
        </response>
   </flow>
   <sub-flow name="Client-Consumer-Encryption-Endpoint">
      <logger message="Begins the encrypted consumer client flow"
         level="INFO" doc:name="Logger" />
      <flow-ref name="Transform-Consumer-Request-Vars" doc:name="Transform to a valid request" />
      <ws:consumer config-ref="Consumer-Encryption-CodeFirst"
         operation="${wsdl.operation}" doc:name="Encrypted code-first endpoint consumer" />
      <logger message="Ends the encrypted consumer client flow"
         level="INFO" doc:name="Logger" />
   </sub-flow>

</mule>


text:
package auth

import (
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"runtime"
	"testing"
	"time"

	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apiserver/pkg/authentication/request/bearertoken"
	"k8s.io/apiserver/pkg/authentication/token/tokenfile"
	"k8s.io/apiserver/pkg/authentication/user"
	restclient "k8s.io/client-go/rest"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/auth/nodeidentifier"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	informers "k8s.io/kubernetes/pkg/client/informers/informers_generated/internalversion"
	"k8s.io/kubernetes/pkg/kubeapiserver/authorizer"
	"k8s.io/kubernetes/plugin/pkg/admission/noderestriction"
	"k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac/bootstrappolicy"
	"k8s.io/kubernetes/test/integration/framework"
)

func TestNodeAuthorizer(t *testing.T) {
	// Start the server so we know the address
	h := &framework.MasterHolder{Initialized: make(chan struct{})}
	apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		<-h.Initialized
		h.M.GenericAPIServer.Handler.ServeHTTP(w, req)
	}))

	const (
		// Define credentials
		tokenMaster      = "master-token"
		tokenNodeUnknown = "unknown-token"
		tokenNode1       = "node1-token"
		tokenNode2       = "node2-token"
	)

	authenticator := bearertoken.New(tokenfile.New(map[string]*user.DefaultInfo{
		tokenMaster:      {Name: "admin", Groups: []string{"system:masters"}},
		tokenNodeUnknown: {Name: "unknown", Groups: []string{"system:nodes"}},
		tokenNode1:       {Name: "system:node:node1", Groups: []string{"system:nodes"}},
		tokenNode2:       {Name: "system:node:node2", Groups: []string{"system:nodes"}},
	}))

	// Build client config, clientset, and informers
	clientConfig := &restclient.Config{Host: apiServer.URL, ContentConfig: restclient.ContentConfig{NegotiatedSerializer: api.Codecs}}
	superuserClient := clientsetForToken(tokenMaster, clientConfig)
	informerFactory := informers.NewSharedInformerFactory(superuserClient, time.Minute)

	// Set up Node+RBAC authorizer
	authorizerConfig := &authorizer.AuthorizationConfig{
		AuthorizationModes: []string{"Node", "RBAC"},
		InformerFactory:    informerFactory,
	}
	nodeRBACAuthorizer, err := authorizerConfig.New()
	if err != nil {
		t.Fatal(err)
	}
	defer bootstrappolicy.ClearClusterRoleBindingFilters()

	// Set up NodeRestriction admission
	nodeRestrictionAdmission := noderestriction.NewPlugin(nodeidentifier.NewDefaultNodeIdentifier())
	nodeRestrictionAdmission.SetInternalKubeClientSet(superuserClient)
	if err := nodeRestrictionAdmission.Validate(); err != nil {
		t.Fatal(err)
	}

	// Start the server
	masterConfig := framework.NewIntegrationTestMasterConfig()
	masterConfig.GenericConfig.Authenticator = authenticator

	masterConfig.GenericConfig.Authorizer = nodeRBACAuthorizer
	masterConfig.GenericConfig.AdmissionControl = nodeRestrictionAdmission
	_, _, closeFn := framework.RunAMasterUsingServer(masterConfig, apiServer, h)
	defer closeFn()

	// Start the informers
	stopCh := make(chan struct{})
	defer close(stopCh)
	informerFactory.Start(stopCh)

	// Wait for a healthy server
	for {
		result := superuserClient.Core().RESTClient().Get().AbsPath("/healthz").Do()
		_, err := result.Raw()
		if err == nil {
			break
		}
		t.Log(err)
		time.Sleep(time.Second)
	}

	// Create objects
	if _, err := superuserClient.Core().Secrets("ns").Create(&api.Secret{ObjectMeta: metav1.ObjectMeta{Name: "mysecret"}}); err != nil {
		t.Fatal(err)
	}
	if _, err := superuserClient.Core().Secrets("ns").Create(&api.Secret{ObjectMeta: metav1.ObjectMeta{Name: "mypvsecret"}}); err != nil {
		t.Fatal(err)
	}
	if _, err := superuserClient.Core().ConfigMaps("ns").Create(&api.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "myconfigmap"}}); err != nil {
		t.Fatal(err)
	}
	if _, err := superuserClient.Core().PersistentVolumeClaims("ns").Create(&api.PersistentVolumeClaim{
		ObjectMeta: metav1.ObjectMeta{Name: "mypvc"},
		Spec: api.PersistentVolumeClaimSpec{
			AccessModes: []api.PersistentVolumeAccessMode{api.ReadOnlyMany},
			Resources:   api.ResourceRequirements{Requests: api.ResourceList{api.ResourceStorage: resource.MustParse("1")}},
		},
	}); err != nil {
		t.Fatal(err)
	}
	if _, err := superuserClient.Core().PersistentVolumes().Create(&api.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{Name: "mypv"},
		Spec: api.PersistentVolumeSpec{
			AccessModes:            []api.PersistentVolumeAccessMode{api.ReadOnlyMany},
			Capacity:               api.ResourceList{api.ResourceStorage: resource.MustParse("1")},
			ClaimRef:               &api.ObjectReference{Namespace: "ns", Name: "mypvc"},
			PersistentVolumeSource: api.PersistentVolumeSource{AzureFile: &api.AzureFileVolumeSource{ShareName: "default", SecretName: "mypvsecret"}},
		},
	}); err != nil {
		t.Fatal(err)
	}

	getSecret := func(client clientset.Interface) error {
		_, err := client.Core().Secrets("ns").Get("mysecret", metav1.GetOptions{})
		return err
	}
	getPVSecret := func(client clientset.Interface) error {
		_, err := client.Core().Secrets("ns").Get("mypvsecret", metav1.GetOptions{})
		return err
	}
	getConfigMap := func(client clientset.Interface) error {
		_, err := client.Core().ConfigMaps("ns").Get("myconfigmap", metav1.GetOptions{})
		return err
	}
	getPVC := func(client clientset.Interface) error {
		_, err := client.Core().PersistentVolumeClaims("ns").Get("mypvc", metav1.GetOptions{})
		return err
	}
	getPV := func(client clientset.Interface) error {
		_, err := client.Core().PersistentVolumes().Get("mypv", metav1.GetOptions{})
		return err
	}

	createNode2NormalPod := func(client clientset.Interface) error {
		_, err := client.Core().Pods("ns").Create(&api.Pod{
			ObjectMeta: metav1.ObjectMeta{Name: "node2normalpod"},
			Spec: api.PodSpec{
				NodeName:   "node2",
				Containers: []api.Container{{Name: "image", Image: "busybox"}},
				Volumes: []api.Volume{
					{Name: "secret", VolumeSource: api.VolumeSource{Secret: &api.SecretVolumeSource{SecretName: "mysecret"}}},
					{Name: "cm", VolumeSource: api.VolumeSource{ConfigMap: &api.ConfigMapVolumeSource{LocalObjectReference: api.LocalObjectReference{Name: "myconfigmap"}}}},
					{Name: "pvc", VolumeSource: api.VolumeSource{PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ClaimName: "mypvc"}}},
				},
			},
		})
		return err
	}
	updateNode2NormalPodStatus := func(client clientset.Interface) error {
		startTime := metav1.NewTime(time.Now())
		_, err := client.Core().Pods("ns").UpdateStatus(&api.Pod{
			ObjectMeta: metav1.ObjectMeta{Name: "node2normalpod"},
			Status:     api.PodStatus{StartTime: &startTime},
		})
		return err
	}
	deleteNode2NormalPod := func(client clientset.Interface) error {
		zero := int64(0)
		return client.Core().Pods("ns").Delete("node2normalpod", &metav1.DeleteOptions{GracePeriodSeconds: &zero})
	}

	createNode2MirrorPod := func(client clientset.Interface) error {
		_, err := client.Core().Pods("ns").Create(&api.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name:        "node2mirrorpod",
				Annotations: map[string]string{api.MirrorPodAnnotationKey: "true"},
			},
			Spec: api.PodSpec{
				NodeName:   "node2",
				Containers: []api.Container{{Name: "image", Image: "busybox"}},
			},
		})
		return err
	}
	deleteNode2MirrorPod := func(client clientset.Interface) error {
		zero := int64(0)
		return client.Core().Pods("ns").Delete("node2mirrorpod", &metav1.DeleteOptions{GracePeriodSeconds: &zero})
	}

	createNode2 := func(client clientset.Interface) error {
		_, err := client.Core().Nodes().Create(&api.Node{ObjectMeta: metav1.ObjectMeta{Name: "node2"}})
		return err
	}
	updateNode2Status := func(client clientset.Interface) error {
		_, err := client.Core().Nodes().UpdateStatus(&api.Node{
			ObjectMeta: metav1.ObjectMeta{Name: "node2"},
			Status:     api.NodeStatus{},
		})
		return err
	}
	deleteNode2 := func(client clientset.Interface) error {
		return client.Core().Nodes().Delete("node2", nil)
	}

	nodeanonClient := clientsetForToken(tokenNodeUnknown, clientConfig)
	node1Client := clientsetForToken(tokenNode1, clientConfig)
	node2Client := clientsetForToken(tokenNode2, clientConfig)

	// all node requests from node1 and unknown node fail
	expectForbidden(t, getSecret(nodeanonClient))
	expectForbidden(t, getPVSecret(nodeanonClient))
	expectForbidden(t, getConfigMap(nodeanonClient))
	expectForbidden(t, getPVC(nodeanonClient))
	expectForbidden(t, getPV(nodeanonClient))
	expectForbidden(t, createNode2NormalPod(nodeanonClient))
	expectForbidden(t, createNode2MirrorPod(nodeanonClient))
	expectForbidden(t, deleteNode2MirrorPod(nodeanonClient))
	expectForbidden(t, createNode2(nodeanonClient))
	expectForbidden(t, updateNode2Status(nodeanonClient))
	expectForbidden(t, deleteNode2(nodeanonClient))

	expectForbidden(t, getSecret(node1Client))
	expectForbidden(t, getPVSecret(node1Client))
	expectForbidden(t, getConfigMap(node1Client))
	expectForbidden(t, getPVC(node1Client))
	expectForbidden(t, getPV(node1Client))
	expectForbidden(t, createNode2NormalPod(nodeanonClient))
	expectForbidden(t, createNode2MirrorPod(node1Client))
	expectForbidden(t, deleteNode2MirrorPod(node1Client))
	expectForbidden(t, createNode2(node1Client))
	expectForbidden(t, updateNode2Status(node1Client))
	expectForbidden(t, deleteNode2(node1Client))

	// related object requests from node2 fail
	expectForbidden(t, getSecret(node2Client))
	expectForbidden(t, getPVSecret(node2Client))
	expectForbidden(t, getConfigMap(node2Client))
	expectForbidden(t, getPVC(node2Client))
	expectForbidden(t, getPV(node2Client))
	expectForbidden(t, createNode2NormalPod(nodeanonClient))
	// mirror pod and self node lifecycle is allowed
	expectAllowed(t, createNode2MirrorPod(node2Client))
	expectAllowed(t, deleteNode2MirrorPod(node2Client))
	expectAllowed(t, createNode2(node2Client))
	expectAllowed(t, updateNode2Status(node2Client))
	expectAllowed(t, deleteNode2(node2Client))

	// create a pod as an admin to add object references
	expectAllowed(t, createNode2NormalPod(superuserClient))

	// unidentifiable node and node1 are still forbidden
	expectForbidden(t, getSecret(nodeanonClient))
	expectForbidden(t, getPVSecret(nodeanonClient))
	expectForbidden(t, getConfigMap(nodeanonClient))
	expectForbidden(t, getPVC(nodeanonClient))
	expectForbidden(t, getPV(nodeanonClient))
	expectForbidden(t, createNode2NormalPod(nodeanonClient))
	expectForbidden(t, updateNode2NormalPodStatus(nodeanonClient))
	expectForbidden(t, deleteNode2NormalPod(nodeanonClient))
	expectForbidden(t, createNode2MirrorPod(nodeanonClient))
	expectForbidden(t, deleteNode2MirrorPod(nodeanonClient))

	expectForbidden(t, getSecret(node1Client))
	expectForbidden(t, getPVSecret(node1Client))
	expectForbidden(t, getConfigMap(node1Client))
	expectForbidden(t, getPVC(node1Client))
	expectForbidden(t, getPV(node1Client))
	expectForbidden(t, createNode2NormalPod(node1Client))
	expectForbidden(t, updateNode2NormalPodStatus(node1Client))
	expectForbidden(t, deleteNode2NormalPod(node1Client))
	expectForbidden(t, createNode2MirrorPod(node1Client))
	expectForbidden(t, deleteNode2MirrorPod(node1Client))

	// node2 can get referenced objects now
	expectAllowed(t, getSecret(node2Client))
	expectAllowed(t, getPVSecret(node2Client))
	expectAllowed(t, getConfigMap(node2Client))
	expectAllowed(t, getPVC(node2Client))
	expectAllowed(t, getPV(node2Client))
	expectForbidden(t, createNode2NormalPod(node2Client))
	expectAllowed(t, updateNode2NormalPodStatus(node2Client))
	expectAllowed(t, deleteNode2NormalPod(node2Client))
	expectAllowed(t, createNode2MirrorPod(node2Client))
	expectAllowed(t, deleteNode2MirrorPod(node2Client))
}

func expectForbidden(t *testing.T, err error) {
	if !errors.IsForbidden(err) {
		_, file, line, _ := runtime.Caller(1)
		t.Errorf("%s:%d: Expected forbidden error, got %v", filepath.Base(file), line, err)
	}
}

func expectAllowed(t *testing.T, err error) {
	if err != nil {
		_, file, line, _ := runtime.Caller(1)
		t.Errorf("%s:%d: Expected no error, got %v", filepath.Base(file), line, err)
	}
}


text:
struct DebuggerEventSettings {
  DebuggerEventSettings()
      : breakOnDllLoad(false),
        breakOnDllUnload(false) {
  }

  DebuggerEventSettings(bool breakOnDllLoad, bool breakOnDllUnload)
      : breakOnDllLoad(breakOnDllLoad),
        breakOnDllUnload(breakOnDllUnload) {
  }

  bool breakOnDllLoad;
  bool breakOnDllUnload;
};

#endif


text:
=======
testSailsProject
================

testing out SAILS node.js MVC framework


text:
package org.robolectric.shadows;

import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

@SuppressWarnings({"UnusedDeclaration"})
@Implements(ColorMatrixColorFilter.class)
public class ShadowColorMatrixColorFilter {
  private ColorMatrix matrix;

  @Implementation
  public void __constructor__(ColorMatrix matrix) {
    this.matrix = matrix;
  }

  @Implementation
  public void __constructor__(float[] array) {
    this.matrix = new ColorMatrix(array);
  }

  @Override @Implementation
  public String toString() {
    return "ColorMatrixColorFilter<" + matrix + ">";
  }
}


text:
package xyz.rc24.bot.core.entities;

public interface GuildSettings
{
    CodeType getDefaultAddType();

    long getGuildId();

    String getPrefix();
}


text:
responsiveElement
=================

You can set up responsive breakpoints for each element differently


text:
Windows Quick Start
-------------------

1. Download COGS
~~~~~~~~~~~~~~~~

First, `Download COGS <http://ci.appveyor.com/api/projects/DanSmith/cogs/artifacts/Cogs.Console/bin/Release/netcoreapp2.0/Windows-CogsRelease.zip>`_
and extract the ZIP file.

COGS runs on the open source .NET Core platform. You will also need to
`Download .NET Core <https://download.microsoft.com/download/7/C/3/7C310A63-13AC-49A4-9666-4CB26388F852/dotnet-runtime-2.0.0-preview2-25407-01-win-x64.exe>`_
and install it.

2. Initialize a Model
~~~~~~~~~~~~~~~~~~~~~

Let's initialize a sample model. On the command line, switch to a directory
where you will create your model. Then, run the following.

.. code-block:: doscon

    c:\sandbox>  dotnet Cogs.Console.dll cogs-new MyModel

.. note::

   Instead of ``Cogs.Console.dll``, you may need to specify the full path. For example,
   it may be ``c:\cogs\Cogs.Console.dll``.

Let's see what's in the directory that COGS created.

.. code-block:: doscon

    C:\sandbox>  dir MyModel

The output of the directory listing shows us what COGS created.

.. code-block:: doscon

     Directory of C:\sandbox\MyModel

     08/09/2017  09:43 AM    <DIR>          .
     08/09/2017  09:43 AM    <DIR>          ..
     08/09/2017  09:43 AM    <DIR>          CompositeTypes
     08/09/2017  09:43 AM    <DIR>          ItemTypes
     08/09/2017  09:43 AM                17 readme.md
     08/09/2017  10:18 AM    <DIR>          Settings
     08/09/2017  09:55 AM    <DIR>          Topics

The folders and files listed above contain everything we need to specify our
model.

3. Generate a Schema and Documentation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Now, let's create an XML Schema to represent the skeleton model that COGS
created for us.

.. code-block:: doscon

    C:\sandbox>  dotnet Cogs.Console.dll publish-xsd MyModel output
    C:\sandbox>  dir output

Here is the output of the directory listing.

.. code-block:: doscon

       Directory of C:\sandbox\output

       08/09/2017  10:24 AM    <DIR>          .
       08/09/2017  10:24 AM    <DIR>          ..
       08/09/2017  10:24 AM             6,251 schema.xsd

The :file:`schema.xsd` file contains our XML schema.

.. note::

    You will need to install Python and Sphinx to generate documentation.
    For installation instructions see `here <http://www.sphinx-doc.org/en/stable/install.html>`_.

Next, let's generate some documentation using Sphinx.

.. code-block:: doscon

    C:\sandbox>  dotnet Cogs.Console.dll publish-sphinx MyModel output/sphinx
    C:\sandbox>  cd output/sphinx
    C:\sandbox>  make html
    C:\sandbox>  dir build/html

Here is the output of the directory listing.

.. code-block:: doscon

    Volume in drive C is Disk
    Directory of C:\sandbox\output\sphinx

    08/09/2017  10:19 AM               234 .buildinfo
    08/09/2017  10:19 AM    <DIR>          composite-types
    08/09/2017  10:19 AM             5,401 genindex.html
    08/09/2017  10:19 AM             6,667 index.html
    08/09/2017  10:19 AM    <DIR>          item-types
    08/09/2017  10:19 AM               277 objects.inv
    08/09/2017  10:19 AM             5,795 search.html
    08/09/2017  10:19 AM               768 searchindex.js
    08/09/2017  10:19 AM    <DIR>          topics
    08/09/2017  10:19 AM    <DIR>          _sources
    08/09/2017  10:19 AM    <DIR>          _static

If we open up the index.html file, we'll see the HTML documentation that COGS
and Sphinx generated.

4. Make the Model Yours
~~~~~~~~~~~~~~~~~~~~~~~

You are now up and running with COGS. Make the model your own by following
the :doc:`/modeler-guide/index`. Learn about publishing to other formats
in the :doc:`/technical-guide/index`.


text:
package adapt.model.panel.configuration.operation;

public enum ParameterType {
	IN, OUT, INOUT;
}


text:
@interface UIViewController (ActivityNavigationBar)
- (void) increaseActivityCount;
- (void) decreaseActivityCount;

//
- (void) checkNeedActicityShowAnimations;
- (void) dzActivityRemoveAnimation;
@end


text:
******************
Modelling problems
******************

.. _21_solver_label:

The solver
==========

The object :code:`Solver` is the key component. It is built as following: ::

 Solver solver = new Solver();

or::

 Solver solver = new Solver("my problem");

This should be the first instruction, prior to any other modelling instructions.
Indeed, a solver is needed to declare variables, and thus constraints.

Here is a list of the commonly used Solver API.

.. note::
    The API related to resolution are not described here but detailed in :ref:`Solving <31_solving_label>`.
    Similarly, API provided to add a constraint to the solver are detailed in :ref:`Constraints <23_constraints_label>`.
    The other missing methods are only useful for internal behavior.

Getters
-------

Variables
^^^^^^^^^

+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| **Method**                                    | **Definition**                                                                                |
+===============================================+==============================================================================================================================================================================+
| ``Variable[] getVars()``                      | Return the array of variables declared in the solver. It includes all type of variables declared, integer, boolean, etc. but also *fixed* variables such as ``Solver.ONE``.  |
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``int getNbVars()``                           | Return the number of variables involved in the solver.                                                                                |
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``Variable getVar(int i)``                    | Return the :math:`i^th` variable declared in the solver.                                                                                |
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``IntVar[] retrieveIntVars()``                | Extract from the solver variables those which are integer (ie whose *KIND* is set to *INT*, that is, including *fixed* integer variables and boolean variables).             |
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``retrieveBoolVars()``                        | Extract from the solver variables those which are boolean (ie whose *KIND* is set to *BOOL*, that is, including ``Solver.ZERO`` and ``Solver.ONE``).                         |
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``SetVar[] retrieveSetVars()``                | Extract from the solver variables those which are set (ie whose *KIND* is set to *SET*)                                                                                |
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``RealVar[] retrieveRealVars()``              | Extract from the solver variables those which are set (ie whose *KIND* is set to *REAL*)                                                                                |
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Constraints
^^^^^^^^^^^

+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| **Method**                                    | **Definition**                                                                                |
+===============================================+==============================================================================================================================================================================+
| ``Constraint[] getCstrs()``                   | Return the array of constraints posted in the solver.                                                                                |
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``getNbCstrs()``                              | Return the number of constraints posted in the solver.                                                                                |
+-----------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Other
^^^^^

+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| **Method**                                    | **Definition**                                                                                |
+===============================================+===================================================================================================+
| ``String getName()``                          | Return the name of the solver.                                                                    |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| ``IMeasures getMeasures()``                   | Return a reference to the measure recorder which stores resolution statistics.                    |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| ``AbstractStrategy getStrategy()``            | Return a reference to the declared search strategy.                                               |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| ``Settings getSettings()``                    | Return the current ``Settings`` used in the solver.                                               |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| ``ISolutionRecorder getSolutionRecorder()``   | Return the solution recorder.                                                                     |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| ``IEnvironment getEnvironment()``             | Return the internal *environment* of the solver, essential to manage backtracking.                |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| ``ObjectiveManager getObjectiveManager()``    | Return the objective manager of the solver, needed when an objective has to be optimized.         |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| ``ExplanationEngine getExplainer()``          | Return the explanation engine declared, (default is *NONE*).                                      |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| ``IPropagationEngine getEngine()``            | Return the propagation engine of the solver, which *orchestrate* the propagation of constraints.  |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+
| ``ISearchLoop getSearchLoop()``               | Return the search loop of the solver, which guide the search process.                             |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------+

Setters
-------

+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| **Method**                                    | **Definition**                                                                                |
+===============================================+===========================================================================================================================================================+
| ``set(Settings settings)``                    | Set the settings to use while modelling and solving.                                                                                |
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``set(AbstractStrategy... strategies)``       | Set a strategy to explore the search space. In case many strategies are given, they will be called in sequence.                                           |
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``set(ISolutionRecorder sr)``                 | Set a solution recorder, and erase the previous declared one (by default, ``LastSolutionRecorder`` is declared, it only stores the last solution found.   |
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``set(ISearchLoop searchLoop)``               | Set the search loop to use during resolution. The default one is a binary search loop.                                                                    |
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``set(IPropagationEngine propagationEngine)`` | Set the propagation engine to use during resolution. The default one is ``SevenQueuesPropagatorEngine``.                                                  |
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``set(ExplanationEngine explainer)``          | Set the explanation engine to use during resolution. The default one is ``ExplanationEngine`` which does nothing.                                         |
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``set(ObjectiveManager om)``                  | Set the objective manager to use during the resolution. *For advanced usage only*.                                                                        |
+-----------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+

Others
------

+-------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+
| **Method**                                | **Definition**                                                                                |
+===========================================+======================================================================================================================================+
| ``void plugMonitor(ISearchMonitor sm)``   | Put a :ref:`search monitor <44_monitors_label>` to react on search events (solutions, decisions, fails, ...).                        |
+-------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+
| ``Solver duplicateModel()``               | Duplicate the model associates with a solver, ie only variables and constraints, and return a new solver.                            |
+-------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+

.. _22_variables_label:

Declaring variables
===================

Principle
---------

A variable is an *unknown*, mathematically speaking.
The goal of a resolution is to *assign* a *value* to each declared variable.
In Constraint Programming, the *domain* --set of values that a variable can initially take-- must be defined.

Choco |version| includes five types of variables: ``IntVar``, ``BoolVar``, ``SetVar`` and ``RealVar``.
A factory is available to ease the declaration of variables: ``VariableFactory`` (or ``VF`` for short).
At least, a variable requires a name and a solver to be declared in.
The name is only helpful for the user, to read the results computed.

Integer variable
----------------

An integer variable is based on domain made with integer values.
There exists under three different forms: **bounded**, **enumerated** or **boolean**.
An alternative is to declare variable-based views.

.. important::

    It is highly advisable not to define domain like ``[Integer.MIN_VALUE, Integer.MAX_VALUE]``.
    Indeed, such domain definition may lead to :

    - incorrect domain size (``Integer.MAX_VALUE - Integer.MIN_VALUE +1 = 0``)
    - and to numeric overflow/underflow operations during propagation.

    If *undefined* domain is really required, the following range should be considered:
    ``[VariableFactory.MIN_INT_BOUND, VariableFactory.MAX_INT_BOUND]``.
    Such an interval defines `42949673` values, from `-21474836` to `21474836`.

Bounded variable
^^^^^^^^^^^^^^^^

Bounded (integer) variables take their value in :math:`[\![a,b]\!]` where :math:`a` and :math:`b` are integers such that :math:`a < b` (the case where :math:`a = b` is handled through views).
Those variables are pretty light in memory (the domain requires two integers) but cannot represent holes in the domain.

To create a bounded variable, the ``VariableFactory`` should be used: ::

 IntVar v = VariableFactory.bounded("v", 1, 12, solver);

To create an array of 5 bounded variables of initial domain :math:`[\![-2,8]\!]`: ::

 IntVar[] vs = VariableFactory.boundedArray("vs", 5, -2, 8, solver);

To create a matrix of 5x6 bounded variables of initial domain :math:`[\![0,5]\!]` : ::

 IntVar[][] vs = VariableFactory.boundedMatrix("vs", 5, 6, 0, 5, solver);

.. note::
   When using bounded variables, branching decisions must either be domain splits or bound assignments/removals.
   Indeed, assigning a bounded variable to a value strictly comprised between its bounds may results in disastrous performances,
   because such branching decisions will not be refutable.

Enumerated variable
^^^^^^^^^^^^^^^^^^^

Integer variables with enumerated domains, or shortly, enumerated variables, take their value in :math:`[\![a,b]\!]` where :math:`a` and :math:`b` are integers such that :math:`a < b` (the case where :math:`a = b` is handled through views) or in an array of ordered values :math:`{a,b,c,..,z}`, where :math:`a < b < c ... < z`.
Enumerated variables provide more information than bounded variables but are heavier in memory (usually the domain requires a bitset).

To create an enumerated variable, the ``VariableFactory`` should be used: ::

 IntVar v = VariableFactory.enumerated("v", 1, 12, solver);

which is equivalent to : ::

 IntVar v = VariableFactory.enumerated("v", new int[]{1,2,3,4,5,6,7,8,9,10,11,12}, solver);

To create a variable with holes in its initial domain: ::

 IntVar v = VariableFactory.enumerated("v", new int[]{1,7,8}, solver);

To create an array of 5 enumerated variables with same domains: ::

 IntVar[] vs = VariableFactory.enumeratedArray("vs", 5, -2, 8, solver);

 IntVar[] vs = VariableFactory.enumeratedArray("vs", 5, new int[]{-10, 0, 10}, solver);

To create a matrix of 5x6 enumerated variables with same domains: ::

 IntVar[][] vs = VariableFactory.enumeratedMatrix("vs", 5, 6, 0, 5, solver);

 IntVar[][] vs = VariableFactory.enumeratedMatrix("vs", 5, 6, new int[]{1,2,3,5,6,99}, solver);

.. admonition:: **Modelling**: Bounded or Enumerated?

    The choice of representation of the domain variables should not be done lightly.
    Not only the memory consumption should be considered but also the type of constraints used.
    Indeed, some constraints only update bounds of integer variables, using them with bounded variables is enough.
    Others make holes in variables' domain, using them with enumerated variables takes advantage of the *power* of the filtering algorithm.
    Most of the time, variables are associated with propagators of various *power*.
    The choice of domain representation must then be done on a case by case basis.

Boolean variable
^^^^^^^^^^^^^^^^

Boolean variables, BoolVar, are specific ``IntVar`` which take their value in :math:`[\![0,1]\!]`.

To create a new boolean variable: ::

 BoolVar b = VariableFactory.bool("b", solver);

To create an array of 5 boolean variables: ::

 BoolVar[] bs = VariableFactory.boolArray("bs", 5, solver);

To create a matrix of 5x6 boolean variables: ::

 BoolVar[] bs = VariableFactory.boolMatrix("bs", 5, 6, solver);

.. _22_variables_constant_label:

Constants
---------

Fixed-value integer variables should be created with a call to the following functions: ::

 VariableFactory.fixed("seven", 7, solver);

Or: ::

 VariableFactory.fixed(8, Solver)

where 7 and 8 are the constant values.
Not specifying a name to a constant enables the solver to use *cache* and avoid multiple occurrence of the same object in memory.

.. _22_variables_view_label:

Variable views
--------------

Views are particular integer variables, they can be used inside constraints.
Their domains are implicitly defined by a function and implied variables.

``x`` is a constant : ::

 IntVar x = VariableFactory.fixed(1, solver);

``x = y + 2`` : ::

 IntVar x = VariableFactory.offset(y, 2);

``x = -y`` : ::

 IntVar x = VariableFactory.minus(y);

``x = 3*y`` : ::

 IntVar x = VariableFactory.scale(y, 3);

Views can be combined together: ::

 IntVar x = VariableFactory.offset(VariableFactory.scale(y,2),5);

Set variable
------------

A set variable ``SV`` represents a set of integers.
Its domain is defined by a set interval: ``[S_E,S_K]``

- the envelope ``S_E`` is an ``ISet`` object which contains integers that potentially figure in at least one solution,
- the kernel ``S_K`` is an ``ISet`` object which contains integers that figure in every solutions.

Initial values for both ``S_K`` and ``S_E`` can be specified. If no initial value is given for ``S_K``, it is empty by default.
Then, decisions and filtering algorithms will remove integers from ``S_E`` and add some others to ``S_K``.
A set variable is instantiated if and only if ``S_E = S_K``.

A set variable can be created as follows: ::

    // z initial domain
    int[] z_envelope = new int[]{2,1,3,5,7,12};
    int[] z_kernel = new int[]{2};
    z = VariableFactory.set("z", z_envelope, z_kernel, solver);

Real variable
-------------

Real variables have a specific status in Choco |version|.
Indeed, continuous variables and constraints are managed with `Ibex solver`_.

A real variable is declared with two doubles which defined its bound: ::

 RealVar x = VariableFactory.real("y", 0.2d, 1.0e8d, 0.001d, solver);

Or a real variable can be declared on the basis of on integer variable: ::

 IntVar ivar = VariableFactory.bounded("i", 0, 4, solver);
 RealVar x = VariableFactory.real(ivar, 0.01d);

.. _Ibex solver: http://www.emn.fr/z-info/ibex/

.. _23_constraints_label:

Constraints and propagators
===========================

Principle
---------

A constraint is a logic formula that defines allowed combinations of values for its variables, that is, restrictions over variables that must be respected in order to get a feasible solution.
A constraint is equipped with a (set of) filtering algorithm(s), named *propagator(s)*.
A propagator **removes**, from the domains of the targeted variables, values that cannot correspond to a valid combination of values.
A solution of a problem is an assignment of all its variables simultaneously verifying all the constraints.

Constraint can be declared in *extension*, by defining the valid/invalid tuples, or in *intension*, by defining a relation between the variables.
Choco |version| provides various factories to declare constraints (see :ref:`Overview <12_overview_label>` to have a list of available factories).
A list of constraints available through factories is given in :ref:`List of available constraints <61_constraints_label>`.

.. admonition:: **Modelling**: Selecting the right constraints

    Constraints, through propagators, suppress forbidden values of the domain of the variables.
    For a given paradigm, there can be several propagators available.
    A widely used example is the `AllDifferent` constraints which holds that all its variables should take a distinct value in a solution.
    Such a rule can be formulated :

    - using a clique of inequality constraints,
    - using a global constraint: either analysing bounds of variable (*Bound consistency*) or analysing all values of the variables (*Arc consistency*),
    - or using a table constraint --an extension constraint which list the valid tuples.

    The choice must be made by not only considering the gain in expressiveness of stress compared to others.
    Indeed, the effective yield of each option can be radically different as the efficiency in terms of computation time.

    Many global constraints are used to model problems that are inherently NP-complete.
    And only a partial domain filtering variables can be done through a polynomial algorithm.
    This is for example the case of `NValue` constraint that one aspect relates to the problem of "minimum hitting set."
    Finally, the *global* nature of this type of constraint also simplifies the work of the solver in that it provides all or part of the structure of the problem.

If we want an integer variable ``sum`` to be equal to the sum of values of variables in the set ``atLeast``, we can use the ``IntConstraintFactory.sum`` constraint:

.. literalinclude:: /../../choco-samples/src/main/java/samples/integer/CarSequencing.java
   :language: java
   :lines: 104

A constraint may define its specific checker through the method ``isSatisfied()``, but most of the time the checker is given by checking the entailment of each of its propagators.
The satisfaction of the constraints' solver is done on each solution if assertions are enabled.

.. note::
   One can enable assertions by adding the ``-ea`` instruction in the JVM arguments.

It can thus be slower if the checker is often called (which is not the case in general).
The advantage of this framework is the economy of code (less constraints need to be implemented), the avoidance of useless redundancy when several constraints use the same propagators (for instance ``IntegerChanneling`` constraint involves ``AllDifferent constraint``), which leads to better performances and an easier maintenance.

.. note::

    To ease modelling, it is not required to manipulate propagators, but only constraints. However, one can define specific constraints by defining combinations of propagators and/or its own propagators. More detailed are given in :ref:`Defining its own constraint <46_define_constraint_label>`.

Choco |version| provides various types of constraints.

Available constraints
^^^^^^^^^^^^^^^^^^^^^

    :ref:`51_icstr_fal`, :ref:`51_icstr_tru`

    On one integer variable
:ref:`51_icstr_ari`,
:ref:`51_icstr_mem`,
:ref:`51_icstr_nmem`.

    On two integer variables
:ref:`51_icstr_abs`,
:ref:`51_icstr_ari`,
:ref:`51_icstr_dist`,
:ref:`51_icstr_squa`,
:ref:`51_icstr_tab`,
:ref:`51_icstr_tim`.

    On three integer variables
:ref:`51_icstr_ari`,
:ref:`51_icstr_dist`,
:ref:`51_icstr_div`,
:ref:`51_icstr_max`,
:ref:`51_icstr_min`,
:ref:`51_icstr_mod`,
:ref:`51_icstr_tim`.

    On an undefined number of integer variables
:ref:`51_icstr_elm`,
:ref:`51_icstr_sor`,
:ref:`51_icstr_tab`,
:ref:`51_icstr_mdd`.

:ref:`51_icstr_alld`,
:ref:`51_icstr_alldc`,
:ref:`51_icstr_alld_e0`,
:ref:`51_icstr_gcc`,

:ref:`51_icstr_amo`,
:ref:`51_icstr_atl`,
:ref:`51_icstr_atm`,
:ref:`51_icstr_cou`,
:ref:`51_icstr_nva`,

:ref:`51_icstr_booc`,
:ref:`51_icstr_ich`.

:ref:`51_icstr_cum`,
:ref:`51_icstr_diffn`.

:ref:`51_icstr_lexcl`,
:ref:`51_icstr_lexce`,
:ref:`51_icstr_lexl`,
:ref:`51_icstr_lexe`.

:ref:`51_icstr_max`,
:ref:`51_icstr_min`,

:ref:`51_icstr_sca`,
:ref:`51_icstr_sum`.

:ref:`51_icstr_creg`,
:ref:`51_icstr_mcreg`,
:ref:`51_icstr_reg`.

:ref:`51_icstr_cir`,
:ref:`51_icstr_pat`,
:ref:`51_icstr_scir`,
:ref:`51_icstr_spat`,
:ref:`51_icstr_tree`.

:ref:`51_icstr_bin`,
:ref:`51_icstr_kna`,
:ref:`51_icstr_tsp`.

    On one set variable
:ref:`51_scstr_note`.

    On two set variables
:ref:`51_scstr_dis`,
:ref:`51_scstr_off`.

    On an undefined number of set variables
:ref:`51_scstr_alldif`,
:ref:`51_scstr_alldis`,
:ref:`51_scstr_alleq`,
:ref:`51_scstr_bcha`,
:ref:`51_scstr_int`,
:ref:`51_scstr_inv`,
:ref:`51_scstr_mem`,
:ref:`51_scstr_nbe`,
:ref:`51_scstr_part`,
:ref:`51_scstr_sse`,
:ref:`51_scstr_sym`,
:ref:`51_scstr_uni`.

    On integer and set variables
:ref:`51_scstr_card`,
:ref:`51_scstr_elm`,
:ref:`51_scstr_icha`,
:ref:`51_scstr_max`,
:ref:`51_scstr_mem`,
:ref:`51_scstr_nme`,
:ref:`51_scstr_min`,
:ref:`51_scstr_sum`.

    On real variables
:ref:`51_rcstr_main`.

.. _512_constraint_things_to_know:

Things to know about constraints
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. _512_automaton:

Automaton-based Constraints
"""""""""""""""""""""""""""

:ref:`51_icstr_creg`, :ref:`51_icstr_mcreg` and :ref:`51_icstr_reg` rely on an automaton, declared implicitly or explicitly.
There are two kinds of ``IAutomaton`` : ``FiniteAutomaton``, needed for :ref:`51_icstr_creg`, and `CostAutomaton`, required for :ref:`51_icstr_mcreg` and :ref:`51_icstr_reg`.
A ``CostAutomaton`` is an extension of ``FiniteAutomaton`` where costs can be declared per transition.

``FiniteAutomaton`` embeds an ``Automaton`` object provided by the ``dk.brics.automaton`` library.
Such an automaton accepts fixed-size words made of multiple ``char`` s, but the regular constraints rely on ``IntVar`` s.
So,  mapping between ``char`` (needed by the underlying library) and ``int`` (declared in ``IntVar``) is made.
The mapping enables declaring regular expressions where a symbol is not only a digit between `0` and `9` but any positive number.
Then to distinct, in the word `101`, the symbols `0`, `1`, `10` and `101`, two additional ``char`` are allowed in a regexp: `<` and `>` which delimits numbers.

In summary, a valid regexp for the :ref:`51_icstr_creg`, :ref:`51_icstr_mcreg` and :ref:`51_icstr_reg` constraints
is a combination of **digits** and Java Regexp special characters.

.. admonition:: Examples of allowed RegExp

        ``"0*11111110+10+10+11111110*"``, ``"11(0|1|2)*00"``, ``"(0|<10> |<20>)*(0|<10>)"``.

.. admonition:: Example of forbidden RegExp

        ``"abc(a|b|c)*"``.

Posting constraints
-------------------

To be effective, a constraint must be posted to the solver. This is achieved using the method: ::

 solver.post(Constraint cstr);

Otherwise, if the ``solver.post(Constraint cstr)`` method is not called, the constraint will not be taken into account during the resolution process : it may not be satisfied in all solutions.

+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| **Method**                                    | **Definition**                                                                                |
+===============================================+=================================================================================================================================================================================+
| ``void post(Constraint c)``                   | Post **permanently** a constraint in the constraint network defined by the solver.                                                                                |
|                                               | The constraint is not propagated on posting, but is added to the propagation engine.                                                                                |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``void post(Constraint... cs)``               | Post **permanently** the constraints in the constraint network defined by the solver.                                                                                |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``void postTemp(Constraint c)``               | Post a constraint **temporary** in the constraint network.                                                                                |
|                                               | The constraint will active on the current sub-tree and be removed upon backtrack.                                                                                |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``void unpost(Constraint c)``                 | Remove permanently the constraint from the constraint network                                                                                |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Reifying constraints
--------------------

In Choco |version|, it is possible to reify any constraint. Reifying a constraint means associating it with a ``BoolVar`` to represent whether the constraint holds or not: ::

 BoolVar b = constraint.reify();

Or: ::

 BoolVar b = VF.bool("b", solver);
 constraint.reifyWith(b);

The first API ``constraint.reify()`` creates the variable, if it does not already exists, and reify the constraint.
The second API ``constraint.reifyWith(b)`` reify the constraint with the given variable.

.. note::

    A constraint is reified with only one boolean variable. If multiple reification are required, equality constraints will be created.

Reifying a constraint means that we allow the constraint not to be satisfied. Therefore, the constraint **should not** be posted.

The ``LogicalConstraintFactory`` enables to manipulate constraints through their reification.
For instance, we can represent the constraint "either ``x<0`` or ``y>42``" as the following: ::

 Constraint a = IntConstraintFactory.arithm(x,"<",0);
 Constraint b = IntConstraintFactory.arithm(y,">",42);
 Constraint c = LogicalConstraintFactory.or(a,b);
 solver.post(c);

This will actually reify both constraints ``a`` and ``b`` and say that at least one of the corresponding boolean variables must be true.
Note that only the constraint ``c`` is posted.

SAT constraints
---------------

A SAT solver is embedded in Choco. It is not  designed to be accessed directly.
The SAT solver is internally managed as a constraint (and a propagator), that's why it is referred as SAT constraint in the following.

.. important::

    The SAT solver is directly inspired by `MiniSat <http://minisat.se/>`_:cite:`EenS03`.
    However, it only propagates clauses, no learning or search is implemented.

On a call to any methods of ``solver.constraints.SatFactory``, the SAT constraint (and propagator) is created and automatically posted to the solver.

How to add clauses
^^^^^^^^^^^^^^^^^^
Clauses can be added with calls to the ``solver.constraints.SatFactory``.

    On one boolean variable
:ref:`51_lcstr_true`,
:ref:`51_lcstr_false`.

    On two boolean variables
:ref:`51_lcstr_booleq`,
:ref:`51_lcstr_boolle`,
:ref:`51_lcstr_boollt`,
:ref:`51_lcstr_boolnot`.

    Reification on two boolean variables
:ref:`51_lcstr_booliseqvar`,
:ref:`51_lcstr_boolislevar`,
:ref:`51_lcstr_boolisltvar`,
:ref:`51_lcstr_boolisneqvar`,
:ref:`51_lcstr_oreqvar`,
:ref:`51_lcstr_xoreqvar`,
:ref:`51_lcstr_andeqvar`.

    On undefined number of boolean variables
:ref:`51_lcstr_orarrayqualtrue`,
:ref:`51_lcstr_atmostnminusone`,
:ref:`51_lcstr_atmostone`,
:ref:`51_lcstr_andarrayequalfalse`,
:ref:`51_lcstr_andarrayeqvar`,
:ref:`51_lcstr_orarrayeqvar`,
:ref:`51_lcstr_clauses`,
:ref:`51_lcstr_maxboolarraylesseqvar`,
:ref:`51_lcstr_sumboolarraygreatereqvar`,
:ref:`51_lcstr_sumboolarraylesseqvar`.

.. _542_complex_clauses:

Declaring complex clauses
^^^^^^^^^^^^^^^^^^^^^^^^^

There is a convenient way to declare complex clauses by calling :ref:`51_lcstr_clauses`.
The method takes a ``LogOp`` and an instance of ``Solver`` as input, extracts the underlying clauses and add them to the ``SatFactory``.

A ``LogOp`` is an implementation of ``ILogical``, just like ``BoolVar``, and provides the following API:

  ``LogOp and(ILogical... operands)`` : create a conjunction, results in `true` if all of its operands are `true`.

  ``LogOp ifOnlyIf(ILogical a, ILogical b)``:  create a biconditional, results in `true` if and only if both operands are false or both operands are `true`.

  ``LogOp ifThenElse(ILogical a, ILogical b, ILogical c)`` : create an implication, results in `true` if ``a`` is `true` and ``b`` is `true` or ``a`` is ``false` and ``c`` is `true.

  ``LogOp implies(ILogical a, ILogical b)`` : create an implication, results in `true` if ``a`` is `false` or ``b`` is `true`.

  ``LogOp reified(BoolVar b, ILogical tree)`` : create a logical connection between ``b`` and ``tree``.

  ``LogOp or(ILogical... operands)`` : create a disjunction, results in `true` whenever one or more of its operands are `true`.

  ``LogOp nand(ILogical... operands)`` : create an alternative denial, results in if at least one of its operands is `false`.

  ``LogOp nor(ILogical... operands)`` : create a joint denial, results in `true` if all of its operands are `false`.

  ``LogOp xor(ILogical a, ILogical b)`` : create an exclusive disjunction, results in `true` whenever both operands differ.

  ``ILogical negate(ILogical l)`` : return the logical complement of `l`.

The resulting logical operation can be very verbose, but certainly more easy to declare: ::

    SatFactory.addClauses(LogOp.and(LogOp.nand(LogOp.nor(a, b), LogOp.or(c, d)), e));
    SatFactory.addClauses(LogOp.nor(LogOp.or(LogOp.nand(a, b), c), d));
    SatFactory.addClauses(LogOp.and(LogOp.nand(LogOp.nor(a, b), LogOp.or(c, d)), e));


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>gui.panels.monitoring.example</title>
<meta name="date" content="2014-03-31">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

gui.panels.monitoring.example

Classes

Main

StatisticMain


text:
      {{item.name}}

<audio controls style="position: fixed; bottom: 0; left: 0; right: 0;width: 100%;">
    Your browser does not support the audio element.
</audio>


text:
<?php
namespace Mw\Metamorph\Step;

use Mw\Metamorph\Domain\Model\MorphConfiguration;
use Mw\Metamorph\Domain\Service\MorphExecutionState;
use Mw\Metamorph\Transformation\AbstractTransformation;
use Mw\Metamorph\Transformation\Progressible;
use Mw\Metamorph\Transformation\ProgressibleTrait;
use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Package\PackageManagerInterface;
use TYPO3\Flow\Utility\Files;

class CreateResources extends AbstractTransformation implements Progressible {

	use ProgressibleTrait;

	/**
	 * @var PackageManagerInterface
	 * @Flow\Inject
	 */
	protected $packageManager;

	public function execute(MorphConfiguration $configuration, MorphExecutionState $state) {
		$this->startProgress(
			'Migrating resources',
			count($configuration->getResourceMappingContainer()->getResourceMappings())
		);

		foreach ($configuration->getResourceMappingContainer()->getResourceMappings() as $resourceMapping) {
			$targetFilePath = $resourceMapping->getTargetFile();
			$targetDirectory = dirname($targetFilePath);

			Files::createDirectoryRecursively($targetDirectory);
			copy($resourceMapping->getSourceFile(), $targetFilePath);

			$this->advanceProgress();
		}

		$this->finishProgress();
	}

}